diff --git a/thirdparty/jsmin/jsmin.php b/thirdparty/jsmin/jsmin.php index a1fc36dcc..4985c6246 100644 --- a/thirdparty/jsmin/jsmin.php +++ b/thirdparty/jsmin/jsmin.php @@ -220,6 +220,10 @@ class JSMin { * @return bool */ protected function isAlphaNum($c) { + // Check if $c is null or not a string + if (!is_string($c) || strlen($c) === 0) { + return false; // Return false if $c is not a valid character + } return ord($c) > 126 || $c === '\\' || preg_match('/^[\w\$]$/', $c) === 1; } diff --git a/workflow/public_html/lib/buildhash b/workflow/public_html/lib/buildhash new file mode 100644 index 000000000..54f0119d6 --- /dev/null +++ b/workflow/public_html/lib/buildhash @@ -0,0 +1 @@ +4d5932e1-7aa8f9de \ No newline at end of file diff --git a/workflow/public_html/lib/css/images/alfrescoIcon.png b/workflow/public_html/lib/css/images/alfrescoIcon.png new file mode 100644 index 000000000..a65ce4667 Binary files /dev/null and b/workflow/public_html/lib/css/images/alfrescoIcon.png differ diff --git a/workflow/public_html/lib/css/images/arrow-right-b.png b/workflow/public_html/lib/css/images/arrow-right-b.png new file mode 100644 index 000000000..e55df7c5c Binary files /dev/null and b/workflow/public_html/lib/css/images/arrow-right-b.png differ diff --git a/workflow/public_html/lib/css/images/arrow-right-d.png b/workflow/public_html/lib/css/images/arrow-right-d.png new file mode 100644 index 000000000..4eaf6617e Binary files /dev/null and b/workflow/public_html/lib/css/images/arrow-right-d.png differ diff --git a/workflow/public_html/lib/css/images/arrow-right-w.png b/workflow/public_html/lib/css/images/arrow-right-w.png new file mode 100644 index 000000000..d0cc4e4ae Binary files /dev/null and b/workflow/public_html/lib/css/images/arrow-right-w.png differ diff --git a/workflow/public_html/lib/css/images/backPM.png b/workflow/public_html/lib/css/images/backPM.png new file mode 100644 index 000000000..ea1475d11 Binary files /dev/null and b/workflow/public_html/lib/css/images/backPM.png differ diff --git a/workflow/public_html/lib/css/images/bg_dd.png b/workflow/public_html/lib/css/images/bg_dd.png new file mode 100644 index 000000000..aa8006075 Binary files /dev/null and b/workflow/public_html/lib/css/images/bg_dd.png differ diff --git a/workflow/public_html/lib/css/images/custom.png b/workflow/public_html/lib/css/images/custom.png new file mode 100644 index 000000000..c6cf69575 Binary files /dev/null and b/workflow/public_html/lib/css/images/custom.png differ diff --git a/workflow/public_html/lib/css/images/editcopy.png b/workflow/public_html/lib/css/images/editcopy.png new file mode 100644 index 000000000..b7c938a99 Binary files /dev/null and b/workflow/public_html/lib/css/images/editcopy.png differ diff --git a/workflow/public_html/lib/css/images/elbow-end.gif b/workflow/public_html/lib/css/images/elbow-end.gif new file mode 100644 index 000000000..406a88dff Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-end.gif differ diff --git a/workflow/public_html/lib/css/images/elbow-line.gif b/workflow/public_html/lib/css/images/elbow-line.gif new file mode 100644 index 000000000..e25ed03fb Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-line.gif differ diff --git a/workflow/public_html/lib/css/images/elbow-minus-nl.gif b/workflow/public_html/lib/css/images/elbow-minus-nl.gif new file mode 100644 index 000000000..928779e92 Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-minus-nl.gif differ diff --git a/workflow/public_html/lib/css/images/elbow-minus.gif b/workflow/public_html/lib/css/images/elbow-minus.gif new file mode 100644 index 000000000..97dcc7110 Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-minus.gif differ diff --git a/workflow/public_html/lib/css/images/elbow-plus-nl.gif b/workflow/public_html/lib/css/images/elbow-plus-nl.gif new file mode 100644 index 000000000..9f7f69880 Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-plus-nl.gif differ diff --git a/workflow/public_html/lib/css/images/elbow-plus.gif b/workflow/public_html/lib/css/images/elbow-plus.gif new file mode 100644 index 000000000..698de4793 Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow-plus.gif differ diff --git a/workflow/public_html/lib/css/images/elbow.gif b/workflow/public_html/lib/css/images/elbow.gif new file mode 100644 index 000000000..201c413e3 Binary files /dev/null and b/workflow/public_html/lib/css/images/elbow.gif differ diff --git a/workflow/public_html/lib/css/images/pmui-sprite-s05eefa0ad7.png b/workflow/public_html/lib/css/images/pmui-sprite-s05eefa0ad7.png new file mode 100644 index 000000000..d6e815c96 Binary files /dev/null and b/workflow/public_html/lib/css/images/pmui-sprite-s05eefa0ad7.png differ diff --git a/workflow/public_html/lib/css/images/submenu.gif b/workflow/public_html/lib/css/images/submenu.gif new file mode 100644 index 000000000..427b9dda2 Binary files /dev/null and b/workflow/public_html/lib/css/images/submenu.gif differ diff --git a/workflow/public_html/lib/css/images/ui-bg_flat_0_aaaaaa_40x100.png b/workflow/public_html/lib/css/images/ui-bg_flat_0_aaaaaa_40x100.png new file mode 100644 index 000000000..2399a7bb2 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_flat_0_aaaaaa_40x100.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_flat_55_fbec88_40x100.png b/workflow/public_html/lib/css/images/ui-bg_flat_55_fbec88_40x100.png new file mode 100644 index 000000000..bb07c6743 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_flat_55_fbec88_40x100.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_glass_75_d0e5f5_1x400.png b/workflow/public_html/lib/css/images/ui-bg_glass_75_d0e5f5_1x400.png new file mode 100644 index 000000000..9923cafb7 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_glass_75_d0e5f5_1x400.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_glass_85_dfeffc_1x400.png b/workflow/public_html/lib/css/images/ui-bg_glass_85_dfeffc_1x400.png new file mode 100644 index 000000000..be95f162d Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_glass_85_dfeffc_1x400.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_glass_95_fef1ec_1x400.png b/workflow/public_html/lib/css/images/ui-bg_glass_95_fef1ec_1x400.png new file mode 100644 index 000000000..4070c9712 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_glass_95_fef1ec_1x400.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png b/workflow/public_html/lib/css/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png new file mode 100644 index 000000000..69b24ff79 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_f5f8f9_1x100.png b/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_f5f8f9_1x100.png new file mode 100644 index 000000000..4170860f3 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_f5f8f9_1x100.png differ diff --git a/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_fcfdfd_1x100.png b/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_fcfdfd_1x100.png new file mode 100644 index 000000000..7fb62e89e Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-bg_inset-hard_100_fcfdfd_1x100.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_217bc0_256x240.png b/workflow/public_html/lib/css/images/ui-icons_217bc0_256x240.png new file mode 100644 index 000000000..8d2b7e570 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_217bc0_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_2e83ff_256x240.png b/workflow/public_html/lib/css/images/ui-icons_2e83ff_256x240.png new file mode 100644 index 000000000..84b601bf0 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_2e83ff_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_469bdd_256x240.png b/workflow/public_html/lib/css/images/ui-icons_469bdd_256x240.png new file mode 100644 index 000000000..5dff3f962 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_469bdd_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_6da8d5_256x240.png b/workflow/public_html/lib/css/images/ui-icons_6da8d5_256x240.png new file mode 100644 index 000000000..f7809f856 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_6da8d5_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_cd0a0a_256x240.png b/workflow/public_html/lib/css/images/ui-icons_cd0a0a_256x240.png new file mode 100644 index 000000000..ed5b6b093 Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_cd0a0a_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_d8e7f3_256x240.png b/workflow/public_html/lib/css/images/ui-icons_d8e7f3_256x240.png new file mode 100644 index 000000000..9b46228fb Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_d8e7f3_256x240.png differ diff --git a/workflow/public_html/lib/css/images/ui-icons_f9bd01_256x240.png b/workflow/public_html/lib/css/images/ui-icons_f9bd01_256x240.png new file mode 100644 index 000000000..f1f0531ad Binary files /dev/null and b/workflow/public_html/lib/css/images/ui-icons_f9bd01_256x240.png differ diff --git a/workflow/public_html/lib/css/mafe-4d5932e1-7aa8f9de.css b/workflow/public_html/lib/css/mafe-4d5932e1-7aa8f9de.css new file mode 100644 index 000000000..08ad39660 --- /dev/null +++ b/workflow/public_html/lib/css/mafe-4d5932e1-7aa8f9de.css @@ -0,0 +1,10734 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: -20px; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -30px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper ::selection { background-color: transparent } +.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget {} + +.CodeMirror-rtl pre { direction: rtl; } + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { + position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } + +.CodeMirror-hints { + position: absolute; + z-index: 10; + overflow: hidden; + list-style: none; + + margin: 0; + padding: 2px; + + -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); + -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); + box-shadow: 2px 3px 5px rgba(0,0,0,.2); + border-radius: 3px; + border: 1px solid silver; + + background: white; + font-size: 90%; + font-family: monospace; + + max-height: 20em; + overflow-y: auto; +} + +.CodeMirror-hint { + margin: 0; + padding: 0 4px; + border-radius: 2px; + white-space: pre; + color: black; + cursor: pointer; +} + +li.CodeMirror-hint-active { + background: #08f; + color: white; +} + +/** @class PMUI.panel.AccordionPanel */ +/** + * @var {color} + * The default background-color for AccordionPanel-header + */ +/** + * @var {color} + * The default background-color for AccordionPanel-body + */ +/** + * @var {color} + * The default background-color for AccordionPanel-body + */ +/** + * @var {color} + * The default background-color for AccordionPanel-header + */ +/** + * @var {color} + * The default background-color for AccordionItem-header + */ +/** + * @var {color} + * The default background-color for AccordionItem-header + */ +/** @class PMUI.ui.Button */ +/** + * @var {number} + * The font-size for the default button + */ +/** + * @var {color} + * The color for the default button + */ +/** + * @var {color} + * The background-color for the default button + */ +/** + * @var {number} + * The button-opacity for the default button + */ +/** + * @var {color} + * The button-opacity for the default button when the button is hover + */ +/** + * @var {color} + * The button-link for the default button + */ +/** + * @var {color} + * The button-link color for the default button when the button is hover + */ +/** + * @var {color} + * The button-background color for the default button when the button is disabled + */ +/** + * @var {color} + * The button-color for the default button when the button is disabled + */ +/** + * @var {color} + * The button-opacity for the default button when the button is disabled + */ +/** + * @var {color} + * The button-background color for the default button when the button is disabled and hover + */ +/** + * @var {color} + * The button-opacity for the default button when the button is disabled and hover + */ +/** @class PMUI.ui.Button */ +/** + * Creates a default pmui button. + * @param {class} $base base class + * @param {number} [$button_fontSize] font size + * @param {color} [$button_color] font color + * @param {button_backgroundColor} [$button_backgroundColor] background color + * @param {number} [$button_opacity] opacity + * @param {color} [$button-hover_opacity] button hover opacity + * @param {color} [$button-link_color] button link color + * @param {color} [$button-link-hover_color] button-link-hover_color + * @param {color} [$button-disabled_backgroundColor] button-disabled_backgroundColor + * @param {color} [$button-disabled_color] button-disabled_color + * @param {color} [$button-disabled_opacity] button-disabled_opacity + * @param {color} [$button-disabled-hover_backgroundColor] button-disabled-hover_backgroundColor + * @param {color} [$button-disabled-hover_opacity] button-disabled-hover_opacity + */ +/*@include font-face("SourceSansPro", font-files("SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf", "SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot", "SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff", "SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg"),"SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot"); +@include font-face("SourceSansProBold", font-files("SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf", "SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot", "SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff", "SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg"),"SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot");*/ +@font-face { + font-family: "Chivo"; + src: url('../fonts/Chivo/Chivo-Black.ttf?1608295698') format('truetype'), url('../fonts/Chivo/Chivo-BlackItalic.ttf?1608295698') format('truetype'), url('../fonts/Chivo/Chivo-Italic.ttf?1608295698') format('truetype'), url('../fonts/Chivo/Chivo-Regular.ttf?1608295698') format('truetype'); +} +@font-face { + font-family: "Montserrat"; + src: url('../fonts/Montserrat/Montserrat-Bold.ttf?1608295698') format('truetype'), url('../fonts/Montserrat/Montserrat-Regular.ttf?1608295698') format('truetype'); +} +.pmui-sprite-sprite, .pmui-sprite-arrow-down, .pmui-sprite-arrow-next, .pmui-sprite-arrow-previous, .pmui-sprite-arrow-right, .pmui-sprite-arrow-up, .pmui-sprite-delete-16, .pmui-sprite-error-64, .pmui-sprite-error, .pmui-sprite-grid-arrow-down, .pmui-sprite-grid-arrow-up, .pmui-sprite-help, .pmui-sprite-info-64, .pmui-sprite-information, .pmui-sprite-question-64, .pmui-sprite-success-64, .pmui-sprite-warning-64, .pmui-sprite-warning, .pmui-sprite-window-close, .pmui-accordion-item-closed, .pmui-accordion-item-expanded, .pmui-gridpanel-pagelink.pmui-gridpanel-nextbutton .pmui-icon, .pmui-gridpanel-pagelink.pmui-gridpanel-previousbutton .pmui-icon, .pmui-gridpanelcolumn.pmui-sortable.pmui-sort-asc .pmui-grid-sort-icon, .pmui-gridpanelcolumn.pmui-sortable.pmui-sort-desc .pmui-grid-sort-icon, .pmui-icon-help, .pmui-icon-info, .pmui-icon-error, .pmui-icon-warning, .pmui-messagewindow-icon-error, .pmui-messagewindow-icon-warning, .pmui-messagewindow-icon-info, .pmui-messagewindow-icon-success, .pmui-messagewindow-icon-confirm { + background-image: url('../img/pmui-sprite-s947c1ade08.png'); + background-repeat: no-repeat; +} + +.pmui-sprite-arrow-down { + background-position: 0 0; + height: 6px; + width: 11px; +} + +.pmui-sprite-arrow-next { + background-position: 0 -6px; + height: 13px; + width: 9px; +} + +.pmui-sprite-arrow-previous { + background-position: 0 -19px; + height: 13px; + width: 9px; +} + +.pmui-sprite-arrow-right { + background-position: 0 -32px; + height: 16px; + width: 16px; +} + +.pmui-sprite-arrow-up { + background-position: 0 -48px; + height: 6px; + width: 11px; +} + +.pmui-sprite-delete-16 { + background-position: 0 -54px; + height: 16px; + width: 16px; +} + +.pmui-sprite-error-64 { + background-position: 0 -70px; + height: 64px; + width: 64px; +} + +.pmui-sprite-error { + background-position: 0 -134px; + height: 16px; + width: 16px; +} + +.pmui-sprite-grid-arrow-down { + background-position: 0 -150px; + height: 6px; + width: 11px; +} + +.pmui-sprite-grid-arrow-up { + background-position: 0 -156px; + height: 6px; + width: 11px; +} + +.pmui-sprite-help { + background-position: 0 -162px; + height: 18px; + width: 18px; +} + +.pmui-sprite-info-64 { + background-position: 0 -180px; + height: 64px; + width: 64px; +} + +.pmui-sprite-information { + background-position: 0 -244px; + height: 16px; + width: 16px; +} + +.pmui-sprite-question-64 { + background-position: 0 -260px; + height: 64px; + width: 64px; +} + +.pmui-sprite-success-64 { + background-position: 0 -324px; + height: 64px; + width: 64px; +} + +.pmui-sprite-warning-64 { + background-position: 0 -388px; + height: 64px; + width: 64px; +} + +.pmui-sprite-warning { + background-position: 0 -452px; + height: 16px; + width: 16px; +} + +.pmui-sprite-window-close { + background-position: 0 -468px; + height: 14px; + width: 18px; +} + +/* Title assignment */ +.mafe-designer-assigment-title { + left: 15px !important; + font-weight: 700; + color: #2d3e50; + background: transparent; + margin-top: 15px; + text-align: left; +} + +.pmui-gridpanel.mafe-designer-assigment-grid input { + border: 1px solid #cdd2d5; +} + +.pmui-gridpanel-tableContainer { + overflow: inherit !important; +} + +.mafe-gridPanel-smooth .mafe-button-delete { + border: 1px solid white; +} + +.pmui-form .pmui-formpanel { + text-align: initial; + overflow: inherit !important; +} + +a.mafe-button-show { + background-color: red; + color: white; + background-color: #7CC2F9; + padding: 0 15px; + text-transform: none; +} + +a.mafe-button-edit { + background-color: #1fbc99; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-edit:hover { + background: #1ba385; + opacity: 1; +} + +a.mafe-button-edit-assign-no-hover { + background-image: url(../img/plus_.png); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: inherit; + background-color: #3397e1; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-edit-assign { + background-image: url(../img/arrow-grid.png); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: inherit; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-edit-assign:hover { + background-image: url(../img/arrow-grid.png); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: #e0e0e0; + opacity: 1; +} + +a.mafe-button-editstep { + background-color: #1fbc99; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-editstep:hover { + background: #1ba385; + opacity: 1; +} + +a.mafe-button-condition-trigger { + line-height: 18px !important; + height: 40px !important; + top: -2px !important; +} + +a.mafe-button-properties { + background-color: white; + padding: 0 5px; + text-transform: none; + line-height: 28px !important; + height: 28px !important; + color: #3397e1; + border: 1px solid #3397e1; + -moz-box-shadow: inset 0 0 0 1px #3397e1; + -webkit-box-shadow: inset 0 0 0 1px #3397e1; + box-shadow: inset 0 0 0 1px #3397e1; +} + +a.mafe-button-properties:hover { + background: #3397e1; + color: #fff; + opacity: 1; +} + +a.mafe-button-delete { + background-color: #e4655f; + border: 1px solid #e14333; + padding: 0 4px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-delete:hover { + background: #e14333; + opacity: 1; +} + +a.mafe-button-delete-assign-no-hover { + background-image: url("../img/close_.png"); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: inherit; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-delete-assign { + background-image: url("../img/close-grid.png"); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: inherit; + padding: 0 12px; + text-transform: none; + line-height: 26px !important; + height: 26px !important; + font-size: 14px; +} + +a.mafe-button-delete-assign:hover { + background-image: url("../img/close-grid.png"); + background-position: 99% 50%; + background-repeat: no-repeat; + background-color: #e0e0e0; + opacity: 1; +} + +#gridUsers .mafe-button-edit { + border: none; +} + +#gridUsers .mafe-button-edit, #gridUsers .mafe-button-delete { + border: none; +} + +a.mafe-button-create { + background-color: #1fbc99; + border: 1px solid #1ba385; + float: right; + padding: 0 15px 0 38px; + background: #1fbc99 url(../img/ico_mor2.png) no-repeat 5px center; + font-size: 16px; + margin-top: 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + margin-right: 2px; +} + +a.mafe-button-create:hover { + background-color: #1ba385; + opacity: 1; +} + +.mafe-webentry-link { + width: 485px; + overflow: hidden; + white-space: nowrap; + display: inline-block; + text-overflow: ellipsis; +} + +/* +a.mafe-button-create:hover{ + background: #1ba385 url(../img/ico_mor2.png) no-repeat 95% center; + padding: 0 45px 0 15px; + opacity : 1; + background-color: #1ba385; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +}*/ +.mafe-gridPanel { + margin: 0 2% 0 2%; +} + +/* MAFE ASSIGMENT*/ +.mafe-tabpanel-assignment { + padding-top: 1%; +} + +/* MAFE ASSIGMENT*/ +.mafe-panel { + text-align: left; +} + +.mafe-panel-assignment-white { + vertical-align: top; + padding-left: 2%; +} + +.mafe-panel-assignment-smooth { + vertical-align: top; + background-color: #eaebed; + padding-left: 2%; +} + +.mafe-designer-assigment-grid { + left: 14px !important; +} + +.mafe-designer-assigment-grid .pmui-gridpanel-tableContainer { + border: 1px solid #e5e5e5; + margin: 0 6% 0 0%; +} + +.mafe-designer-assigment-grid .pmui-gridpanel-table { + min-height: 0em; + overflow: hidden; +} + +.mafe-designer-assigment-grid .pmui-gridpanelcell-content { + padding: 0 0 0 0; + font-size: 14px; +} + +/*.mafe-designer-assigment-grid .mafe-button-edit { + background-color: #FFFFFF; +}*/ +/*.mafe-designer-assigment-grid .mafe-button-delete { + background-color: #FFFFFF; + border: 1px solid white; +}*/ +/* +.mafe-designer-assigment-grid tr:hover .mafe-button-delete { + background-color: #e53d3d; +} + +.mafe-designer-assigment-grid tr:hover .mafe-button-edit{ + background-color: #19bd9b; +}*/ +.mafe-panel-assignment-smooth .mafe-designer-assigment-grid { + background-color: #eaebed; +} + +/*option selector */ +.mafe-assigment-buttons { + margin: 9px 0 2px 0; + text-align: left; +} + +.mafe-assigment-buttons .pmui-switch-buttonitem { + margin-right: 7px; + border-radius: 0 0 0 0; + font-size: 11px; + border: 0px solid rgba(45, 62, 82, 0.1); + background-color: rgba(45, 62, 82, 0.1); + padding: 8px 15px; +} + +.mafe-assigment-buttons .pmui-switch-buttonitem:hover { + border: 0px solid rgba(45, 62, 82, 0.1); + border-radius: 0 0 0 0; +} + +.mafe-assigment-buttons .pmui-switch-buttonitem-selected { + font-size: 11px; + margin-right: 7px; + border-radius: 0 0 0 0; + background: #2d3e50; + border: 0px solid #2d3e50; + padding: 8px 15px; +} + +.mafe-assigment-buttons .pmui-switch-buttonitem-selected:hover { + border: 0px solid #2d3e50; + border-radius: 0 0 0 0; +} + +.pmui-switch-buttonitem.pmui-switch-icon-all .pmui-switch-buttonitem-icon { + height: 22px; + display: inline-block; + vertical-align: middle; +} + +.pmui-switch-buttonitem-selected.pmui-switch-icon-all .pmui-switch-buttonitem-icon { + height: 22px; + display: inline-block; + vertical-align: middle; +} + +.pmui-switch-buttonitem.pmui-switch-icon-user .pmui-switch-buttonitem-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: 0px -173px; + width: 33px; + height: 22px; + display: inline-block; + vertical-align: middle; +} + +.pmui-switch-buttonitem-selected.pmui-switch-icon-user .pmui-switch-buttonitem-icon { + background: url(../img/i_us_white.png) no-repeat; + background-position: 0px 0px; + width: 33px; + height: 22px; + display: inline-block; + vertical-align: middle; +} + +.pmui-switch-buttonitem.pmui-switch-icon-group .pmui-switch-buttonitem-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: 0px -113px; + width: 33px; + height: 22px; + display: inline-block; + vertical-align: middle; + margin: 0 6px; +} + +.pmui-switch-buttonitem-selected.pmui-switch-icon-group .pmui-switch-buttonitem-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: 0px -91px; + width: 33px; + height: 22px; + display: inline-block; + vertical-align: middle; + margin: 0 6px; +} + +.mafe-grid-panel-empty { + background: url(../img/i_group_big.png) no-repeat center; + height: none; + text-align: center; + padding-top: 120px; + box-sizing: border-box; +} + +.mafe-grid-panel-empty span { + font-size: 18px; + color: #777777; + font-style: normal; +} + +/* STEPS SUPERVISOR*/ +.mafe-panel-smooth { + background-color: #eaebed; +} + +.mafe-gridPanel-smooth .pmui-gridpanel-tableContainer { + border: 1px solid #e5e5e5; + margin: 0 6% 0 0%; +} + +.mafe-gridPanel-smooth .pmui-gridpanel-table { + min-height: 0em; +} + +.mafe-gridPanel-smooth .pmui-gridpanelcell-content { + padding: 0 0 0 0; + font-size: 14px; +} + +.mafe-gridPanel-smooth .mafe-button-edit { + background-color: #FFFFFF; +} + +.mafe-gridPanel-smooth .mafe-button-delete { + background-color: #FFFFFF; +} + +.mafe-gridPanel-smooth tr:hover .mafe-button-delete { + background-color: #e53d3d; +} + +.mafe-gridPanel-smooth tr:hover .mafe-button-edit { + background-color: #19bd9b; +} + +.pmui-accordion-item-header { + background: #3397e1 !important; + color: white; + border-color: #2481c5; + border-top: 1px solid #2081C8 !important; + border-bottom: 1px solid #068CED !important; +} + +.pmui-accordion-panel-body { + border: 1px solid #eee; + min-height: 200px; +} + +.pmui-accordion-item-container { + border-left: none !important; + border-right: none !important; +} + +.mafe-border-panel { + border: 1px solid #aeb5b6; +} + +.mafe-hidden-fields-panel { + list-style-type: none; + border: 1px solid #C0C0C0; + height: 50px; + width: 100%; + margin-top: 2px; + bottom: 1px; + overflow: auto; +} + +.mafe-hidden-fields-panel > * { + margin: 5px 0px 5px 5px; + padding: 2px; + float: left; + height: 34px; + width: 90px; + text-align: center; +} + +.mafe-hidden-fields-panel-name { + font-size: 10px; + border: 2px dotted #C0C0C0; + height: 15px; + margin: 3px; + line-height: 150%; + width: 80px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.mafe-hidden-fields-panel-label { + font-size: 9px; +} + +.mafe-hidden-fields-panel-label-isSelected { + background-color: gainsboro; +} + +.pmui-gridpanel-footer { + top: 0px; + left: 10px; + width: 95%; + height: 13px; +} + +#gridUsers .pmui-gridpanel-footer, +#gridUserList .pmui-gridpanel-footer, +#gridUsersAD .pmui-gridpanel-footer, +#gridUserListAD .pmui-gridpanel-footer { + position: initial; + top: inherit; + left: initial; + width: 95%; + margin-top: inherit; + height: 13px; + padding-top: 1px !important; + position: relative; +} + +.pmui-gridpanel-footer { + padding: 10px 10px; +} + +#gridUserList .pmui-gridpanel-tableContainer, +#gridUsers .pmui-gridpanel-tableContainer, +#gridUsersAD .pmui-gridpanel-tableContainer, +#gridUserListAD .pmui-gridpanel-tableContainer { + height: 245px; +} + +.pmui-gridpanel-total { + vertical-align: super; +} + +.content_controls ul li { + padding: 1px 0 !important; +} + +.pmui-gridpanel-footer-dinamic .pmui-gridpanel-pager { + padding: 0px; +} + +#gridUsers .pmui-gridpanel-searchload.load { + left: 310px; + top: 15px; +} + +.pmui-field-control-table td { + padding: 0px 45px 0px 20px !important; +} + +#gridAcceptedValues .pmui-gridpanel-footer { + top: 0px; + left: 10px; + width: 89%; + height: 13px; + padding-top: 1px !important; +} + +.clearlooks2 .mceFocus .mceTop .mceCenter { + background: #3397e1 !important; + color: white !important; + text-align: left !important; + padding: 10px 15px !important; + cursor: move !important; + font-size: 14px !important; + border-bottom: 1px solid #e5e5e5 !important; +} + +.clearlooks2 .mceBottom .mceCenter { + left: 5px !important; + width: 100% !important; + background: none !important; + background-color: white !important; +} + +.clearlooks2 { + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4) !important; +} + +.clearlooks2 a.mceResizeW { + background-color: white !important; +} + +.clearlooks2 a.mceResizeE { + background-color: white !important; +} + +.clearlooks2 .mceResize { + background: none !important; +} + +.clearlooks2 .mceClose { + background: url("../img/mafe-tools.png") no-repeat !important; + background-position: 0 -966px !important; + width: 20px !important; + height: 20px !important; + margin-top: -1px !important; + margin-right: 3px !important; + opacity: inherit !important; +} + +.clearlooks2 .mceClose:hover { + background: url("../img/mafe-tools.png") no-repeat !important; + background-position: 0 -1156px !important; +} + +.clearlooks2 .mceFocus .mceMax { + visibility: hidden; +} + +.clearlooks2 .mceFocus .mceMed { + background: url(../img/mafe-tools.png) no-repeat !important; + background-position: 0 -966px !important; + width: 27px !important; + height: 20px !important; + margin-top: -3px !important; +} + +.pmui-window-close { + margin-top: 0px !important; + outline: 0; +} + +.pmui-window-close .button-icon { + background: url("../img/mafe-tools.png") no-repeat !important; + background-position: 0 -966px !important; + width: 20px !important; + height: 20px !important; + margin-top: 0px !important; + opacity: inherit !important; +} + +.pmui-window-close .button-icon:hover { + background: url("../img/mafe-tools.png") no-repeat !important; + background-position: 0 -1156px !important; +} + +.pmui-gridpanel-pagelink.disable, +.pmui-gridpanel-pagelink.pmui-gridpanel-nextbutton.disable, +.pmui-gridpanel-pagelink.pmui-gridpanel-previousbutton.disable { + background: #D6D2D2; + color: #ffffff; + cursor: default; +} + +.mafe-button-submenu-option { + padding: 10px; + cursor: pointer; +} + +#buttonCriteriaField { + background: black; +} + +.mafe-activity-task-red { + background-color: #ce0615; + border: 1px solid #9f0614; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.list-suggest-item :hover { + background-color: #e0e0e0; +} + +.list-suggest-item.single-label :hover { + background-color: initial; + color: white; +} + +#ActionsByEmailPanel #customGridPanelControls { + border: 1px solid #c0c0c0; +} + +#customGridPanel .pmui-formpanel { + padding: 3px !important; +} + +#customGridPanelControls #firstPanel { + float: left; +} + +#thirdPanel .pmui-button { + padding: 5px 10px 5px 10px; + width: 75px !important; +} + +#thirdPanel .pmui-button { + padding: 5px 10px 5px 10px; + width: 75px !important; +} + +.propertiesTask-accordionItem { + right: 6px; + position: absolute; + display: inline-block; +} + +.propertiesTask-accordionButton { + padding: 0px 7px 3px 7px; + border: 1px solid; + box-sizing: border-box; +} + +.propertiesTask-accordionButton:hover { + background: #2481c5; +} + +.mafe-button-delete.propertiesTask-accordionButton, +.mafe-button-edit.propertiesTask-accordionButton { + line-height: initial !important; + border-right: none; + cursor: pointer; +} + +.mafe-button-edit.propertiesTask-accordionButton { + border: none; + border-right: 1px solid; +} + +#stepsAssignAccordion .pmui-accordion-item-header { + cursor: move; +} + +#idAssignment .pmui-accordion-item-header, +#idRouting .pmui-accordion-item-header { + cursor: auto; +} + +#stepsAssignTree .pmui-treepanel-list { + width: 300px; +} + +#stepsAssignTree .pmui-treepanel-node-collapsed { + cursor: move; +} + +#stepsMainContainer .pmui-field-label, +#stepsMainContainer .pmui-textannotationfield { + padding: 0px 10px 0px 10px; +} + +#stepsMainContainer .mafe-gridPanel { + margin: 0px !important; + padding: 0px 10px 0px 10px; + border: 1px solid; + border-color: #c0c0c0; +} + +#stepsMainContainer .pmui-accordion-item-body { + padding: 3px; + box-sizing: border-box; +} + +#stepsAssignAccordion .pmui-accordion-item-title { + width: 400px; + text-transform: none; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; +} + +#mainContainer #collapse-button { + width: 160px !important; +} + +.mafe-activity-task { + background-color: white; + border: 2px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 12px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.mafe-activity-task-disabled { + background-color: white; + border: 2px solid #a5adb4; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 12px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; +} + +.pmui-pmactivity .pmui-label span { + color: black; +} + +.pmui-pmevent .pmui-label span { + color: black; +} + +.pmui-pmgateway .pmui-label span { + color: black; +} + +.pmui-pmpool .pmui-label > first-child { + color: black; +} + +.rotateText { + color: #3b4753; +} + +.mafe-activity-subprocess { + background-color: white; + border: 4px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 12px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; +} + +.mafe-activity-subprocess-disabled { + background-color: white; + border: 3px solid #a5adb4; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 12px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; +} + +.pmui-pmactivity .pmui-label span { + color: black; +} + +.pmui-pmdata .pmui-label span { + color: black; +} + +.pmui-connection .pmui-label span { + color: black; +} + +.mafe-intersection { + bacground-color: black; +} + +.dragConnectHandler { + background-color: #FAB606; + border-radius: 50%; +} + +/*.dragConnectHandler.ui-draggable-dragging { + background: green; + z-index:200; +} +*/ +.dropConnectHandler { + background-color: #3b4753; + border-radius: 50%; +} + +/*.dropConnectHandler.ui-draggable-dragging { + background: #0317FC; + z-index:200; +}*/ +.dropConnectHandler.ui-state-active { + background: white; +} + +.dropConnectHandler .ui-state-hover { + background: green; +} + +.pmui { + font-family: Chivo-regular, sans-serif; + font-size: inherit; + padding: 0; +} + +.pmui-window-modal { + position: fixed; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.4); + left: 0; + top: 0; + z-index: 100; +} + +.pmui-window { + display: inline-block; + position: absolute; + background-color: #FFF; + -moz-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); + -webkit-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); +} + +.pmui-window-header { + background: #3397e1; + color: #FFF; + text-align: left; + padding: 10px 15px; + cursor: move; + font-size: 14px; + border-bottom: 1px solid #e5e5e5; +} + +.pmui-window-close.pmui-button { + border: none; + padding: 0px 6px; +} + +.pmui-window .pmui-window-close .button-icon:hover { + /* + //@include transform(scale(0.90)); + //@include opacity(0.7); + -moz-opacity:$window-close_hover-opacity; + -khtml-opacity:$window-close_hover-opacity; + opacity: $window-close_hover-opacity; + -ms-transform:$window-close_hover-transform; + -webkit-transform:$window-close_hover-transform; + -moz-transform:$window-close_hover-transform; + -o-transform:$window-close_hover-transform; + filter: alpha(opacity=70);*/ + color: #000; + text-decoration: none; + cursor: pointer; + opacity: .5; + filter: alpha(opacity=50); +} + +.pmui.pmui-window-close { + /*background: none;*/ + padding: 0; + cursor: pointer; + background: 0 0; + border: 0; + -webkit-appearance: none; + margin: -3px 0 0 0; +} +.pmui.pmui-window-close .button-icon { + /*display: inline-block; + height: 15px; + width: 18px;*/ + float: right; + font-size: 24px; + font-weight: 700; + color: #000; + text-shadow: 0 1px 0 #fff; + opacity: .2; + filter: alpha(opacity=20); + font-family: "Chivo"; +} +.pmui.pmui-window-close .button-label { + display: none; +} + +.pmui-window-title { + text-transform: none; + display: block; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + font-family: Chivo-regular, sans-serif; +} + +.pmui-window-body { + background-color: #FFF; + padding: 0px 0px; + overflow: auto; + text-align: inherit; + font-family: "SourceSansPro"; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.pmui-window-toolbar-top, +.pmui-window-toolbar-bottom { + overflow: hidden; + padding: 10px; + width: 100%; + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.pmui-window .pmui-buttonpanel .pmui-button { + margin-left: 5px; + margin-right: 5px; +} + + /* + .pmui-window .pmui-buttonpanel .pmui-link{ + margin-left:3.5px; + margin-right:3.5px; + padding: initial; + font-size : $window-panelButtons_fontSize; + } + .pmui-window .pmui-buttonpanel .pmui-textlabel { + margin-left : 3.5px; + margin-right : 3.5px + }*/ +.pmui-window .pmui-buttonpanel { + padding: 10px; + border-top: 1px solid #e5e5e5; +} + +.pmui-accordion-panel-header { + padding-top: 5px; + height: 25px; + background-color: #93c4ea; + text-align: center; + color: white; +} + +.pmui-accordion-panel-header span { + font-size: 14px; +} + +.pmui-accordion-panel-body { + border-top: 1px solid #c3d8e9; + border-bottom: 0px; + height: 357px; + width: auto; +} + +.pmui-accordion-panel-footer { + height: 0px; +} + +.pmui-accordion-panel-container { + overflow: auto; +} + +/* AccordionItem */ +.pmui-accordion-item-header { + background-color: #DFE8F6; + border-top: 1px solid #c3d8e9; + border-bottom: 1px solid #c3d8e9; + overflow-wrap: break-word; + padding: 2px; + color: white; + font-size: 14px; +} + +.pmui-accordion-item-body { + overflow: auto; + background-color: white; +} + +.pmui-accordion-item-footer { + overflow: auto; + background-color: white; +} + +.pmui-accordion-item-container { + height: auto; + width: auto; + border-left: 1px solid #c3d8e9; + border-right: 1px solid #c3d8e9; +} + +.pmui-accordion-item-iconbase { + background-repeat: no-repeat; + display: inline-block; + height: 16px; + margin: 0 5px 0 5px; + width: 16px; +} + +.pmui-accordion-item-closed { + background-position: 0 -32px; + height: 16px; + width: 16px; + opacity: 0.6; + filter: alpha(opacity=60); +} + +.pmui-accordion-item-expanded { + background-position: 0 0; + height: 6px; + width: 11px; + opacity: 0.6; + filter: alpha(opacity=60); +} + +.pmui-accordion .pmui-accordion-item-iconContainer { + cursor: pointer; + padding: 5px; +} + +.pmui-button { + font-size: 14px; + display: inline-block; + text-decoration: none; + padding: 11px 35px; + /*@include border-radius($PMUI-DEFAULT-BORDER-RADIUS);*/ + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + -ms-border-radius: 2px; + -o-border-radius: 2px; + border-radius: 2px; + background-color: #1e91d1; + color: #FFF; + text-align: center; + -webkit-transition: all .5s; + -moz-transition: all .5s; + -ms-transition: all .5s; + -o-transition: all .5s; + transition: all .5s; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.pmui-button.pmui-error:hover { + background: #e14333; + opacity: 1; + opacity: 1; +} + +.pmui-button.pmui-warning:hover { + background: #db9d22; + opacity: 1; + opacity: 1; +} + +.pmui-button.pmui-success:hover { + background: #1ba385; + opacity: 1; + opacity: 1; +} + +.pmui-button.pmui-info:hover { + background: #3397e1; + opacity: 1; + opacity: 1; +} + +.pmui-button.pmui-link { + color: #383838; + text-decoration: underline; + background: none; + padding: initial; +} + +.pmui-button.pmui-success { + color: #fff; + background-color: #1fbc99; + border: 1px solid #1ba385; +} + +.pmui-button.pmui-info { + color: #fff; + background-color: #3397e1; + border: 1px solid #3397e1; +} + +.pmui-button.pmui-warning { + color: #fff; + background-color: #EE9B26; + border: 1px solid #d58512; +} + +.pmui-button.pmui-error { + color: #fff; + background-color: #e4655f; + border: 1px solid #e14333; +} + +.pmui-button.pmui-disabled { + background-color: #BEBEBE; + color: #F7F7F7; + opacity: 0.8; + pointer-events: none; + cursor: default; + border: 1px solid #AAA8A8; +} + +.button-disabled:hover { + opacity: 0.8; +} + +.pmui-button.pmui-link.pmui-disabled { + background-color: inherit; + color: #CCC8C8; + opacity: inherit; + border: inherit; +} + +.pmui-flashmessage { + color: #DDD; + background: rgba(0, 0, 0, 0.8); + padding: 12px; + text-align: center; +} + +.pmui-flashmessage.pmui-info { + background: rgba(30, 145, 209, 0.8); +} + +.pmui-flashmessage.pmui-error { + background: rgba(255, 0, 0, 0.8); +} + +.pmui-flashmessage.pmui-success { + background: rgba(0, 143, 97, 0.8); +} + +.pmui-flashmessage-list { + margin: 0; + -webkit-padding-start: 20px; + -moz-padding-start: 20px; +} + +.pmui-optionsselectorfield a { + text-decoration: none; +} + +.pmui-switch-buttonitem { + background-color: #ebebeb; + border: 1px solid #d3d3d3; + color: #555555; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + display: inline-block; + position: relative; + padding: 5px 10px 5px 10px; + line-height: normal; + cursor: pointer; + margin: 0em; + vertical-align: middle; + text-align: center; + text-transform: none; + text-indent: 0px; + text-shadow: none; + overflow: visible; + word-spacing: normal; + font: -webkit-small-control; + letter-spacing: normal; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; +} + +.pmui-switch-buttonitem:hover { + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + border: 1px solid #d3d3d3; + color: #333; + background-color: #d8d8d8; + border-color: #adadad; +} + +.pmui-switch-buttonitem-selected { + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + border: 1px solid #3276B1; + background-color: #3276B1; + color: #ffffff; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + display: inline-block; + position: relative; + padding: 5px 10px 5px 10px; + line-height: normal; + cursor: pointer; + margin: 0em; + vertical-align: middle; + text-align: center; + text-transform: none; + text-indent: 0px; + text-shadow: none; + overflow: visible; + word-spacing: normal; + font: -webkit-small-control; + letter-spacing: normal; +} + +.pmui-switch-buttonitem-disabled { + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + border: 1px solid #d3d3d3; + background-color: #e5e5e5; + color: #d3cfcf; + cursor: default; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + border-top-right-radius: 4px; + border-top-left-radius: 4px; + display: inline-block; + position: relative; + padding: 5px 10px 5px 10px; + line-height: normal; + cursor: pointer; + margin: 0em; + vertical-align: middle; + text-align: center; + text-transform: none; + text-indent: 0px; + text-shadow: none; + overflow: visible; + word-spacing: normal; + font: -webkit-small-control; + letter-spacing: normal; +} + +.pmui-menu { + font-family: Tahoma, Arial, Verdana; + font-size: 12px; + border: 1px solid #d5d8dc; + display: inline-block; + list-style: none; + background: #F0F0F0; + margin: 0; + padding: 0; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); +} + +.pmui-menuoption { + position: relative; + -moz-transition: all 0.3s; + -o-transition: all 0.3s; + -webkit-transition: all 0.3s; + transition: all 0.3s; +} + +.pmui-menuoption:hover { + background: #444; +} + +.pmui-menuoption.pmui-disabled:hover { + background: none; +} + +.pmui-menuoption-title { + display: block; + padding: 0.4em 0.6em; + text-decoration: none; + color: #2d3e50; +} + +.pmui-disabled .pmui-menuoption-title { + cursor: default; +} + +.pmui-menuoption-text { + line-height: 1.84em; + padding-right: 15px; + white-space: nowrap; +} + +.pmui-disabled .pmui-menuoption-text { + color: #bbb; +} + +.pmui-menuoption:hover > .pmui-menuoption-title { + color: #F0F0F0; +} + +.pmui-menuoption.pmui-father > .pmui-menuoption-title { + background: url(images/arrow-right-b.png) no-repeat right content-box; +} + +.pmui-menuoption.pmui-father:hover > .pmui-menuoption-title { + background-image: url(images/arrow-right-w.png); +} + +.pmui-menuoption.pmui-father.pmui-disabled > .pmui-menuoption-title, +.pmui-menuoption.pmui-father.pmui-disabled:hover > .pmui-menuoption-title { + background-image: url(images/arrow-right-d.png); +} + +.pmui-menuseparatoritem { + border-top: 1px solid #d8d8d8; + border-bottom: 1px solid #fff; +} + +.pmui-menuoption:hover > .pmui-menu { + display: inline-block; +} + +.pmui-menuoption.pmui-disabled:hover > .pmui-menu { + display: none; +} + +.pmui-menu .pmui-menu { + display: none; + position: absolute !important; + left: 100% !important; + top: 0 !important; +} + +.pmui-datepicker { + font-size: 12px; + width: 200px; + position: absolute; + border: #888 1px solid; + color: #000; + background-color: #F8F8F8; + -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.5); + box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.5); +} + +.pmui-datetimecontrol { + border: 1px solid #ccc; +} + +.pmui-datepicker input { + border: #888 1px solid; + font-size: 0.8em; + text-align: center; + width: 100%; +} + +.pmui-datepicker a { + text-decoration: none; + color: inherit; +} + +.pmui-datepicker-header { + font-size: 1.2em; + background-color: #F8F8F8; +} + +.pmui-datepicker-head-table { + width: 100%; +} + +.pmui-datepicker-month-selector select, +.pmui-datepicker-year-selector select { + background: none; + border: none; +} + +.pmui-datepicker-month-selector { + text-align: left; +} + +.pmui-datepicker-year-selector { + text-align: right; +} + +.pmui-datepicker-table { + width: 100%; +} + +.pmui-datepicker-table tr { + margin: 0; + padding: 0; +} + +.pmui-datepicker-table td { + text-align: center; + background: #F0F0F0; + padding: 1px; +} + +.pmui-datepicker-table td a { + display: block; + background-color: #F8F8F8; + color: #000; +} + +.pmui-datepicker-table td a:hover, +.pmui-datepicker-table td .selected { + background-color: #D0D0D0; +} + +.pmui-datepicker-table thead th { + font-size: 0.8em; + color: #000; + background-color: #F8F8F8; +} + +.pmui-datepicker-disabled-date { + color: #888; +} + +.pmui-datepicker-footer { + padding: 4px; +} + +.pmui-datepicker-footer div { + display: inline-block; +} + +.pmui-datepicker-button { + font-family: Arial; + background-color: #C0C0C0; + padding: 1px; + border: solid #888; + border-width: 1px; + margin: 1px; + /*color:$datepicker-button_color;*/ +} + +.pmui-gridpanel { + background-color: #FFF; + font-size: 14px; + vertical-align: top; + font-family: "SourceSansPro", Arial, Tahoma, Verdana; +} + +.pmui-gridpanel-tableContainer { + border: 0px solid #e5e5e5; +} + +.pmui-gridpanel-table { + border-collapse: collapse; + min-height: 3em; + background-color: #fff; + width: 100%; + font-size: 14px; +} + +.pmui-gridpanelcolumn { + border-right: 2px solid #fff; + /*padding: 5px 10px;*/ + color: #fff; + font-size: 14px; + background: #3397e1; +} + +.pmui-gridpanelcell { + border-right: 2px solid #fff; +} + +.pmui-gridpanelcolumn.pmui-sortable { + cursor: pointer; +} + +.pmui-gridpanel.pmui-sortable.pmui-sort-asc, +.pmui-gridpanel.pmui-sortable.pmui-sort-desc { + background-repeat: no-repeat; + background-position: right; +} + +.pmui-gridpanelrow { + border-bottom: 1px solid #e5e5e5; + line-height: auto; +} + +.pmui-gridpanelrow.ui-draggable > .pmui-gridpanelcell:first-child, +.pmui-gridpanel-tbody.ui-sortable .pmui-gridpanelrow > .pmui-gridpanelcell:first-child { + background-image: url(images/bg_dd.png); + background-position: 2px center; + background-repeat: no-repeat; +} + +.pmui-gridpanelrow.ui-draggable, +.pmui-gridpanel-tbody.ui-sortable .pmui-gridpanelrow { + cursor: move; +} + +.pmui-gridpanelrow:hover { + background: #e0e0e0; +} + +.pmui-gridpanel-pager { + display: inline-block; + margin: 0; +} + +.pmui-gridpanel-gotoPage { + width: 40px; + margin: 0 2px 0 2px; + height: 20px; + text-align: center; + border: 1px solid #ddd; +} + +.pmui-gridpanel-footer.pmui-gridpanel-total { + vertical-align: super; + font-size: 13px; + padding: 2px; +} + +.pmui-gridpanel-pager-current { + text-decoration: none; + float: left; + color: #0493E5; + font-size: 14px; + line-height: 26px; + font-weight: normal; + text-align: center; + border: 1px solid #ddd; + min-width: 14px; + padding: 0 11px; + margin: 0 5px 0 0; + background: #FFF; + background: #0493E5; + color: #FFF; + cursor: default; + margin-left: -7px; +} + +.pmui-gridpanel-pager-ellipse { + background: none; + border: none; + border-radius: 0; + box-shadow: none; + font-weight: bold; + cursor: default; + text-decoration: none; + float: left; + color: #0493E5; + font-size: 14px; + line-height: 26px; + font-weight: normal; + text-align: center; + border: 1px solid #ddd; + min-width: 14px; + padding: 0 7px; + margin: 0 5px 0 0; + background: #FFF; + margin-left: -7px; +} + +.pmui-gridpanel-pager li a { + text-decoration: none; + float: left; + color: #0493E5; + font-size: 14px; + line-height: 26px; + font-weight: normal; + text-align: center; + border: 1px solid #ddd; + min-width: 14px; + padding: 0 11px; + margin: 0 5px 0 0; + background: #FFF; + margin-left: -7px; +} + +.pmui-gridpanel-pager li a:hover { + text-decoration: none; + background: #0493E5; + color: #FFF; +} + +.pmui-gridpanel-pager li { + display: inline-block; + margin: 0 1px; +} + +.pmui-gridpanel-pagelink { + float: left; + display: block; + color: #2d3e50; + padding: 4px 7px; + height: 13px; +} + +.pmui-gridpanel-pagelink, +.pmui-gridpanel-pagelink.pmui-gridpanel-nextbutton, +.pmui-gridpanel-pagelink.pmui-gridpanel-previousbutton { + text-decoration: none; + font-size: 12px; +} + +.pmui-gridpanel-pagelink.pmui-gridpanel-nextbutton .pmui-icon { + background-position: 0 -6px; + height: 13px; + width: 9px; +} + +.pmui-gridpanel-pagelink.pmui-gridpanel-previousbutton .pmui-icon { + background-position: 0 -19px; + height: 13px; + width: 9px; +} + +.pmui-gridpanel-pagelink { + float: left; + display: block; + color: #2d3e50; + padding: 4px 7px; + font-size: 12px; +} + +.pmui-gridpanel-pagelink:hover { + filter: alpha(opacity=0.7); + -moz-opacity: 0.7; + -khtml-opacity: 0.7; + opacity: 0.7; +} + +.pmui-gridpanel-pagelink.pmui-active { + color: #fff; + background: #2d3e50; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; +} + +.pmui-gridpanel-toolbar { + padding: 5px 0px; + text-align: left; + height: 40px; + margin: 4px 0 4px 0; +} + +.pmui-gridpanel-footer { + text-align: center; + padding: 10px 20px; +} + +.pmui-gridpanel-statusbar { + text-align: left; + font-size: 12px; + margin-top: 5px; +} + +.pmui-gridpanelcell-content, +.pmui-gridpanelColumn-title { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + position: relative; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.pmui-gridpanelcell-content { + display: inline-block; + color: #333; + text-align: left; + padding: 1px 5px 1px 5px; + margin-left: 5px; +} + +.pmui-gridpanelColumn-title { + display: block; + padding: 9px 5px; + text-align: left; + font-weight: initial; +} + +.pmui-grid-sort-icon { + position: absolute; + width: 11px; + height: 1em; + right: 5px; + display: none; + top: 9px; +} +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-asc .pmui-grid-sort-icon { + background-position: 0 -150px; + height: 6px; + width: 11px; +} +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-desc .pmui-grid-sort-icon { + background-position: 0 -156px; + height: 6px; + width: 11px; +} + +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-asc .pmui-gridpanelColumn-title, +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-desc .pmui-gridpanelColumn-title { + padding-right: 20px; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; +} +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-asc .pmui-gridpanelColumn-title:hover, +.pmui-gridpanelcolumn.pmui-sortable.pmui-sort-desc .pmui-gridpanelColumn-title:hover { + filter: alpha(opacity=0.7); + -moz-opacity: 0.7; + -khtml-opacity: 0.7; + opacity: 0.7; +} + +.pmui-gridpanelcolumn.pmui-sortable .pmui-grid-sort-icon { + display: inline-block; +} + +.pmui-active-row { + background: antiquewhite; +} + +.pmui-gridpanel-emptyrow td { + padding: 0.5em; + font-style: italic; +} + +.pmui-gridpanelrow-deleteButton { + width: 16px; + height: 16px; + padding: 2px; + background: #e0e0e0; + position: absolute; + top: -16px; + right: 0px; + -moz-border-radius: 100% 100% 0px 0px; + -webkit-border-radius: 100% 100% 0px 0px; + border-radius: 100% 100% 0px 0px; +} + +.pmui-gridpanelrow-deleteButton a { + display: inline-block; + /*@include pmui-sprite-sprite(delete-16);*/ +} + +.pmui-gridpanel-searchload.load { + background: url(../img/loading.gif) no-repeat center; + background-size: contain; + height: 20px; + width: 20px; + position: absolute; +} + +.pmui-tabpanel { + background: none; +} + +.pmui-tabpanel-container { + background: #FFF; + overflow: visible !important; +} + +.pmui-tabpanel-tabs { + padding: 0; + margin: 0; + border-bottom: 1px solid #ddd; + width: 92%; +} + +.pmui-tabitem { + font-size: 14px; + font-weight: normal; + text-transform: none; + margin: 0 4px; +} + +.pmui-tab-ref { + display: block; + color: #337ab7; + text-decoration: none; + background: #FFF; + padding: 0.6em 0.9em; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.pmui-tabitem.pmui-active .pmui-tab-ref { + color: #555; + background: FFF; + border: 1px solid #ddd; + border-top: 3px solid #3397e1; +} + +.pmui-tabitem:hover .pmui-tab-ref { + color: #555; + background: #FFF; +} + +.pmui-tab_title { + text-overflow: ellipsis; + white-space: nowrap; + overflow: inherit; + display: inline-block; +} + +.pmui-tabpanel-left .pmui-tabpanel-tabs { + border-bottom: 0; + padding-right: 6px; +} +.pmui-tabpanel-left .pmui-tabitem { + clear: both; + text-align: left; + /*width: 100%;*/ + margin: 2px 0; +} + +.pmui-collapsibleBar { + width: 5px; + background: white; + border-left: 1px solid #dadfe4; +} + +.pmui-tab-icon { + float: left; + width: auto; + height: 20px; +} + +.pmui-textcontrol, +.pmui-dropdownlistcontrol, +.pmui-textareacontrol, +.pmui-passwordcontrol, +.pmui-uploadcontrol, +.pmui-datetimecontrol { + font-size: 14px; + border-radius: 2px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + background: #fff; + display: inline-block; + text-align: 'left'; + padding: 4px 6px; + color: #000; + border: 1px solid #adafb2; +} + +.pmui-textcontrol, .pmui-passwordcontrol { + color: #000; +} + +.pmui-textcontrol:-ms-input-placeholder, .pmui-passwordcontrol:-ms-input-placeholder { + color: #AAAAAA; +} + +select.pmui-dropdownlistcontrol { + height: 36px; +} + +.pmui-textareacontrol { + width: 100%; +} + +.pmui-selectablecontrol span { + font-size: 14px; +} + +.pmui-field-label { + display: block; + text-align: left; + width: 160px; + padding: 6px 20px 6px 10px; + color: #2d3e50; + font-size: 14px; + box-sizing: border-box; +} + +.pmui-field { + padding: 4px 0; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + background: none; +} + +.pmui-field-label, +.pmui-field-control { + /*float: left;*/ + display: inline-block; + text-align: left; + margin-right: 5px; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.pmui-textannotationfield { + color: #2d3e50; +} + +.pmui-textannotationfield .pmui-field-label { + margin: 0px; + color: inherit; +} + +.pmui-field-control-er { + color: #f00; +} + +.pmui-field-required { + color: #e84c3d; + padding-top: 3px; + text-align: center; +} + +.pmui-field .pmui-textlabel { + clear: both; + color: #fff; + font-size: 12px; + background: #F5736D; + padding: 4px 10px; + display: inline-block; +} + +.pmui-field-colon { + color: #000; +} + +.pmui-field .error { + outline: 1px solid #ecc3c2; + border: 1px solid white; +} + +.pmui-field-control-table { + display: inline-block; +} + +.pmui-field-control-table { + border: 1px solid #e7e7e7; + padding: 0px; +} + +.pmui-field-control-table td { + padding: 0px 45px 0px 0px; +} + +.pmui-field-message { + text-align: left; + position: absolute; + z-index: 100; +} + +.pmui.pmui-textannotationfield { + clear: both; +} + +.pmui-tooltip .pmui-icon { + background-repeat: no-repeat; + display: inline-block; + margin-left: 3px; + float: right; + margin-top: 5px; +} + +.pmui-icon-help { + background-position: 0 -162px; + height: 18px; + width: 18px; +} + +.pmui-icon-info { + background-position: 0 -244px; + height: 16px; + width: 16px; +} + +.pmui-icon-error { + background-position: 0 -134px; + height: 16px; + width: 16px; +} + +.pmui-icon-warning { + background-position: 0 -452px; + height: 16px; + width: 16px; +} + +.pmui-tooltip { + margin-left: 5px; + border-radius: 1em; +} + +.pmui-tooltip-message { + margin: 0 5px 0 3px; +} + +.pmui .pmui-tooltip-mode-normal .pmui-tooltip-message { + font-size: 0.8em; +} + +.pmui-field-message-container { + display: block; +} + +.pmui-tooltip-category-error { + color: #F00; +} + +.ui-tooltip { + max-width: 350px !important; +} + +.pmui-form { + background-color: white; +} + +.pmui-form-title, +.pmui-form-footer { + text-align: center; +} + +.pmui-form-header { + padding: 0.4em; + background-color: white; +} + +.pmui-form-title { + font-size: 1.2em; + margin: 0; + line-height: 100%; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: black; +} + +.pmui-form fieldset { + border-color: #c7c7c7; + color: #2d3e50; +} + +/*.pmui-form .pmui-buttonpanel a { + color: #fff; + font-size: 16px; + background: $form-buttonBar_background; + margin-right: 10px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + padding: 0px 15px; + border: 1px solid #2D9663; +} +.pmui .pmui-buttonpanel .button-link{ + color : #000000; + text-decoration: underline; + background : inherit; + padding : 0px 5px 0px 5px; +}*/ +.pmui-form .pmui-formpanel { + text-align: initial; +} + +.pmui-treepanel { + display: inline-block; + height: 360px; +} + +.pmui-treepanel-list { + list-style: none; + margin: 0; + padding: 0; + vertical-align: top; +} + +.pmui-treepanel-node .pmui-treepanel-list { + margin-left: 18px; +} + +.pmui-treepanel-node-title { + text-decoration: none; + color: #000; +} + +.pmui-treepanel-node { + background: url(images/elbow-line.gif) repeat-y left top; + list-style-type: none; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + text-align: left; +} + +.pmui-treepanel, +.pmui-treepanel-node { + font-size: 14px; + background: inherit; +} + +.pmui-treepanel-node, +.pmui-treepanel-list > .pmui-treepanel-node:last-child { + background: url(images/elbow-end.gif) no-repeat left top; +} + +.pmui-treepanel-node-icon { + display: inline-block; + margin-right: 3px; +} + +.pmui-treepanel-node-elbow { + width: 16px; + margin-right: 3px; + display: inline-block; +} + +.pmui-treepanel-emptymessage { + font-style: italic; +} + +.pmui-treepanel-toolbar { + margin: 1em 0.5em; +} + +.pmui-treepanel .pmui-treepanel-node { + background: url(images/elbow-line.gif) repeat-y top left; +} + +.pmui-treepanel-node .pmui-treepanel-node-elbow { + background: url(images/elbow-end.gif) no-repeat top left; +} + +ul.pmui-treepanel > .pmui-treepanel-node:last-child { + background: url(images/elbow-end.gif) no-repeat top left; +} + +.pmui-treepanel-node.pmui-treepanel-node-father > .pmui-treepanel-node-title .pmui-treepanel-node-elbow { + background: url(images/elbow-minus-nl.gif) no-repeat center; +} + +.pmui-treepanel-node.pmui-treepanel-node-father.pmui-treepanel-node-collapsed > .pmui-treepanel-node-title .pmui-treepanel-node-elbow { + background: url(images/elbow-plus-nl.gif) no-repeat center; +} + +/*.pmui-buttonpanel { + padding : 7px; + border-bottom : 1px solid $button-panel_borderColor +}*/ +.pmui-messagewindow-container { + margin: 10px; +} + +.pmui-messagewindow-container tr, +.pmui-messagewindow-container tr td { + margin: 0; + border: 0; + padding: 0; +} + +.pmui-messagewindow-icon { + display: inline-block; + margin-right: 10px; +} + +.pmui-messagewindow-icon-error { + background-position: 0 -70px; + height: 64px; + width: 64px; +} + +.pmui-messagewindow-icon-warning { + background-position: 0 -388px; + height: 64px; + width: 64px; +} + +.pmui-messagewindow-icon-info { + background-position: 0 -180px; + height: 64px; + width: 64px; +} + +.pmui-messagewindow-icon-success { + background-position: 0 -324px; + height: 64px; + width: 64px; +} + +.pmui-messagewindow-icon-confirm { + background-position: 0 -260px; + height: 64px; + width: 64px; +} + +.pmui-window-body { + font-Size: 16px; +} + +.pmui-windowmessage.pmui-windowmessage-error { + background-color: inherit; + /*.pmui-buttonpanel .pmui-button { + background-color : $windowMessage-error-header_background-color; + } + .pmui-buttonpanel .pmui-link { + background : none; + }*/ +} +.pmui-windowmessage.pmui-windowmessage-error .pmui-window-header { + background-color: #e4655f; + padding: 7px 15px; +} +.pmui-windowmessage.pmui-windowmessage-error .pmui-window-body { + background-color: white; + color: #58585b; + font-size: 14px; + padding: 20px 30px 20px 30px; +} +.pmui-windowmessage.pmui-windowmessage-error .pmui-messagewindow-message { + font-size: 14px; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} +.pmui-windowmessage.pmui-windowmessage-error .pmui-window-footer { + background-color: white; +} + +.pmui-windowmessage.pmui-windowmessage-warning { + background-color: inherit; + /*.pmui-buttonpanel .pmui-button { + background-color : $windowMessage-warning-header_background-color ; + } + .pmui-buttonpanel .pmui-link { + background : none; + }*/ +} +.pmui-windowmessage.pmui-windowmessage-warning .pmui-window-header { + background-color: #edb60b; + padding: 7px 15px; +} +.pmui-windowmessage.pmui-windowmessage-warning .pmui-window-body { + background-color: white; + color: #58585b; + font-size: 14px; +} +.pmui-windowmessage.pmui-windowmessage-warning .pmui-messagewindow-message { + font-size: 14px; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} +.pmui-windowmessage.pmui-windowmessage-warning .pmui-window-footer { + background-color: white; +} + +.pmui-windowmessage.pmui-windowmessage-success { + background-color: inherit; + /*.pmui-buttonpanel .pmui-button { + background-color : $windowMessage-success-header_background-color; + } + .pmui-buttonpanel .pmui-link { + background : none; + }*/ +} +.pmui-windowmessage.pmui-windowmessage-success .pmui-window-header { + background-color: #2ddfb7; + padding: 7px 15px; +} +.pmui-windowmessage.pmui-windowmessage-success .pmui-window-body { + background-color: white; + color: #58585b; + font-size: 14px; +} +.pmui-windowmessage.pmui-windowmessage-success .pmui-messagewindow-message { + font-size: 14px; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} +.pmui-windowmessage.pmui-windowmessage-success .pmui-window-footer { + background-color: white; +} + +.pmui-windowmessage.pmui-windowmessage-default { + background-color: inherit; + /*.pmui-buttonpanel .pmui-button { + background-color : $windowMessage-default-header_background-color; + } + .pmui-buttonpanel .pmui-link { + background : none; + }*/ +} +.pmui-windowmessage.pmui-windowmessage-default .pmui-window-header { + background-color: #44afff; + padding: 7px 15px; +} +.pmui-windowmessage.pmui-windowmessage-default .pmui-window-body { + background-color: white; + color: #58585b; + font-size: 14px; +} +.pmui-windowmessage.pmui-windowmessage-default .pmui-messagewindow-message { + font-size: 14px; + -webkit-user-select: text; + -moz-user-select: text; + user-select: text; +} +.pmui-windowmessage.pmui-windowmessage-default .pmui-window-footer { + background-color: white; +} + +.pmui-windowmessage .pmui-buttonpanel .pmui-button { + padding-left: 25px; + padding-right: 25px; + border-radius: 2px; +} + +.pmui-windowmessage .pmui-buttonpanel .pmui-textlabel { + margin-left: 5px; +} + +.pmui-windowmessage .pmui-buttonpanel .pmui-link { + padding: initial; + margin-left: 5px; +} + +.pmui-windowmessage .pmui-window-footer { + padding: 10px; + border-top: 1px solid #e5e5e5; + background: white; +} + +.pmui-windowmessage .pmui-window-body { + padding: 20px 30px 20px 30px; + font-family: Chivo-regular, sans-serif; +} + +.pmui-windowmessage .pmui-textlabel { + font-size: 16px; +} + +.pmui-windowmessage .pmui-buttonpanel .pmui-button { + margin-left: 10px; +} + +.pmui-windowmessage .pmui-window-title { + text-align: center; +} + +.pmui-toolbaritem { + display: inline-block; + margin: 2px; +} + +.pmui-listpanel { + border: 1px solid #bbb; + font-size: 12px; +} + +.pmui-listitem { + border: solid 1px #bbb; +} + +.pmui-listpanel-title, +.pmui-listpanel-toolbar, +.pmui-listpanel-statusbar { + padding: 0.5em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.pmui-listpanel-title { + min-height: 1em; + background: #5f6c79; + color: #FFF; +} + +.pmui-listpanel-toolbar { + font-size: 0.8em; +} + +.pmui-listpanel-statusbar { + background: #E9E9E9; +} + +.pmui-listpanel-list { + overflow: auto; + border-color: #bbb; + border-style: solid; + border-width: 2px 0; + padding: 0; + margin: 0; + border-collapse: collapse; +} + +.pmui-listitem { + list-style: none; + border-color: #bbb; + border-style: solid; + border-width: 0 0 1px 0; + padding: 0.5em; + background: #f8f8f8; +} + +.pmui-listpanel-list > .pmui-listitem:last-child { + border-bottom: 0px; +} + +.pmui-listitem:nth-child(odd) { + background: #eaebed; +} + +.pmui-listitem:hover { + background: #e0e0e0; +} + +.pmui-listitem-icon, +.pmui-listitem-text { + display: inline-block; + vertical-align: middle; +} + +.pmui-listitem-icon { + margin-right: 0.3em; +} + +.pmui-listitem .pmui-toolbar.pmui-listitem-actions { + text-align: right; +} + +.pmui.ui-layout-pane { + border: 1px solid #BBB; + padding: 2px; + /*alerta*/ +} + +/* + * Default Layout Theme + * + * Created for jquery.layout + * + * Copyright (c) 2010 + * Fabrizio Balliano (http://www.fabrizioballiano.net) + * Kevin Dalman (http://allpro.net) + * + * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) + * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. + * + * Last Updated: 2010-02-10 + * NOTE: For best code readability, view this with a fixed-space font and tabs equal to 4-chars + */ + +/* + * DEFAULT FONT + * Just to make demo-pages look better - not actually relevant to Layout! + */ +/*body { + font-family: Geneva, Arial, Helvetica, sans-serif; + font-size: 100%; + *font-size: 80%; +}*/ + +/* + * PANES & CONTENT-DIVs + */ +.ui-layout-pane { /* all 'panes' */ + background: #FFF; + border: 1px solid #BBB; + padding: 2px; + overflow: auto; + /* DO NOT add scrolling (or padding) to 'panes' that have a content-div, + otherwise you may get double-scrollbars - on the pane AND on the content-div + - use ui-layout-wrapper class if pane has a content-div + - use ui-layout-container if pane has an inner-layout + */ + } + /* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */ + .ui-layout-content { + padding: 10px; + position: relative; /* contain floated or positioned elements */ + overflow: auto; /* add scrolling to content-div */ + } + +/* + * UTILITY CLASSES + * Must come AFTER pane-class above so will override + * These classes are NOT auto-generated and are NOT used by Layout + */ +.layout-child-container, +.layout-content-container { + padding: 0; + overflow: hidden; +} +.layout-child-container { + border: 0; /* remove border because inner-layout-panes probably have borders */ +} +.layout-scroll { + overflow: auto; +} +.layout-hide { + display: none; +} + +/* + * RESIZER-BARS + */ +.ui-layout-resizer { /* all 'resizer-bars' */ + background: #DDD; + border: 1px solid #BBB; + border-width: 0; + } + .ui-layout-resizer-drag { /* REAL resizer while resize in progress */ + } + .ui-layout-resizer-hover { /* affects both open and closed states */ + } + /* NOTE: It looks best when 'hover' and 'dragging' are set to the same color, + otherwise color shifts while dragging when bar can't keep up with mouse */ + .ui-layout-resizer-open-hover , /* hover-color to 'resize' */ + .ui-layout-resizer-dragging { /* resizer beging 'dragging' */ + background: #C4E1A4; + } + .ui-layout-resizer-dragging { /* CLONED resizer being dragged */ + border: 1px solid #BBB; + } + .ui-layout-resizer-north-dragging, + .ui-layout-resizer-south-dragging { + border-width: 1px 0; + } + .ui-layout-resizer-west-dragging, + .ui-layout-resizer-east-dragging { + border-width: 0 1px; + } + /* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */ + .ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */ + background: #E1A4A4; /* red */ + } + + .ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */ + background: #EBD5AA; + } + .ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */ + opacity: .10; /* show only a slight shadow */ + filter: alpha(opacity=10); + } + .ui-layout-resizer-sliding-hover { /* sliding resizer - hover */ + opacity: 1.00; /* on-hover, show the resizer-bar normally */ + filter: alpha(opacity=100); + } + /* sliding resizer - add 'outside-border' to resizer on-hover + * this sample illustrates how to target specific panes and states */ + .ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; } + .ui-layout-resizer-south-sliding-hover { border-top-width: 1px; } + .ui-layout-resizer-west-sliding-hover { border-right-width: 1px; } + .ui-layout-resizer-east-sliding-hover { border-left-width: 1px; } + +/* + * TOGGLER-BUTTONS + */ +.ui-layout-toggler { + border: 1px solid #BBB; /* match pane-border */ + background-color: #BBB; + } + .ui-layout-resizer-hover .ui-layout-toggler { + opacity: .60; + filter: alpha(opacity=60); + } + .ui-layout-toggler-hover , /* need when NOT resizable */ + .ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */ + background-color: #FC6; + opacity: 1.00; + filter: alpha(opacity=100); + } + .ui-layout-toggler-north , + .ui-layout-toggler-south { + border-width: 0 1px; /* left/right borders */ + } + .ui-layout-toggler-west , + .ui-layout-toggler-east { + border-width: 1px 0; /* top/bottom borders */ + } + /* hide the toggler-button when the pane is 'slid open' */ + .ui-layout-resizer-sliding .ui-layout-toggler { + display: none; + } + /* + * style the text we put INSIDE the togglers + */ + .ui-layout-toggler .content { + color: #666; + font-size: 12px; + font-weight: bold; + width: 100%; + padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */ + } + +/* + * PANE-MASKS + * these styles are hard-coded on mask elems, but are also + * included here as !important to ensure will overrides any generic styles + */ +.ui-layout-mask { + border: none !important; + padding: 0 !important; + margin: 0 !important; + overflow: hidden !important; + position: absolute !important; + opacity: 0 !important; + filter: Alpha(Opacity="0") !important; +} +.ui-layout-mask-inside-pane { /* masks always inside pane EXCEPT when pane is an iframe */ + top: 0 !important; + left: 0 !important; + width: 100% !important; + height: 100% !important; +} +div.ui-layout-mask {} /* standard mask for iframes */ +iframe.ui-layout-mask {} /* extra mask for objects/applets */ + +/* + * Default printing styles + */ +@media print { + /* + * Unless you want to print the layout as it appears onscreen, + * these html/body styles are needed to allow the content to 'flow' + */ + html { + height: auto !important; + overflow: visible !important; + } + body.ui-layout-container { + position: static !important; + top: auto !important; + bottom: auto !important; + left: auto !important; + right: auto !important; + /* only IE6 has container width & height set by Layout */ + _width: auto !important; + _height: auto !important; + } + .ui-layout-resizer, .ui-layout-toggler { + display: none !important; + } + /* + * Default pane print styles disables positioning, borders and backgrounds. + * You can modify these styles however it suit your needs. + */ + .ui-layout-pane { + border: none !important; + background: transparent !important; + position: relative !important; + top: auto !important; + bottom: auto !important; + left: auto !important; + right: auto !important; + width: auto !important; + height: auto !important; + overflow: visible !important; + } +} +/*! jQuery UI - v1.10.3 - 2013-09-02 +* http://jqueryui.com +* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css +* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=11px&cornerRadius=5px&bgColorHeader=%235c9ccc&bgTextureHeader=gloss_wave&bgImgOpacityHeader=55&borderColorHeader=%234297d7&fcHeader=%23ffffff&iconColorHeader=%23d8e7f3&bgColorContent=%23fcfdfd&bgTextureContent=inset_hard&bgImgOpacityContent=100&borderColorContent=%23a6c9e2&fcContent=%23222222&iconColorContent=%23469bdd&bgColorDefault=%23dfeffc&bgTextureDefault=glass&bgImgOpacityDefault=85&borderColorDefault=%23c5dbec&fcDefault=%232e6e9e&iconColorDefault=%236da8d5&bgColorHover=%23d0e5f5&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=%2379b7e7&fcHover=%231d5987&iconColorHover=%23217bc0&bgColorActive=%23f5f8f9&bgTextureActive=inset_hard&bgImgOpacityActive=100&borderColorActive=%2379b7e7&fcActive=%23e17009&iconColorActive=%23f9bd01&bgColorHighlight=%23fbec88&bgTextureHighlight=flat&bgImgOpacityHighlight=55&borderColorHighlight=%23fad42e&fcHighlight=%23363636&iconColorHighlight=%232e83ff&bgColorError=%23fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=%23cd0a0a&fcError=%23cd0a0a&iconColorError=%23cd0a0a&bgColorOverlay=%23aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=%23aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px +* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { + display: none; +} +.ui-helper-hidden-accessible { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.ui-helper-reset { + margin: 0; + padding: 0; + border: 0; + outline: 0; + line-height: 1.3; + text-decoration: none; + font-size: 100%; + list-style: none; +} +.ui-helper-clearfix:before, +.ui-helper-clearfix:after { + content: ""; + display: table; + border-collapse: collapse; +} +.ui-helper-clearfix:after { + clear: both; +} +.ui-helper-clearfix { + min-height: 0; /* support: IE7 */ +} +.ui-helper-zfix { + width: 100%; + height: 100%; + top: 0; + left: 0; + position: absolute; + opacity: 0; + filter:Alpha(Opacity=0); +} + +.ui-front { + z-index: 100; +} + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { + cursor: default !important; +} + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + display: block; + text-indent: -99999px; + overflow: hidden; + background-repeat: no-repeat; +} + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +.ui-resizable { + position: relative; +} +.ui-resizable-handle { + position: absolute; + font-size: 0.1px; + display: block; +} +.ui-resizable-disabled .ui-resizable-handle, +.ui-resizable-autohide .ui-resizable-handle { + display: none; +} +.ui-resizable-n { + cursor: n-resize; + height: 7px; + width: 100%; + top: -5px; + left: 0; +} +.ui-resizable-s { + cursor: s-resize; + height: 7px; + width: 100%; + bottom: -5px; + left: 0; +} +.ui-resizable-e { + cursor: e-resize; + width: 7px; + right: -5px; + top: 0; + height: 100%; +} +.ui-resizable-w { + cursor: w-resize; + width: 7px; + left: -5px; + top: 0; + height: 100%; +} +.ui-resizable-se { + cursor: se-resize; + width: 12px; + height: 12px; + right: 1px; + bottom: 1px; +} +.ui-resizable-sw { + cursor: sw-resize; + width: 9px; + height: 9px; + left: -5px; + bottom: -5px; +} +.ui-resizable-nw { + cursor: nw-resize; + width: 9px; + height: 9px; + left: -5px; + top: -5px; +} +.ui-resizable-ne { + cursor: ne-resize; + width: 9px; + height: 9px; + right: -5px; + top: -5px; +} +.ui-selectable-helper { + position: absolute; + z-index: 100; + border: 1px dotted black; +} +.ui-accordion .ui-accordion-header { + display: block; + cursor: pointer; + position: relative; + margin-top: 2px; + padding: .5em .5em .5em .7em; + min-height: 0; /* support: IE7 */ +} +.ui-accordion .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-noicons { + padding-left: .7em; +} +.ui-accordion .ui-accordion-icons .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-header .ui-accordion-header-icon { + position: absolute; + left: .5em; + top: 50%; + margin-top: -8px; +} +.ui-accordion .ui-accordion-content { + padding: 1em 2.2em; + border-top: 0; + overflow: auto; +} +.ui-autocomplete { + position: absolute; + top: 0; + left: 0; + cursor: default; +} +.ui-button { + display: inline-block; + position: relative; + padding: 0; + line-height: normal; + margin-right: .1em; + cursor: pointer; + vertical-align: middle; + text-align: center; + overflow: visible; /* removes extra width in IE */ +} +.ui-button, +.ui-button:link, +.ui-button:visited, +.ui-button:hover, +.ui-button:active { + text-decoration: none; +} +/* to make room for the icon, a width needs to be set here */ +.ui-button-icon-only { + width: 2.2em; +} +/* button elements seem to need a little more width */ +button.ui-button-icon-only { + width: 2.4em; +} +.ui-button-icons-only { + width: 3.4em; +} +button.ui-button-icons-only { + width: 3.7em; +} + +/* button text element */ +.ui-button .ui-button-text { + display: block; + line-height: normal; +} +.ui-button-text-only .ui-button-text { + padding: .4em 1em; +} +.ui-button-icon-only .ui-button-text, +.ui-button-icons-only .ui-button-text { + padding: .4em; + text-indent: -9999999px; +} +.ui-button-text-icon-primary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 1em .4em 2.1em; +} +.ui-button-text-icon-secondary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 2.1em .4em 1em; +} +.ui-button-text-icons .ui-button-text { + padding-left: 2.1em; + padding-right: 2.1em; +} +/* no icon support for input elements, provide padding by default */ +input.ui-button { + padding: .4em 1em; +} + +/* button icon element(s) */ +.ui-button-icon-only .ui-icon, +.ui-button-text-icon-primary .ui-icon, +.ui-button-text-icon-secondary .ui-icon, +.ui-button-text-icons .ui-icon, +.ui-button-icons-only .ui-icon { + position: absolute; + top: 50%; + margin-top: -8px; +} +.ui-button-icon-only .ui-icon { + left: 50%; + margin-left: -8px; +} +.ui-button-text-icon-primary .ui-button-icon-primary, +.ui-button-text-icons .ui-button-icon-primary, +.ui-button-icons-only .ui-button-icon-primary { + left: .5em; +} +.ui-button-text-icon-secondary .ui-button-icon-secondary, +.ui-button-text-icons .ui-button-icon-secondary, +.ui-button-icons-only .ui-button-icon-secondary { + right: .5em; +} + +/* button sets */ +.ui-buttonset { + margin-right: 7px; +} +.ui-buttonset .ui-button { + margin-left: 0; + margin-right: -.3em; +} + +/* workarounds */ +/* reset extra padding in Firefox, see h5bp.com/l */ +input.ui-button::-moz-focus-inner, +button.ui-button::-moz-focus-inner { + border: 0; + padding: 0; +} +.ui-datepicker { + width: 17em; + padding: .2em .2em 0; + display: none; +} +.ui-datepicker .ui-datepicker-header { + position: relative; + padding: .2em 0; +} +.ui-datepicker .ui-datepicker-prev, +.ui-datepicker .ui-datepicker-next { + position: absolute; + top: 2px; + width: 1.8em; + height: 1.8em; +} +.ui-datepicker .ui-datepicker-prev-hover, +.ui-datepicker .ui-datepicker-next-hover { + top: 1px; +} +.ui-datepicker .ui-datepicker-prev { + left: 2px; +} +.ui-datepicker .ui-datepicker-next { + right: 2px; +} +.ui-datepicker .ui-datepicker-prev-hover { + left: 1px; +} +.ui-datepicker .ui-datepicker-next-hover { + right: 1px; +} +.ui-datepicker .ui-datepicker-prev span, +.ui-datepicker .ui-datepicker-next span { + display: block; + position: absolute; + left: 50%; + margin-left: -8px; + top: 50%; + margin-top: -8px; +} +.ui-datepicker .ui-datepicker-title { + margin: 0 2.3em; + line-height: 1.8em; + text-align: center; +} +.ui-datepicker .ui-datepicker-title select { + font-size: 1em; + margin: 1px 0; +} +.ui-datepicker select.ui-datepicker-month-year { + width: 100%; +} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { + width: 49%; +} +.ui-datepicker table { + width: 100%; + font-size: .9em; + border-collapse: collapse; + margin: 0 0 .4em; +} +.ui-datepicker th { + padding: .7em .3em; + text-align: center; + font-weight: bold; + border: 0; +} +.ui-datepicker td { + border: 0; + padding: 1px; +} +.ui-datepicker td span, +.ui-datepicker td a { + display: block; + padding: .2em; + text-align: right; + text-decoration: none; +} +.ui-datepicker .ui-datepicker-buttonpane { + background-image: none; + margin: .7em 0 0 0; + padding: 0 .2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} +.ui-datepicker .ui-datepicker-buttonpane button { + float: right; + margin: .5em .2em .4em; + cursor: pointer; + padding: .2em .6em .3em .6em; + width: auto; + overflow: visible; +} +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { + float: left; +} + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { + width: auto; +} +.ui-datepicker-multi .ui-datepicker-group { + float: left; +} +.ui-datepicker-multi .ui-datepicker-group table { + width: 95%; + margin: 0 auto .4em; +} +.ui-datepicker-multi-2 .ui-datepicker-group { + width: 50%; +} +.ui-datepicker-multi-3 .ui-datepicker-group { + width: 33.3%; +} +.ui-datepicker-multi-4 .ui-datepicker-group { + width: 25%; +} +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { + border-left-width: 0; +} +.ui-datepicker-multi .ui-datepicker-buttonpane { + clear: left; +} +.ui-datepicker-row-break { + clear: both; + width: 100%; + font-size: 0; +} + +/* RTL support */ +.ui-datepicker-rtl { + direction: rtl; +} +.ui-datepicker-rtl .ui-datepicker-prev { + right: 2px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next { + left: 2px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-prev:hover { + right: 1px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next:hover { + left: 1px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane { + clear: right; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button { + float: left; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, +.ui-datepicker-rtl .ui-datepicker-group { + float: right; +} +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { + border-right-width: 0; + border-left-width: 1px; +} +.ui-dialog { + position: absolute; + top: 0; + left: 0; + padding: .2em; + outline: 0; +} +.ui-dialog .ui-dialog-titlebar { + padding: .4em 1em; + position: relative; +} +.ui-dialog .ui-dialog-title { + float: left; + margin: .1em 0; + white-space: nowrap; + width: 90%; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute; + right: .3em; + top: 50%; + width: 21px; + margin: -10px 0 0 0; + padding: 1px; + height: 20px; +} +.ui-dialog .ui-dialog-content { + position: relative; + border: 0; + padding: .5em 1em; + background: none; + overflow: auto; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: .5em; + padding: .3em 1em .5em .4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: .5em .4em .5em 0; + cursor: pointer; +} +.ui-dialog .ui-resizable-se { + width: 12px; + height: 12px; + right: -5px; + bottom: -5px; + background-position: 16px 16px; +} +.ui-draggable .ui-dialog-titlebar { + cursor: move; +} +.ui-menu { + list-style: none; + padding: 2px; + margin: 0; + display: block; + outline: none; +} +.ui-menu .ui-menu { + margin-top: -3px; + position: absolute; +} +.ui-menu .ui-menu-item { + margin: 0; + padding: 0; + width: 100%; + /* support: IE10, see #8844 */ + list-style-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7); +} +.ui-menu .ui-menu-divider { + margin: 5px -2px 5px -2px; + height: 0; + font-size: 0; + line-height: 0; + border-width: 1px 0 0 0; +} +.ui-menu .ui-menu-item a { + text-decoration: none; + display: block; + padding: 2px .4em; + line-height: 1.5; + min-height: 0; /* support: IE7 */ + font-weight: normal; +} +.ui-menu .ui-menu-item a.ui-state-focus, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} + +.ui-menu .ui-state-disabled { + font-weight: normal; + margin: .4em 0 .2em; + line-height: 1.5; +} +.ui-menu .ui-state-disabled a { + cursor: default; +} + +/* icon support */ +.ui-menu-icons { + position: relative; +} +.ui-menu-icons .ui-menu-item a { + position: relative; + padding-left: 2em; +} + +/* left-aligned */ +.ui-menu .ui-icon { + position: absolute; + top: .2em; + left: .2em; +} + +/* right-aligned */ +.ui-menu .ui-menu-icon { + position: static; + float: right; +} +.ui-progressbar { + height: 2em; + text-align: left; + overflow: hidden; +} +.ui-progressbar .ui-progressbar-value { + margin: -1px; + height: 100%; +} +.ui-progressbar .ui-progressbar-overlay { + background: url("images/animated-overlay.gif"); + height: 100%; + filter: alpha(opacity=25); + opacity: 0.25; +} +.ui-progressbar-indeterminate .ui-progressbar-value { + background-image: none; +} +.ui-slider { + position: relative; + text-align: left; +} +.ui-slider .ui-slider-handle { + position: absolute; + z-index: 2; + width: 1.2em; + height: 1.2em; + cursor: default; +} +.ui-slider .ui-slider-range { + position: absolute; + z-index: 1; + font-size: .7em; + display: block; + border: 0; + background-position: 0 0; +} + +/* For IE8 - See #6727 */ +.ui-slider.ui-state-disabled .ui-slider-handle, +.ui-slider.ui-state-disabled .ui-slider-range { + filter: inherit; +} + +.ui-slider-horizontal { + height: .8em; +} +.ui-slider-horizontal .ui-slider-handle { + top: -.3em; + margin-left: -.6em; +} +.ui-slider-horizontal .ui-slider-range { + top: 0; + height: 100%; +} +.ui-slider-horizontal .ui-slider-range-min { + left: 0; +} +.ui-slider-horizontal .ui-slider-range-max { + right: 0; +} + +.ui-slider-vertical { + width: .8em; + height: 100px; +} +.ui-slider-vertical .ui-slider-handle { + left: -.3em; + margin-left: 0; + margin-bottom: -.6em; +} +.ui-slider-vertical .ui-slider-range { + left: 0; + width: 100%; +} +.ui-slider-vertical .ui-slider-range-min { + bottom: 0; +} +.ui-slider-vertical .ui-slider-range-max { + top: 0; +} +.ui-spinner { + position: relative; + display: inline-block; + overflow: hidden; + padding: 0; + vertical-align: middle; +} +.ui-spinner-input { + border: none; + background: none; + color: inherit; + padding: 0; + margin: .2em 0; + vertical-align: middle; + margin-left: .4em; + margin-right: 22px; +} +.ui-spinner-button { + width: 16px; + height: 50%; + font-size: .5em; + padding: 0; + margin: 0; + text-align: center; + position: absolute; + cursor: default; + display: block; + overflow: hidden; + right: 0; +} +/* more specificity required here to overide default borders */ +.ui-spinner a.ui-spinner-button { + border-top: none; + border-bottom: none; + border-right: none; +} +/* vertical centre icon */ +.ui-spinner .ui-icon { + position: absolute; + margin-top: -8px; + top: 50%; + left: 0; +} +.ui-spinner-up { + top: 0; +} +.ui-spinner-down { + bottom: 0; +} + +/* TR overrides */ +.ui-spinner .ui-icon-triangle-1-s { + /* need to fix icons sprite */ + background-position: -65px -16px; +} +.ui-tabs { + position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ + padding: .2em; +} +.ui-tabs .ui-tabs-nav { + margin: 0; + padding: .2em .2em 0; +} +.ui-tabs .ui-tabs-nav li { + list-style: none; + float: left; + position: relative; + top: 0; + margin: 1px .2em 0 0; + border-bottom-width: 0; + padding: 0; + white-space: nowrap; +} +.ui-tabs .ui-tabs-nav li a { + float: left; + padding: .5em 1em; + text-decoration: none; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active { + margin-bottom: -1px; + padding-bottom: 1px; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active a, +.ui-tabs .ui-tabs-nav li.ui-state-disabled a, +.ui-tabs .ui-tabs-nav li.ui-tabs-loading a { + cursor: text; +} +.ui-tabs .ui-tabs-nav li a, /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { + cursor: pointer; +} +.ui-tabs .ui-tabs-panel { + display: block; + border-width: 0; + padding: 1em 1.4em; + background: none; +} +.ui-tooltip { + padding: 8px; + position: absolute; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; +} +body .ui-tooltip { + border-width: 2px; +} + +/* Component containers +----------------------------------*/ +.ui-widget { + font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; + font-size: 11px; +} +.ui-widget .ui-widget { + font-size: 1em; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; + font-size: 1em; +} +.ui-widget-content { + border-right: 1px solid #a6c9e2; + border-left: 1px solid #a6c9e2; + border-bottom: 1px solid #a6c9e2; + background: #fcfdfd url(images/ui-bg_inset-hard_100_fcfdfd_1x100.png) 50% bottom repeat-x; + color: #222222; +} +.ui-widget-content a { + color: #222222; +} +.ui-widget-header { + border: 1px solid #4297d7; + background: #5c9ccc url(images/ui-bg_gloss-wave_55_5c9ccc_500x100.png) 50% 50% repeat-x; + color: #ffffff; + font-weight: bold; + /*color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #49afcd; + *background-color: #2f96b4; + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); + background-repeat: repeat-x; + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);*/ +} +.ui-widget-header a { + color: #ffffff; +} + +/* Interaction states +----------------------------------*/ +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + border: 1px solid #c5dbec; + background: #dfeffc url(images/ui-bg_glass_85_dfeffc_1x400.png) 50% 50% repeat-x; + font-weight: bold; + color: #2e6e9e; +} +.ui-state-default a, +.ui-state-default a:link, +.ui-state-default a:visited { + color: #2e6e9e; + text-decoration: none; +} +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover, +.ui-state-focus, +.ui-widget-content .ui-state-focus, +.ui-widget-header .ui-state-focus { + border: 1px solid #79b7e7; + background: #d0e5f5 url(images/ui-bg_glass_75_d0e5f5_1x400.png) 50% 50% repeat-x; + font-weight: bold; + color: #1d5987; +} +.ui-state-hover a, +.ui-state-hover a:hover, +.ui-state-hover a:link, +.ui-state-hover a:visited { + color: #1d5987; + text-decoration: none; +} +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #79b7e7; + background: #f5f8f9 url(images/ui-bg_inset-hard_100_f5f8f9_1x100.png) 50% 50% repeat-x; + font-weight: bold; + color: #e17009; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #e17009; + text-decoration: none; +} + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, +.ui-widget-content .ui-state-highlight, +.ui-widget-header .ui-state-highlight { + border: 1px solid #fad42e; + background: #fbec88 url(images/ui-bg_flat_55_fbec88_40x100.png) 50% 50% repeat-x; + color: #363636; +} +.ui-state-highlight a, +.ui-widget-content .ui-state-highlight a, +.ui-widget-header .ui-state-highlight a { + color: #363636; +} +.ui-state-error, +.ui-widget-content .ui-state-error, +.ui-widget-header .ui-state-error { + border: 1px solid #cd0a0a; + background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; + color: #cd0a0a; +} +.ui-state-error a, +.ui-widget-content .ui-state-error a, +.ui-widget-header .ui-state-error a { + color: #cd0a0a; +} +.ui-state-error-text, +.ui-widget-content .ui-state-error-text, +.ui-widget-header .ui-state-error-text { + color: #cd0a0a; +} +.ui-priority-primary, +.ui-widget-content .ui-priority-primary, +.ui-widget-header .ui-priority-primary { + font-weight: bold; +} +.ui-priority-secondary, +.ui-widget-content .ui-priority-secondary, +.ui-widget-header .ui-priority-secondary { + opacity: .7; + filter:Alpha(Opacity=70); + font-weight: normal; +} +.ui-state-disabled, +.ui-widget-content .ui-state-disabled, +.ui-widget-header .ui-state-disabled { + opacity: .35; + filter:Alpha(Opacity=35); + background-image: none; +} +.ui-state-disabled .ui-icon { + filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ +} + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + width: 16px; + height: 16px; +} +.ui-icon, +.ui-widget-content .ui-icon { + background-image: url(images/ui-icons_469bdd_256x240.png); +} +.ui-widget-header .ui-icon { + background-image: url(images/ui-icons_d8e7f3_256x240.png); +} +.ui-state-default .ui-icon { + background-image: url(images/ui-icons_6da8d5_256x240.png); +} +.ui-state-hover .ui-icon, +.ui-state-focus .ui-icon { + background-image: url(images/ui-icons_217bc0_256x240.png); +} +.ui-state-active .ui-icon { + background-image: url(images/ui-icons_f9bd01_256x240.png); +} +.ui-state-highlight .ui-icon { + background-image: url(images/ui-icons_2e83ff_256x240.png); +} +.ui-state-error .ui-icon, +.ui-state-error-text .ui-icon { + background-image: url(images/ui-icons_cd0a0a_256x240.png); +} + +/* positioning */ +.ui-icon-blank { background-position: 16px 16px; } +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-on { background-position: -96px -144px; } +.ui-icon-radio-off { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 5px; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 5px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 5px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 5px; +} + +/* Overlays */ +.ui-widget-overlay { + background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); +} +.ui-widget-shadow { + margin: -8px 0 0 -8px; + padding: 8px; + background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); + border-radius: 8px; +} +.introjs-overlay { + position: absolute; + z-index: 999999; + background-color: #000; + opacity: 0; + background: -moz-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -webkit-gradient(radial,center center,0px,center center,100%,color-stop(0%,rgba(0,0,0,0.4)),color-stop(100%,rgba(0,0,0,0.9))); + background: -webkit-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -o-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -ms-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#66000000',endColorstr='#e6000000',GradientType=1); + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; + filter: alpha(opacity=50); + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-fixParent { + z-index: auto !important; + opacity: 1.0 !important; + position: absolute !important; + -webkit-transform: none !important; + -moz-transform: none !important; + -ms-transform: none !important; + -o-transform: none !important; + transform: none !important; +} + +.introjs-showElement, +tr.introjs-showElement > td, +tr.introjs-showElement > th { + z-index: 9999999 !important; +} + +.introjs-disableInteraction { + z-index: 99999999 !important; + position: absolute; +} + +.introjs-relativePosition, +tr.introjs-showElement > td, +tr.introjs-showElement > th { + position: relative; +} + +.introjs-helperLayer { + position: fixed; + z-index: 9999998; + background-color: #FFF; + background-color: rgba(255,255,255,.9); + border: 1px solid #777; + border: 1px solid rgba(0,0,0,.5); + border-radius: 4px; + box-shadow: 0 2px 15px rgba(0,0,0,.4); + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-tooltipReferenceLayer { + position: fixed; + z-index: 10000000; + background-color: transparent; + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-helperLayer *, +.introjs-helperLayer *:before, +.introjs-helperLayer *:after { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + -ms-box-sizing: content-box; + -o-box-sizing: content-box; + box-sizing: content-box; +} + +.introjs-helperNumberLayer { + position: absolute; + top: 5px; + /*left: -16px;*/ + left: 50%; + z-index: 9999999999 !important; + padding: 2px; + font-family: Arial, verdana, tahoma; + font-size: 13px; + font-weight: bold; + color: white; + text-align: center; + text-shadow: 1px 1px 1px rgba(0,0,0,.3); + background: #ff3019; /* Old browsers */ + background: -webkit-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Chrome10+,Safari5.1+ */ + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ff3019), color-stop(100%, #cf0404)); /* Chrome,Safari4+ */ + background: -moz-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* FF3.6+ */ + background: -ms-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* IE10+ */ + background: -o-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Opera 11.10+ */ + background: linear-gradient(to bottom, #ff3019 0%, #cf0404 100%); /* W3C */ + width: 20px; + height:20px; + line-height: 20px; + border: 3px solid white; + border-radius: 50%; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3019', endColorstr='#cf0404', GradientType=0); /* IE6-9 */ + filter: progid:DXImageTransform.Microsoft.Shadow(direction=135, strength=2, color=ff0000); /* IE10 text shadows */ + box-shadow: 0 2px 5px rgba(0,0,0,.4); +} + +.introjs-arrow { + border: 5px solid white; + content:''; + position: absolute; +} +.introjs-arrow.top { + top: -10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.top-right { + top: -10px; + right: 10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.top-middle { + top: -10px; + left: 50%; + margin-left: -5px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.right { + right: -10px; + top: 10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:white; +} +.introjs-arrow.right-bottom { + bottom:10px; + right: -10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:white; +} +.introjs-arrow.bottom { + bottom: -10px; + border-top-color:white; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:transparent; +} +.introjs-arrow.left { + left: -10px; + top: 10px; + border-top-color:transparent; + border-right-color:white; + border-bottom-color:transparent; + border-left-color:transparent; +} +.introjs-arrow.left-bottom { + left: -10px; + bottom:10px; + border-top-color:transparent; + border-right-color:white; + border-bottom-color:transparent; + border-left-color:transparent; +} + +.introjs-tooltip { + position: absolute; + padding: 10px; + background-color: white; + min-width: 200px; + max-width: 600px; + border-radius: 3px; + box-shadow: 0 1px 10px rgba(0,0,0,.4); + -webkit-transition: opacity 0.1s ease-out; + -moz-transition: opacity 0.1s ease-out; + -ms-transition: opacity 0.1s ease-out; + -o-transition: opacity 0.1s ease-out; + transition: opacity 0.1s ease-out; +} + +.introjs-tooltipbuttons { + text-align: right; + white-space: nowrap; +} + +/* + Buttons style by http://nicolasgallagher.com/lab/css3-github-buttons/ + Changed by Afshin Mehrabani +*/ +.introjs-button { + position: relative; + overflow: visible; + display: inline-block; + padding: 0.3em 0.8em; + border: 1px solid #d4d4d4; + margin: 0; + text-decoration: none; + text-shadow: 1px 1px 0 #fff; + font: 11px/normal sans-serif; + color: #333; + white-space: nowrap; + cursor: pointer; + outline: none; + background-color: #ececec; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f4f4f4), to(#ececec)); + background-image: -moz-linear-gradient(#f4f4f4, #ececec); + background-image: -o-linear-gradient(#f4f4f4, #ececec); + background-image: linear-gradient(#f4f4f4, #ececec); + -webkit-background-clip: padding; + -moz-background-clip: padding; + -o-background-clip: padding-box; + /*background-clip: padding-box;*/ /* commented out due to Opera 11.10 bug */ + -webkit-border-radius: 0.2em; + -moz-border-radius: 0.2em; + border-radius: 0.2em; + /* IE hacks */ + zoom: 1; + *display: inline; + margin-top: 10px; +} + +.introjs-button:hover { + border-color: #bcbcbc; + text-decoration: none; + box-shadow: 0px 1px 1px #e3e3e3; +} + +.introjs-button:focus, +.introjs-button:active { + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ececec), to(#f4f4f4)); + background-image: -moz-linear-gradient(#ececec, #f4f4f4); + background-image: -o-linear-gradient(#ececec, #f4f4f4); + background-image: linear-gradient(#ececec, #f4f4f4); +} + +/* overrides extra padding on button elements in Firefox */ +.introjs-button::-moz-focus-inner { + padding: 0; + border: 0; +} + +.introjs-skipbutton { + margin-right: 5px; + color: #7a7a7a; +} + +.introjs-prevbutton { + -webkit-border-radius: 0.2em 0 0 0.2em; + -moz-border-radius: 0.2em 0 0 0.2em; + border-radius: 0.2em 0 0 0.2em; + border-right: none; +} + +.introjs-nextbutton { + -webkit-border-radius: 0 0.2em 0.2em 0; + -moz-border-radius: 0 0.2em 0.2em 0; + border-radius: 0 0.2em 0.2em 0; +} + +.introjs-disabled, .introjs-disabled:hover, .introjs-disabled:focus { + color: #9a9a9a; + border-color: #d4d4d4; + box-shadow: none; + cursor: default; + background-color: #f4f4f4; + background-image: none; + text-decoration: none; +} + +.introjs-bullets { + text-align: center; +} +.introjs-bullets ul { + clear: both; + margin: 15px auto 0; + padding: 0; + display: inline-block; +} +.introjs-bullets ul li { + list-style: none; + float: left; + margin: 0 2px; +} +.introjs-bullets ul li a { + display: block; + width: 6px; + height: 6px; + background: #ccc; + border-radius: 10px; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + text-decoration: none; +} +.introjs-bullets ul li a:hover { + background: #999; +} +.introjs-bullets ul li a.active { + background: #999; +} + +.introjs-progress { + overflow: hidden; + height: 10px; + margin: 10px 0 5px 0; + border-radius: 4px; + background-color: #ecf0f1 +} +.introjs-progressbar { + float: left; + width: 0%; + height: 100%; + font-size: 10px; + line-height: 10px; + text-align: center; + background-color: #08c; +} + +.introjsFloatingElement { + position: absolute; + height: 0; + width: 0; + left: 50%; + top: 50%; +} + +table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}table.dataTable thead th,table.dataTable tfoot th{font-weight:bold}table.dataTable thead th,table.dataTable thead td{padding:10px 18px;border-bottom:1px solid #111}table.dataTable thead th:active,table.dataTable thead td:active{outline:none}table.dataTable tfoot th,table.dataTable tfoot td{padding:10px 18px 6px 18px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer;*cursor:hand}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url("../img/sort_both.png")}table.dataTable thead .sorting_asc{background-image:url("../img/sort_asc.png")}table.dataTable thead .sorting_desc{background-image:url("../img/sort_desc.png")}table.dataTable thead .sorting_asc_disabled{background-image:url("../img/sort_asc_disabled.png")}table.dataTable thead .sorting_desc_disabled{background-image:url("../img/sort_desc_disabled.png")}table.dataTable tbody tr{background-color:#fff}table.dataTable tbody tr.selected{background-color:#B0BED9}table.dataTable tbody th,table.dataTable tbody td{padding:8px 10px}table.dataTable.row-border tbody th,table.dataTable.row-border tbody td,table.dataTable.display tbody th,table.dataTable.display tbody td{border-top:1px solid #ddd}table.dataTable.row-border tbody tr:first-child th,table.dataTable.row-border tbody tr:first-child td,table.dataTable.display tbody tr:first-child th,table.dataTable.display tbody tr:first-child td{border-top:none}table.dataTable.cell-border tbody th,table.dataTable.cell-border tbody td{border-top:1px solid #ddd;border-right:1px solid #ddd}table.dataTable.cell-border tbody tr th:first-child,table.dataTable.cell-border tbody tr td:first-child{border-left:1px solid #ddd}table.dataTable.cell-border tbody tr:first-child th,table.dataTable.cell-border tbody tr:first-child td{border-top:none}table.dataTable.stripe tbody tr.odd,table.dataTable.display tbody tr.odd{background-color:#f9f9f9}table.dataTable.stripe tbody tr.odd.selected,table.dataTable.display tbody tr.odd.selected{background-color:#abb9d3}table.dataTable.hover tbody tr:hover,table.dataTable.display tbody tr:hover{background-color:#f5f5f5}table.dataTable.hover tbody tr:hover.selected,table.dataTable.display tbody tr:hover.selected{background-color:#a9b7d1}table.dataTable.order-column tbody tr>.sorting_1,table.dataTable.order-column tbody tr>.sorting_2,table.dataTable.order-column tbody tr>.sorting_3,table.dataTable.display tbody tr>.sorting_1,table.dataTable.display tbody tr>.sorting_2,table.dataTable.display tbody tr>.sorting_3{background-color:#f9f9f9}table.dataTable.order-column tbody tr.selected>.sorting_1,table.dataTable.order-column tbody tr.selected>.sorting_2,table.dataTable.order-column tbody tr.selected>.sorting_3,table.dataTable.display tbody tr.selected>.sorting_1,table.dataTable.display tbody tr.selected>.sorting_2,table.dataTable.display tbody tr.selected>.sorting_3{background-color:#acbad4}table.dataTable.display tbody tr.odd>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}table.dataTable.display tbody tr.odd>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}table.dataTable.display tbody tr.odd>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}table.dataTable.display tbody tr.odd.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}table.dataTable.display tbody tr.odd.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}table.dataTable.display tbody tr.odd.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}table.dataTable.display tbody tr.even>.sorting_1,table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}table.dataTable.display tbody tr.even>.sorting_2,table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}table.dataTable.display tbody tr.even>.sorting_3,table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}table.dataTable.display tbody tr.even.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}table.dataTable.display tbody tr.even.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}table.dataTable.display tbody tr.even.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}table.dataTable.display tbody tr:hover>.sorting_1,table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}table.dataTable.display tbody tr:hover>.sorting_2,table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}table.dataTable.display tbody tr:hover>.sorting_3,table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}table.dataTable.display tbody tr:hover.selected>.sorting_1,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}table.dataTable.display tbody tr:hover.selected>.sorting_2,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}table.dataTable.display tbody tr:hover.selected>.sorting_3,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}table.dataTable.no-footer{border-bottom:1px solid #111}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}table.dataTable.compact thead th,table.dataTable.compact thead td{padding:4px 17px 4px 4px}table.dataTable.compact tfoot th,table.dataTable.compact tfoot td{padding:4px}table.dataTable.compact tbody th,table.dataTable.compact tbody td{padding:4px}table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-center,table.dataTable td.dt-center,table.dataTable td.dataTables_empty{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}table.dataTable,table.dataTable th,table.dataTable td{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.dataTables_wrapper{position:relative;clear:both;*zoom:1;zoom:1}.dataTables_wrapper .dataTables_length{float:left}.dataTables_wrapper .dataTables_filter{float:right;text-align:right}.dataTables_wrapper .dataTables_filter input{margin-left:0.5em}.dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:0.755em}.dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:0.25em}.dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#333 !important;border:1px solid transparent}.dataTables_wrapper .dataTables_paginate .paginate_button.current,.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333 !important;border:1px solid #cacaca;background-color:#fff;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc));background:-webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-moz-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-ms-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-o-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:linear-gradient(to bottom, #fff 0%, #dcdcdc 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active{cursor:default;color:#666 !important;border:1px solid transparent;background:transparent;box-shadow:none}.dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:white !important;border:1px solid #111;background-color:#585858;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));background:-webkit-linear-gradient(top, #585858 0%, #111 100%);background:-moz-linear-gradient(top, #585858 0%, #111 100%);background:-ms-linear-gradient(top, #585858 0%, #111 100%);background:-o-linear-gradient(top, #585858 0%, #111 100%);background:linear-gradient(to bottom, #585858 0%, #111 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:none;background-color:#2b2b2b;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));background:-webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);box-shadow:inset 0 0 3px #111}.dataTables_wrapper .dataTables_paginate .ellipsis{padding:0 1em}.dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background-color:white;background:-webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));background:-webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%)}.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter,.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate{color:#333}.dataTables_wrapper .dataTables_scroll{clear:both}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{*margin-top:-1px;-webkit-overflow-scrolling:touch}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing,.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing{height:0;overflow:hidden;margin:0 !important;padding:0 !important}.dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.dataTables_wrapper.no-footer div.dataTables_scrollHead table,.dataTables_wrapper.no-footer div.dataTables_scrollBody table{border-bottom:none}.dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width: 767px){.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.dataTables_wrapper .dataTables_paginate{margin-top:0.5em}}@media screen and (max-width: 640px){.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter{float:none;text-align:center}.dataTables_wrapper .dataTables_filter{margin-top:0.5em}} + +.pmui-pmlabelfield .pmui-textlabel { + background: #aaaaaa; +} + +/* +.pmui-gridpanel { + padding: 10px 20px; +}*/ +.pmui-gridpanel-pager .list-item-ajax a { + position: relative; + float: left; + padding: 6px 12px; + line-height: 1.42857143; + text-decoration: none; + color: #428bca; + background-color: #fff; + border: 1px solid #ddd; + margin: 0 0 0 -1px; + min-width: inherit; + font-size: 14px; + border-radius: 2px; +} + +.pmui-gridpanel-pager .list-item-ajax { + margin: 0px; +} + +.pmui-gridpanel-gotoPage { + padding: 6px 14px 6px 14px; + margin: 0px; + background-color: #f7f7f7; + text-align: left; + color: #555; + border-radius: 2px; +} + +.pmui-gridpanel-pager .list-item-ajax a:hover { + color: #2a6496; + background-color: #eee; + border-color: #ddd; +} + +/*@import "base"; + +.pmui-pmform { + margin-left: 20px; + margin-right: 20px; +} + + +.pmui-background { + background-color: $PMUI-FORM-BACKGROUND; +} + +.pmui-window-footer { + padding-left: 20px; + padding-right: 20px; +} + +.pmui-window-footer > button-solid { + margin-left: 5px; + margin-right: 5px; + margin-bottom: 5px; + +} + +div.pmui-window-footer > a.button-solid { + margin-left: 7px; + margin-top: 5px; + margin-bottom: 5px; + background: $MAFE-FORM-BUTTONS-BACKGROUND; + padding: 6px 15px; +} + +div.pmui-form-footer > a.button-solid { + margin-left: 7px; + margin-top: 5px; + margin-bottom: 5px; + background: $MAFE-FORM-BUTTONS-BACKGROUND; + padding: 6px 15px; +} + +.pmui-buttonpanel { + padding-right: 10px; + padding-left: 10px; + text-align: right; +}*/ + +body { + font-family: 'SourceSansProRegular', Arial, Tahoma, Verdana; + background: #fff; + margin: 0; + padding: 0; +} + +/*IE9*/ +/**::selection*/ +/*.content_control::selection +{ + background-color:transparent; +} +.content_control::-moz-selection +{ + background-color:transparent; +}*/ +* { + /*You just need this if you are only concerned with android and not desktop browsers.*/ + -webkit-tap-highlight-color: transparent; +} + +/* BPMN */ +#p-center-layout { + -webkit-user-select: none; + -moz-user-select: -moz-none; + user-select: none; +} + +/** +* Canvas +*/ +.pmui-pmcanvas { + background-image: url(../img/bg_designer.gif); +} + +/** +* ToolbarPanel +*/ +.mafe-toolbarpanel-btn { + text-decoration: none; + list-style: none; + text-align: center; +} + +.mafe-toolbarpanel-btn-span { + font-size: 10px; +} + +.mafe-toolbarpanel-btn-img { + width: 30px; + height: 30px; +} + +.mafe-toolbarpanel-tooltip { + font-size: 10px; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + -moz-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; + background-color: #6D87B7; + color: white; +} + +.mafe-email { + background: url(../img/email.png) no-repeat; +} + +/* +* For buttons that are on the north from the Layout +*/ +.ui-layout-north a { + margin-left: 2px; +} + +/** + * Shapes + */ +.mafe-shape-sprite { + background: url("../img/mafe_sprite.png") no-repeat; +} + +[class^="mafe-activity-task-"], +[class*=" mafe-activity-task-"], +[class^="mafe-event-"], +[class*=" mafe-event-"], +[class^="mafe-gateway-"], +[class*=" mafe-gateway-"], +[class^="PM-decorator_"], +[class*=" PM-decorator_"], +[class^="mafe-usertask-marker-"], +[class*=" mafe-usertask-marker-"], +[class^="mafe-sendtask-marker-"], +[class*=" mafe-sendtask-marker-"], +[class^="mafe-receivetask-marker-"], +[class*=" mafe-receivetask-marker-"], +[class^="mafe-usertask-marker-"], +[class*=" mafe-usertask-marker-"], +[class^="mafe-servicetask-marker-"], +[class*=" mafe-servicetask-marker-"], +[class^="mafe-scripttask-marker-"], +[class*=" mafe-scripttask-marker-"], +[class^="mafe-manualtask-marker-"], +[class*=" mafe-manualtask-marker-"], +[class^="mafe-businessrule-marker-"], +[class*=" mafe-businessrule-marker-"], +[class^="mafe-collapsed-marker-"], +[class*="mafe-parallel-marker-"], +[class*="mafe-sequential-marker-"], +[class*="mafe-loop-marker-"], +[class*="mafe-style-error-marker-"], +[class^="mafe-data"], +[class*=" mafe-data"], +[class^="mafe-message"], +[class*=" mafe-message"], +[class^="mafe-sequence"], +[class*=" mafe-sequence"], +[class^="mafe-association"], +[class*=" mafe-association"], +[class^="mafe-default"], +[class*=" mafe-default"] { + background-image: url("../img/mafe_sprite.png"); + background-repeat: no-repeat; + background-position: -565px -510px; +} + +.mafe-activity-task-red { + background-color: #BD0A17; + border: 1px solid #72020C; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-green { + background-color: #1B7909; + border: 1px solid #0F5502; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-orange { + background-color: #C57701; + border: 1px solid #965B02; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-silver { + background-color: #AAA8A6; + border: 1px solid #6F6D6C; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-artifact-group { + border: 1px dashed #995E06; +} + +.mafe-artifact-annotation { + /*background-color: #fbf1ce;*/ + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; +} + +.mafe-artifact-annotation-close { + float: right; + background: url("../img/delete.png") no-repeat center; + width: 10px; + height: 10px; + cursor: pointer; +} + +.mafe-layer-line-vertical { + visibility: visible; + background-color: transparent; + border-left-width: 1px; + border-left-style: solid; + border-left-color: red; + border-top-width: 0px; + border-top-style: solid; + border-top-color: red; + overflow: hidden; +} + +.mafe-layer-line-horizontal { + background-color: transparent; + border-left-width: 0px; + border-left-style: solid; + border-left-color: red; + border-top-width: 1px; + border-top-style: solid; + border-top-color: red; + overflow: hidden; +} + +.mafe-participant { + background-color: white; + border: 2px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 6px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; +} + +.mafe-pool { + border: 2px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 6px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; + background-color: white; +} + +/*mafe sprite*/ +.mafe-association_100_target_bottom { + background-position: 0 -9162px; +} + +.mafe-association_100_target_left { + background-position: 0 -9184px; +} + +.mafe-association_100_target_right { + background-position: 0 -9251px; +} + +.mafe-association_100_target_top { + background-position: 0 -9173px; +} + +.mafe-association_125_target_bottom { + background-position: 0 -9048px; +} + +.mafe-association_125_target_left { + background-position: 0 -9136px; +} + +.mafe-association_125_target_right { + background-position: 0 -9149px; +} + +.mafe-association_125_target_top { + background-position: 0 -9093px; +} + +.mafe-association_150_target_bottom { + background-position: 0 -8993px; +} + +.mafe-association_150_target_left { + background-position: 0 -11416px; +} + +.mafe-association_150_target_right { + background-position: 0 -9106px; +} + +.mafe-association_150_target_top { + background-position: 0 -9018px; +} + +.mafe-association_50_target_bottom { + background-position: 0 -9791px; +} + +.mafe-association_50_target_left { + background-position: 0 -9797px; +} + +.mafe-association_50_target_right { + background-position: 0 -9893px; +} + +.mafe-association_50_target_top { + background-position: 0 -9824px; +} + +.mafe-association_75_target_bottom { + background-position: 0 -9506px; +} + +.mafe-association_75_target_left { + background-position: 0 -9525px; +} + +.mafe-association_75_target_right { + background-position: 0 -9569px; +} + +.mafe-association_75_target_top { + background-position: 0 -9533px; +} + +.mafe-businessrule-marker-10 { + background-position: 0 -11431px; +} + +.mafe-businessrule-marker-15 { + background-position: 0 -11360px; +} + +.mafe-businessrule-marker-21 { + background-position: 0 -11225px; +} + +.mafe-businessrule-marker-26 { + background-position: 0 -11334px; +} + +.mafe-businessrule-marker-31 { + background-position: 0 -11441px; +} + +.mafe-collapsed-marker-10 { + background-position: 0 -9008px; +} + +.mafe-collapsed-marker-15 { + background-position: 0 -8518px; +} + +.mafe-collapsed-marker-21 { + background-position: 0 -8357px; +} + +.mafe-collapsed-marker-26 { + background-position: 0 -8378px; +} + +.mafe-collapsed-marker-31 { + background-position: 0 -8947px; +} + +.mafe-datainput-marker-10 { + background-position: 0 -9322px; +} + +.mafe-datainput-marker-15 { + background-position: 0 -8978px; +} + +.mafe-datainput-marker-21 { + background-position: 0 -8616px; +} + +.mafe-datainput-marker-26 { + background-position: 0 -8548px; +} + +.mafe-datainput-marker-31 { + background-position: 0 -11179px; +} + +.mafe-dataobject-100 { + background-position: 0 -8010px; +} + +.mafe-dataobject-125 { + background-position: 0 -7886px; +} + +.mafe-dataobject-150 { + background-position: 0 -11000px; +} + +.mafe-dataobject-50 { + background-position: 0 -8650px; +} + +.mafe-dataobject-75 { + background-position: 0 -8242px; +} + +.mafe-dataoutput-marker-10 { + background-position: 0 -9433px; +} + +.mafe-dataoutput-marker-15 { + background-position: 0 -9033px; +} + +.mafe-dataoutput-marker-21 { + background-position: 0 -8906px; +} + +.mafe-dataoutput-marker-26 { + background-position: 0 -8870px; +} + +.mafe-dataoutput-marker-31 { + background-position: 0 -11385px; +} + +.mafe-datastore-20 { + background-position: 0 -7643px; +} + +.mafe-datastore-30 { + background-position: 0 -5709px; +} + +.mafe-datastore-41 { + background-position: 0 -3780px; +} + +.mafe-datastore-51 { + background-position: 0 -1972px; +} + +.mafe-datastore-61 { + background-position: 0 -4076px; +} + +.mafe-default_100_source_bottom { + background-position: 0 -9577px; +} + +.mafe-default_100_source_left { + background-position: 0 -9605px; +} + +.mafe-default_100_source_right { + background-position: 0 -9588px; +} + +.mafe-default_100_source_top { + background-position: 0 -9558px; +} + +.mafe-default_125_source_bottom { + background-position: 0 -9443px; +} + +.mafe-default_125_source_left { + background-position: 0 -9480px; +} + +.mafe-default_125_source_right { + background-position: 0 -9493px; +} + +.mafe-default_125_source_top { + background-position: 0 -9456px; +} + +.mafe-default_150_source_bottom { + background-position: 0 -9262px; +} + +.mafe-default_150_source_left { + background-position: 0 -9061px; +} + +.mafe-default_150_source_right { + background-position: 0 -9077px; +} + +.mafe-default_150_source_top { + background-position: 0 -9347px; +} + +.mafe-default_50_source_bottom { + background-position: 0 -9984px; +} + +.mafe-default_50_source_left { + background-position: 0 -9974px; +} + +.mafe-default_50_source_right { + background-position: 0 -9963px; +} + +.mafe-default_50_source_top { + background-position: 0 -9979px; +} + +.mafe-default_75_source_bottom { + background-position: 0 -9877px; +} + +.mafe-default_75_source_left { + background-position: 0 -9922px; +} + +.mafe-default_75_source_right { + background-position: 0 -9899px; +} + +.mafe-default_75_source_top { + background-position: 0 -9885px; +} + +.mafe-event-boundary-compensationthrow-16 { + background-position: 0 -7394px; +} + +.mafe-event-boundary-compensationthrow-24 { + background-position: 0 -5883px; +} + +.mafe-event-boundary-compensationthrow-33 { + background-position: 0 -3335px; +} + +.mafe-event-boundary-compensationthrow-41 { + background-position: 0 -1080px; +} + +.mafe-event-boundary-compensationthrow-49 { + background-position: 0 -198px; +} + +.mafe-event-boundary-conditional-16 { + background-position: 0 -8083px; +} + +.mafe-event-boundary-conditional-24 { + background-position: 0 -6889px; +} + +.mafe-event-boundary-conditional-33 { + background-position: 0 -5277px; +} + +.mafe-event-boundary-conditional-41 { + background-position: 0 -4137px; +} + +.mafe-event-boundary-conditional-49 { + background-position: 0 -3401px; +} + +.mafe-event-boundary-empty-16 { + background-position: 0 -7963px; +} + +.mafe-event-boundary-empty-24 { + background-position: 0 -6680px; +} + +.mafe-event-boundary-empty-33 { + background-position: 0 -4610px; +} + +.mafe-event-boundary-empty-41 { + background-position: 0 -2426px; +} + +.mafe-event-boundary-empty-49 { + background-position: 0 -1031px; +} + +.mafe-event-boundary-errorcatch-1 { + background-position: 0 -11375px; +} + +.mafe-event-boundary-errorcatch-16 { + background-position: 0 -10867px; +} + +.mafe-event-boundary-errorcatch-2 { + background-position: 0 -11061px; +} + +.mafe-event-boundary-errorcatch-24 { + background-position: 0 -10426px; +} + +.mafe-event-boundary-errorcatch-3 { + background-position: 0 -10664px; +} + +.mafe-event-boundary-errorcatch-33 { + background-position: 0 -9203px; +} + +.mafe-event-boundary-errorcatch-4 { + background-position: 0 -10328px; +} + +.mafe-event-boundary-errorcatch-41 { + background-position: 0 -7458px; +} + +.mafe-event-boundary-errorcatch-49 { + background-position: 0 -5931px; +} + +.mafe-event-boundary-errorcatch-5 { + background-position: 0 -10798px; +} + +.mafe-event-boundary-linkcatch-16 { + background-position: 0 -7555px; +} + +.mafe-event-boundary-linkcatch-24 { + background-position: 0 -5980px; +} + +.mafe-event-boundary-linkcatch-33 { + background-position: 0 -3673px; +} + +.mafe-event-boundary-linkcatch-41 { + background-position: 0 -1387px; +} + +.mafe-event-boundary-linkcatch-49 { + background-position: 0 -357px; +} + +.mafe-event-boundary-linkthrow-16 { + background-position: 0 -7499px; +} + +.mafe-event-boundary-linkthrow-24 { + background-position: 0 -6028px; +} + +.mafe-event-boundary-linkthrow-33 { + background-position: 0 -3887px; +} + +.mafe-event-boundary-linkthrow-41 { + background-position: 0 -1651px; +} + +.mafe-event-boundary-linkthrow-49 { + background-position: 0 -702px; +} + +.mafe-event-boundary-messagecatch-16 { + background-position: 0 -7742px; +} + +.mafe-event-boundary-messagecatch-24 { + background-position: 0 -6165px; +} + +.mafe-event-boundary-messagecatch-33 { + background-position: 0 -3994px; +} + +.mafe-event-boundary-messagecatch-41 { + background-position: 0 -2072px; +} + +.mafe-event-boundary-messagecatch-49 { + background-position: 0 -849px; +} + +.mafe-event-boundary-messagecatch-enabled-16 { + background-position: 0 -11246px; +} + +.mafe-event-boundary-messagecatch-enabled-24 { + background-position: 0 -10819px; +} + +.mafe-event-boundary-messagecatch-enabled-33 { + background-position: 0 -10565px; +} + +.mafe-event-boundary-messagecatch-enabled-41 { + background-position: 0 -10235px; +} + +.mafe-event-boundary-messagecatch-enabled-49 { + background-position: 0 -9616px; +} + +.mafe-event-boundary-messagethrow-16 { + background-position: 0 -11318px; +} + +.mafe-event-boundary-messagethrow-24 { + background-position: 0 -10940px; +} + +.mafe-event-boundary-messagethrow-33 { + background-position: 0 -10631px; +} + +.mafe-event-boundary-messagethrow-41 { + background-position: 0 -10359px; +} + +.mafe-event-boundary-messagethrow-49 { + background-position: 0 -10145px; +} + +.mafe-event-boundary-multiplecatch-16 { + background-position: 0 -7426px; +} + +.mafe-event-boundary-multiplecatch-24 { + background-position: 0 -5835px; +} + +.mafe-event-boundary-multiplecatch-33 { + background-position: 0 -3014px; +} + +.mafe-event-boundary-multiplecatch-41 { + background-position: 0 -949px; +} + +.mafe-event-boundary-multiplecatch-49 { + background-position: 0 0; +} + +.mafe-event-boundary-multiplethrow-16 { + background-position: 0 -7258px; +} + +.mafe-event-boundary-multiplethrow-24 { + background-position: 0 -5739px; +} + +.mafe-event-boundary-multiplethrow-33 { + background-position: 0 -3269px; +} + +.mafe-event-boundary-multiplethrow-41 { + background-position: 0 -1305px; +} + +.mafe-event-boundary-multiplethrow-49 { + background-position: 0 -604px; +} + +.mafe-event-boundary-parallelcatch-16 { + background-position: 0 -7338px; +} + +.mafe-event-boundary-parallelcatch-24 { + background-position: 0 -5787px; +} + +.mafe-event-boundary-parallelcatch-33 { + background-position: 0 -3047px; +} + +.mafe-event-boundary-parallelcatch-41 { + background-position: 0 -1223px; +} + +.mafe-event-boundary-parallelcatch-49 { + background-position: 0 -455px; +} + +.mafe-event-boundary-signalcatch-16 { + background-position: 0 -7587px; +} + +.mafe-event-boundary-signalcatch-24 { + background-position: 0 -6100px; +} + +.mafe-event-boundary-signalcatch-33 { + background-position: 0 -3821px; +} + +.mafe-event-boundary-signalcatch-41 { + background-position: 0 -1428px; +} + +.mafe-event-boundary-signalcatch-49 { + background-position: 0 -98px; +} + +.mafe-event-boundary-signalthrow-16 { + background-position: 0 -7603px; +} + +.mafe-event-boundary-signalthrow-24 { + background-position: 0 -6076px; +} + +.mafe-event-boundary-signalthrow-33 { + background-position: 0 -3854px; +} + +.mafe-event-boundary-signalthrow-41 { + background-position: 0 -1559px; +} + +.mafe-event-boundary-signalthrow-49 { + background-position: 0 -800px; +} + +.mafe-event-boundary-timer-16 { + background-position: 0 -7854px; +} + +.mafe-event-boundary-timer-24 { + background-position: 0 -6369px; +} + +.mafe-event-boundary-timer-33 { + background-position: 0 -4372px; +} + +.mafe-event-boundary-timer-41 { + background-position: 0 -2344px; +} + +.mafe-event-boundary-timer-49 { + background-position: 0 -1733px; +} + +.mafe-event-end-cancelthrow-16 { + background-position: 0 -7726px; +} + +.mafe-event-end-cancelthrow-24 { + background-position: 0 -6503px; +} + +.mafe-event-end-cancelthrow-33 { + background-position: 0 -4528px; +} + +.mafe-event-end-cancelthrow-41 { + background-position: 0 -2508px; +} + +.mafe-event-end-cancelthrow-49 { + background-position: 0 -1872px; +} + +.mafe-event-end-compensationthrow-16 { + background-position: 0 -7758px; +} + +.mafe-event-end-compensationthrow-24 { + background-position: 0 -6575px; +} + +.mafe-event-end-compensationthrow-33 { + background-position: 0 -4899px; +} + +.mafe-event-end-compensationthrow-41 { + background-position: 0 -3146px; +} + +.mafe-event-end-compensationthrow-49 { + background-position: 0 -2254px; +} + +.mafe-event-end-email-16 { + background-position: 0 -8288px; +} + +.mafe-event-end-email-24 { + background-position: 0 -7290px; +} + +.mafe-event-end-email-33 { + background-position: 0 -6823px; +} + +.mafe-event-end-email-41 { + background-position: 0 -6230px; +} + +.mafe-event-end-email-49 { + background-position: 0 -5458px; +} + +.mafe-event-end-empty-16 { + background-position: 0 -8481px; +} + +.mafe-event-end-empty-24 { + background-position: 0 -7515px; +} + +.mafe-event-end-empty-33 { + background-position: 0 -6704px; +} + +.mafe-event-end-empty-41 { + background-position: 0 -5589px; +} + +.mafe-event-end-empty-49 { + background-position: 0 -4479px; +} + +.mafe-event-end-errorthrow-16 { + background-position: 0 -8168px; +} + +.mafe-event-end-errorthrow-24 { + background-position: 0 -7186px; +} + +.mafe-event-end-errorthrow-33 { + background-position: 0 -6312px; +} + +.mafe-event-end-errorthrow-41 { + background-position: 0 -5195px; +} + +.mafe-event-end-errorthrow-49 { + background-position: 0 -4561px; +} + +.mafe-event-end-messagethrow-16 { + background-position: 0 -8304px; +} + +.mafe-event-end-messagethrow-24 { + background-position: 0 -7314px; +} + +.mafe-event-end-messagethrow-33 { + background-position: 0 -6856px; +} + +.mafe-event-end-messagethrow-41 { + background-position: 0 -6271px; +} + +.mafe-event-end-messagethrow-49 { + background-position: 0 -5507px; +} + +.mafe-event-end-multiplethrow-16 { + background-position: 0 -7710px; +} + +.mafe-event-end-multiplethrow-24 { + background-position: 0 -6551px; +} + +.mafe-event-end-multiplethrow-33 { + background-position: 0 -4866px; +} + +.mafe-event-end-multiplethrow-41 { + background-position: 0 -3550px; +} + +.mafe-event-end-multiplethrow-49 { + background-position: 0 -2639px; +} + +.mafe-event-end-signalthrow-16 { + background-position: 0 -8272px; +} + +.mafe-event-end-signalthrow-24 { + background-position: 0 -7370px; +} + +.mafe-event-end-signalthrow-33 { + background-position: 0 -6985px; +} + +.mafe-event-end-signalthrow-41 { + background-position: 0 -6441px; +} + +.mafe-event-end-signalthrow-49 { + background-position: 0 -5660px; +} + +.mafe-event-end-terminatethrow-16 { + background-position: 0 -8404px; +} + +.mafe-event-end-terminatethrow-24 { + background-position: 0 -7234px; +} + +.mafe-event-end-terminatethrow-33 { + background-position: 0 -6737px; +} + +.mafe-event-end-terminatethrow-41 { + background-position: 0 -6189px; +} + +.mafe-event-end-terminatethrow-49 { + background-position: 0 -5343px; +} + +.mafe-event-intermediate-compensationthrow-16 { + background-position: 0 -7410px; +} + +.mafe-event-intermediate-compensationthrow-24 { + background-position: 0 -5907px; +} + +.mafe-event-intermediate-compensationthrow-33 { + background-position: 0 -3368px; +} + +.mafe-event-intermediate-compensationthrow-41 { + background-position: 0 -1121px; +} + +.mafe-event-intermediate-compensationthrow-49 { + background-position: 0 -247px; +} + +.mafe-event-intermediate-conditional-16 { + background-position: 0 -8099px; +} + +.mafe-event-intermediate-conditional-24 { + background-position: 0 -6913px; +} + +.mafe-event-intermediate-conditional-33 { + background-position: 0 -5310px; +} + +.mafe-event-intermediate-conditional-41 { + background-position: 0 -4178px; +} + +.mafe-event-intermediate-conditional-49 { + background-position: 0 -3450px; +} + +.mafe-event-intermediate-email-16 { + background-position: 0 -8115px; +} + +.mafe-event-intermediate-email-24 { + background-position: 0 -7018px; +} + +.mafe-event-intermediate-email-33 { + background-position: 0 -5392px; +} + +.mafe-event-intermediate-email-41 { + background-position: 0 -4219px; +} + +.mafe-event-intermediate-email-49 { + background-position: 0 -2867px; +} + +.mafe-event-intermediate-linkcatch-16 { + background-position: 0 -7571px; +} + +.mafe-event-intermediate-linkcatch-24 { + background-position: 0 -6004px; +} + +.mafe-event-intermediate-linkcatch-33 { + background-position: 0 -3706px; +} + +.mafe-event-intermediate-linkcatch-41 { + background-position: 0 -1469px; +} + +.mafe-event-intermediate-linkcatch-49 { + background-position: 0 -406px; +} + +.mafe-event-intermediate-linkthrow-16 { + background-position: 0 -7539px; +} + +.mafe-event-intermediate-linkthrow-24 { + background-position: 0 -6052px; +} + +.mafe-event-intermediate-linkthrow-33 { + background-position: 0 -3920px; +} + +.mafe-event-intermediate-linkthrow-41 { + background-position: 0 -1692px; +} + +.mafe-event-intermediate-linkthrow-49 { + background-position: 0 -751px; +} + +.mafe-event-intermediate-messagecatch-16 { + background-position: 0 -11272px; +} + +.mafe-event-intermediate-messagecatch-24 { + background-position: 0 -10843px; +} + +.mafe-event-intermediate-messagecatch-33 { + background-position: 0 -10598px; +} + +.mafe-event-intermediate-messagecatch-41 { + background-position: 0 -2303px; +} + +.mafe-event-intermediate-messagecatch-419 { + background-position: 0 -10194px; +} + +.mafe-event-intermediate-messagecatch-49 { + background-position: 0 -10070px; +} + +.mafe-event-intermediate-messagethrow-16 { + background-position: 0 -8131px; +} + +.mafe-event-intermediate-messagethrow-24 { + background-position: 0 -7042px; +} + +.mafe-event-intermediate-messagethrow-33 { + background-position: 0 -5425px; +} + +.mafe-event-intermediate-messagethrow-41 { + background-position: 0 -4260px; +} + +.mafe-event-intermediate-messagethrow-49 { + background-position: 0 -2916px; +} + +.mafe-event-intermediate-multiplecatch-16 { + background-position: 0 -7442px; +} + +.mafe-event-intermediate-multiplecatch-24 { + background-position: 0 -5859px; +} + +.mafe-event-intermediate-multiplecatch-33 { + background-position: 0 -3080px; +} + +.mafe-event-intermediate-multiplecatch-41 { + background-position: 0 -990px; +} + +.mafe-event-intermediate-multiplecatch-49 { + background-position: 0 -49px; +} + +.mafe-event-intermediate-multiplethrow-16 { + background-position: 0 -7274px; +} + +.mafe-event-intermediate-multiplethrow-24 { + background-position: 0 -5763px; +} + +.mafe-event-intermediate-multiplethrow-33 { + background-position: 0 -3302px; +} + +.mafe-event-intermediate-multiplethrow-41 { + background-position: 0 -1346px; +} + +.mafe-event-intermediate-multiplethrow-49 { + background-position: 0 -653px; +} + +.mafe-event-intermediate-parallelcatch-16 { + background-position: 0 -7354px; +} + +.mafe-event-intermediate-parallelcatch-24 { + background-position: 0 -5811px; +} + +.mafe-event-intermediate-parallelcatch-33 { + background-position: 0 -3113px; +} + +.mafe-event-intermediate-parallelcatch-41 { + background-position: 0 -1264px; +} + +.mafe-event-intermediate-parallelcatch-49 { + background-position: 0 -504px; +} + +.mafe-event-intermediate-signalcatch-16 { + background-position: 0 -8051px; +} + +.mafe-event-intermediate-signalcatch-24 { + background-position: 0 -6937px; +} + +.mafe-event-intermediate-signalcatch-33 { + background-position: 0 -5162px; +} + +.mafe-event-intermediate-signalcatch-41 { + background-position: 0 -3953px; +} + +.mafe-event-intermediate-signalcatch-49 { + background-position: 0 -2205px; +} + +.mafe-event-intermediate-signalthrow-16 { + background-position: 0 -8067px; +} + +.mafe-event-intermediate-signalthrow-24 { + background-position: 0 -6961px; +} + +.mafe-event-intermediate-signalthrow-33 { + background-position: 0 -5556px; +} + +.mafe-event-intermediate-signalthrow-41 { + background-position: 0 -4301px; +} + +.mafe-event-intermediate-signalthrow-49 { + background-position: 0 -2965px; +} + +.mafe-event-intermediate-timer-16 { + background-position: 0 -7870px; +} + +.mafe-event-intermediate-timer-24 { + background-position: 0 -6393px; +} + +.mafe-event-intermediate-timer-33 { + background-position: 0 -4405px; +} + +.mafe-event-intermediate-timer-41 { + background-position: 0 -2385px; +} + +.mafe-event-intermediate-timer-49 { + background-position: 0 -1782px; +} + +.mafe-event-start-conditional-16 { + background-position: 0 -7838px; +} + +.mafe-event-start-conditional-24 { + background-position: 0 -6527px; +} + +.mafe-event-start-conditional-33 { + background-position: 0 -4737px; +} + +.mafe-event-start-conditional-41 { + background-position: 0 -3739px; +} + +.mafe-event-start-conditional-49 { + background-position: 0 -2818px; +} + +.mafe-event-start-empty-16 { + background-position: 0 -8226px; +} + +.mafe-event-start-empty-24 { + background-position: 0 -7619px; +} + +.mafe-event-start-empty-33 { + background-position: 0 -6623px; +} + +.mafe-event-start-empty-41 { + background-position: 0 -5236px; +} + +.mafe-event-start-empty-49 { + background-position: 0 -4027px; +} + +.mafe-event-start-messagecatch-16 { + background-position: 0 -8184px; +} + +.mafe-event-start-messagecatch-24 { + background-position: 0 -7210px; +} + +.mafe-event-start-messagecatch-33 { + background-position: 0 -6770px; +} + +.mafe-event-start-messagecatch-41 { + background-position: 0 -6124px; +} + +.mafe-event-start-messagecatch-49 { + background-position: 0 -5023px; +} + +.mafe-event-start-multiplecatch-16 { + background-position: 0 -7774px; +} + +.mafe-event-start-multiplecatch-24 { + background-position: 0 -6656px; +} + +.mafe-event-start-multiplecatch-33 { + background-position: 0 -4833px; +} + +.mafe-event-start-multiplecatch-41 { + background-position: 0 -2777px; +} + +.mafe-event-start-multiplecatch-49 { + background-position: 0 -2023px; +} + +.mafe-event-start-parallelcatch-16 { + background-position: 0 -7694px; +} + +.mafe-event-start-parallelcatch-24 { + background-position: 0 -6599px; +} + +.mafe-event-start-parallelcatch-33 { + background-position: 0 -4770px; +} + +.mafe-event-start-parallelcatch-41 { + background-position: 0 -3591px; +} + +.mafe-event-start-parallelcatch-49 { + background-position: 0 -2549px; +} + +.mafe-event-start-signalcatch-16 { + background-position: 0 -7806px; +} + +.mafe-event-start-signalcatch-24 { + background-position: 0 -6417px; +} + +.mafe-event-start-signalcatch-33 { + background-position: 0 -4643px; +} + +.mafe-event-start-signalcatch-41 { + background-position: 0 -3187px; +} + +.mafe-event-start-signalcatch-48 { + background-position: 0 -2688px; +} + +.mafe-event-start-signalcatch-49 { + background-position: 0 -7822px; +} + +.mafe-event-start-timer-16 { + background-position: 0 -7790px; +} + +.mafe-event-start-timer-24 { + background-position: 0 -6345px; +} + +.mafe-event-start-timer-33 { + background-position: 0 -10471px; +} + +.mafe-event-start-timer-41 { + background-position: 0 -2467px; +} + +.mafe-event-start-timer-49 { + background-position: 0 -1510px; +} + +.mafe-gateway-complex-20 { + background-position: 0 -7126px; +} + +.mafe-gateway-complex-30 { + background-position: 0 -5132px; +} + +.mafe-gateway-complex-41 { + background-position: 0 -3632px; +} + +.mafe-gateway-complex-51 { + background-position: 0 -2113px; +} + +.mafe-gateway-complex-61 { + background-position: 0 -4962px; +} + +.mafe-gateway-eventbased-20 { + background-position: 0 -7086px; +} + +.mafe-gateway-eventbased-30 { + background-position: 0 -4803px; +} + +.mafe-gateway-eventbased-41 { + background-position: 0 -2164px; +} + +.mafe-gateway-eventbased-51 { + background-position: 0 -553px; +} + +.mafe-gateway-eventbased-61 { + background-position: 0 -296px; +} + +.mafe-gateway-exclusive-20 { + background-position: 0 -7166px; +} + +.mafe-gateway-exclusive-30 { + background-position: 0 -5102px; +} + +.mafe-gateway-exclusive-41 { + background-position: 0 -3228px; +} + +.mafe-gateway-exclusive-51 { + background-position: 0 -1921px; +} + +.mafe-gateway-exclusive-61 { + background-position: 0 -10009px; +} + +.mafe-gateway-exclusiveeventbased-20 { + background-position: 0 -7106px; +} + +.mafe-gateway-exclusiveeventbased-30 { + background-position: 0 -4932px; +} + +.mafe-gateway-exclusiveeventbased-41 { + background-position: 0 -2598px; +} + +.mafe-gateway-exclusiveeventbased-51 { + background-position: 0 -898px; +} + +.mafe-gateway-exclusiveeventbased-61 { + background-position: 0 -1162px; +} + +.mafe-gateway-inclusive-20 { + background-position: 0 -7066px; +} + +.mafe-gateway-inclusive-30 { + background-position: 0 -5072px; +} + +.mafe-gateway-inclusive-41 { + background-position: 0 -2736px; +} + +.mafe-gateway-inclusive-51 { + background-position: 0 -1600px; +} + +.mafe-gateway-inclusive-61 { + background-position: 0 -8420px; +} + +.mafe-gateway-parallel-20 { + background-position: 0 -7146px; +} + +.mafe-gateway-parallel-30 { + background-position: 0 -5630px; +} + +.mafe-gateway-parallel-41 { + background-position: 0 -4438px; +} + +.mafe-gateway-parallel-51 { + background-position: 0 -3499px; +} + +.mafe-gateway-parallel-61 { + background-position: 0 -10504px; +} + +.mafe-gateway-paralleleventbased-20 { + background-position: 0 -6803px; +} + +.mafe-gateway-paralleleventbased-30 { + background-position: 0 -4342px; +} + +.mafe-gateway-paralleleventbased-41 { + background-position: 0 -1831px; +} + +.mafe-gateway-paralleleventbased-51 { + background-position: 0 -147px; +} + +.mafe-gateway-paralleleventbased-61 { + background-position: 0 -4676px; +} + +.mafe-loop-marker-10 { + background-position: 0 -8937px; +} + +.mafe-loop-marker-15 { + background-position: 0 -8588px; +} + +.mafe-loop-marker-21 { + background-position: 0 -8497px; +} + +.mafe-loop-marker-26 { + background-position: 0 -8200px; +} + +.mafe-loop-marker-31 { + background-position: 0 -7979px; +} + +.mafe-manualtask-marker-10 { + background-position: 0 -11288px; +} + +.mafe-manualtask-marker-15 { + background-position: 0 -10964px; +} + +.mafe-manualtask-marker-21 { + background-position: 0 -10777px; +} + +.mafe-manualtask-marker-26 { + background-position: 0 -10690px; +} + +.mafe-manualtask-marker-31 { + background-position: 0 -10716px; +} + +.mafe-message_100_source_bottom, +.mafe-message_100_source_top, +.mafe-message_100_source_left, +.mafe-message_100_source_right { + background-position: 0 -8859px; +} + +.mafe-message_100_target_bottom { + background-position: 0 -8806px; +} + +.mafe-message_100_target_left { + background-position: 0 -8795px; +} + +.mafe-message_100_target_right { + background-position: 0 -8784px; +} + +.mafe-message_100_target_top { + background-position: 0 -8817px; +} + +.mafe-message_125_source_bottom, +.mafe-message_125_source_top, +.mafe-message_125_source_left, +.mafe-message_125_source_right { + background-position: 0 -8726px; +} + +.mafe-message_125_target_bottom { + background-position: 0 -8637px; +} + +.mafe-message_125_target_left { + background-position: 0 -8685px; +} + +.mafe-message_125_target_right { + background-position: 0 -8698px; +} + +.mafe-message_125_target_top { + background-position: 0 -8603px; +} + +.mafe-message_150_source_bottom, +.mafe-message_150_source_top, +.mafe-message_150_source_left, +.mafe-message_150_source_right { + background-position: 0 -8739px; +} + +.mafe-message_150_target_bottom { + background-position: 0 -8769px; +} + +.mafe-message_150_target_left { + background-position: 0 -8754px; +} + +.mafe-message_150_target_right { + background-position: 0 -8711px; +} + +.mafe-message_150_target_top { + background-position: 0 -8670px; +} + +.mafe-message_50_source_bottom, +.mafe-message_50_source_top, +.mafe-message_50_source_left, +.mafe-message_50_source_right { + background-position: 0 -9725px; +} + +.mafe-message_50_target_bottom { + background-position: 0 -9599px; +} + +.mafe-message_50_target_left { + background-position: 0 -9402px; +} + +.mafe-message_50_target_right { + background-position: 0 -9408px; +} + +.mafe-message_50_target_top { + background-position: 0 -9541px; +} + +.mafe-message_75_source_bottom, +.mafe-message_75_source_top, +.mafe-message_75_source_left, +.mafe-message_75_source_right { + background-position: 0 -9414px; +} + +.mafe-message_75_target_bottom { + background-position: 0 -9278px; +} + +.mafe-message_75_target_left { + background-position: 0 -9128px; +} + +.mafe-message_75_target_right { + background-position: 0 -9195px; +} + +.mafe-message_75_target_top { + background-position: 0 -9286px; +} + +.mafe-parallel-marker-10 { + background-position: 0 -9989px; +} + +.mafe-parallel-marker-15 { + background-position: 0 -9907px; +} + +.mafe-parallel-marker-21 { + background-position: 0 -9803px; +} + +.mafe-parallel-marker-26 { + background-position: 0 -9691px; +} + +.mafe-parallel-marker-31 { + background-position: 0 -9846px; +} + +.mafe-receivetask-marker-10 { + background-position: 0 -11298px; +} + +.mafe-receivetask-marker-15 { + background-position: 0 -11133px; +} + +.mafe-receivetask-marker-21 { + background-position: 0 -10979px; +} + +.mafe-receivetask-marker-26 { + background-position: 0 -10914px; +} + +.mafe-receivetask-marker-31 { + background-position: 0 -10883px; +} + +.mafe-scripttask-marker-10 { + background-position: 0 -11262px; +} + +.mafe-scripttask-marker-15 { + background-position: 0 -10762px; +} + +.mafe-scripttask-marker-21 { + background-position: 0 -10450px; +} + +.mafe-scripttask-marker-26 { + background-position: 0 -10400px; +} + +.mafe-scripttask-marker-31 { + background-position: 0 -10297px; +} + +.mafe-sendtask-marker-10 { + background-position: 0 -11308px; +} + +.mafe-sendtask-marker-15 { + background-position: 0 -11210px; +} + +.mafe-sendtask-marker-21 { + background-position: 0 -11148px; +} + +.mafe-sendtask-marker-26 { + background-position: 0 -11076px; +} + +.mafe-sendtask-marker-31 { + background-position: 0 -11102px; +} + +.mafe-sequence_100_target_bottom { + background-position: 0 -9547px; +} + +.mafe-sequence_100_target_left { + background-position: 1px -9469px; +} + +.mafe-sequence_100_target_right { + background-position: -1px -9422px; +} + +.mafe-sequence_100_target_top { + background-position: 0 -9514px; +} + +.mafe-sequence_125_target_bottom { + background-position: 0 -9363px; +} + +.mafe-sequence_125_target_left { + background-position: 1px -9376px; +} + +.mafe-sequence_125_target_right { + background-position: 0 -9294px; +} + +.mafe-sequence_125_target_top { + background-position: 0 -9389px; +} + +.mafe-sequence_150_target_bottom { + background-position: 0 -9307px; +} + +.mafe-sequence_150_target_left { + background-position: 2px -11472px; +} + +.mafe-sequence_150_target_right { + background-position: -1px -9332px; +} + +.mafe-sequence_150_target_top { + background-position: 0 -9235px; +} + +.mafe-sequence_50_target_bottom { + background-position: 0 -9951px; +} + +.mafe-sequence_50_target_left { + background-position: 0 -9957px; +} + +.mafe-sequence_50_target_right { + background-position: 0 -9968px; +} + +.mafe-sequence_50_target_top { + background-position: 0 -9945px; +} + +.mafe-sequence_75_target_bottom { + background-position: 0 -9752px; +} + +.mafe-sequence_75_target_left { + background-position: 0 -9838px; +} + +.mafe-sequence_75_target_right { + background-position: 0 -9830px; +} + +.mafe-sequence_75_target_top { + background-position: 0 -9717px; +} + +.mafe-sequential-marker-10 { + background-position: 0 -9999px; +} + +.mafe-sequential-marker-15 { + background-position: 0 -9930px; +} + +.mafe-sequential-marker-21 { + background-position: 0 -9731px; +} + +.mafe-sequential-marker-26 { + background-position: 0 -9665px; +} + +.mafe-sequential-marker-31 { + background-position: 0 -9760px; +} + +.mafe-servicetask-marker-10 { + background-position: 0 -11169px; +} + +.mafe-servicetask-marker-15 { + background-position: 0 -10747px; +} + +.mafe-servicetask-marker-21 { + background-position: 0 -10276px; +} + +.mafe-servicetask-marker-26 { + background-position: 0 -10119px; +} + +.mafe-servicetask-marker-31 { + background-position: 0 -8828px; +} + +.mafe-usertask-marker-10 { + background-position: 0 -8927px; +} + +.mafe-usertask-marker-15 { + background-position: 0 -8533px; +} + +.mafe-usertask-marker-21 { + background-position: 0 -6482px; +} + +.mafe-usertask-marker-26 { + background-position: 0 -7937px; +} + +.mafe-usertask-marker-31 { + background-position: 0 -7663px; +} + +/*******end sprite***********/ +.mafe-toolbar-sprite { + background-image: url(../img/bpmn_sprite_with_zoom.png); + background-repeat: no-repeat; + width: 16px; + height: 16px; + display: inline-block; +} + +.mafe-toolbar-size { + width: 17px; + height: 17px; + display: block; + margin: 2px 0 2px 2px; +} + +.mafe-toolbar-container { + padding-left: 0; +} + +.mafe-toolbar-rectangle-size { + width: 17px; + height: 13px; + display: block; + margin: 2px 0 2px 2px; +} + +/** +* PMTask Menu +*/ +.mafe-menu-task-steps { + background: url(../img/steps.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-users-action { + background: url(../img/users.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-delete-rules-action { + background: url(../img/delete_rules.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-delete-action { + background: url(../img/delete.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-properties-action { + background: url(../img/dynaforms.gif) no-repeat; + background-size: 20px 20px; +} + +/** +* Tree Menu +*/ +.mafe-menu-tree-disable { + background: url(../img/deactivate.png) no-repeat; +} + +.mafe-menu-tree-enable { + background: url(../img/activate.png) no-repeat; +} + +/** +* Sub process Menu +*/ +.mafe-menu-rules-action { + background: url(../img/rules.png) no-repeat; + background-size: 20px 20px; +} + +/** +* Toolbar Menu +*/ +.mafe-menu-toolbar-blank-dynaform { + background: url(../img/form.gif) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-toolbar-copyimport-dynaform { + background: url(../img/edit-table.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-label-annotation span { + color: black; +} + +/** +* Input Document +*/ +.mafe-inputDocument-newinput { + background-position: 0 -199px; + margin: 10px 0 10px 20px; +} + +/* BUTTON UID*/ +/*a.mafe-button-uid:link,a.mafe-button-uid:visited{ + display: block; + color: #e77e23; + font-size: 14px; + font-weight: 700; + line-height: 24px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #fdf8e2; + width: 90%; + height: 24px; + margin: 4px auto; + padding: 0 5px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} +a.mafe-button-uid:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} +.mafe-button-uid .pmui-button-label { + color: #e77e23; + font-weight:bold; +}*/ +/* BUTTON NEW*/ +/*a.mafe-button-new:link,a.mafe-button-new:visited{ + float: right; + display: block; + color: #fff; + line-height: 45px; + text-decoration: none; + background: #e77e23 url(../img/ico_mor2.png) no-repeat 5px center; + background-size : 25px; + padding: 6px 38px 6px 33px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + max-width: 80%; + height: auto; +} +a.mafe-button-new:hover{ + background: #e77e23 url(../img/ico_mor2.png) no-repeat 96% center; + background-size : 25px; + padding: 6px 38px 6px 33px; +} +.mafe-button-new .pmui-button-label { + text-transform:capitalize; +}*/ +/* BUTTON EDIT*/ +/*a.mafe-button-edit:link,a.mafe-button-edit:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #19bd9b; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-edit:hover{ + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +}*/ +/* BUTTON DELETE*/ +/*a.mafe-button-delete:link,a.mafe-button-delete:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #e84c3d; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-delete:hover { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +}*/ +/* BUTTON PROPERTIES*/ +/*a.mafe-button-properties:link,a.mafe-button-properties:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #3D78E5; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-properties:hover { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} +a.mafe-button-img-delete { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-delete .pmui-button-icon { + background-image: url(../img/delete.png); + background-repeat: no-repeat; + display: inline-block; + width: 19px; + height: 18px; +} +a.mafe-button-img-delete .pmui-button-label { + display: none; +} +a.mafe-button-img-edit { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-edit .pmui-button-icon { + background-image: url(../img/edit.gif); + background-repeat: no-repeat; + display: inline-block; + width: 23px; + height: 20px; +} +a.mafe-button-img-edit .pmui-button-label { + display: none; +} + +a.mafe-button-img-properties { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-properties .pmui-button-icon { + background-image: url(../img/edit-table.png); + background-repeat: no-repeat; + display: inline-block; + width: 17px; + height: 16px; +} +a.mafe-button-img-properties .pmui-button-label { + display: none; +} + +.mafe-button-text{ + background-color :#FDFDFD; +} +.mafe-button-text .pmui-button-label{ + background-color :#FDFDFD; + color: black; + text-transform:capitalize; +} +*/ +/* ToolbarPanel */ +.mafe-toolbarpanel-btn { + text-decoration: none; + list-style: none; + text-align: center; +} + +.mafe-toolbarpanel-btn-span { + font-size: 10px; +} + +.mafe-toolbarpanel-btn-img { + width: 30px; + height: 30px; +} + +.mafe-toolbarpanel-tooltip { + font-size: 10px; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + -moz-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; + background-color: #6D87B7; + color: white; +} + +/** + * Styles for arrows + */ +.mafe-decorator_50_target_right { + border-bottom: 3px solid transparent; + border-top: 3px solid transparent; + border-right: 6px solid black; +} + +.mafe-decorator_75_target_right { + border-bottom: 4px solid transparent; + border-top: 4px solid transparent; + border-right: 8px solid black; +} + +.mafe-decorator_100_target_right { + border-bottom: 5px solid transparent; + border-top: 5px solid transparent; + border-right: 10px solid black; +} + +.mafe-decorator_125_target_right { + border-bottom: 6px solid transparent; + border-top: 6px solid transparent; + border-right: 12px solid black; +} + +.mafe-decorator_150_target_right { + border-bottom: 7px solid transparent; + border-top: 7px solid transparent; + border-right: 14px solid black; +} + +.mafe-decorator_50_target_bottom { + border-left: 3px solid transparent; + border-right: 3px solid transparent; + border-bottom: 6px solid black; +} + +.mafe-decorator_75_target_bottom { + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-bottom: 8px solid black; +} + +.mafe-decorator_100_target_bottom { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 10px solid black; +} + +.mafe-decorator_125_target_bottom { + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-bottom: 12px solid black; +} + +.mafe-decorator_150_target_bottom { + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-bottom: 14px solid black; +} + +.mafe-decorator_50_target_left { + border-bottom: 3px solid transparent; + border-top: 3px solid transparent; + border-left: 6px solid black; +} + +.mafe-decorator_75_target_left { + border-bottom: 4px solid transparent; + border-top: 4px solid transparent; + border-left: 8px solid black; +} + +.mafe-decorator_100_target_left { + border-bottom: 5px solid transparent; + border-top: 5px solid transparent; + border-left: 10px solid black; +} + +.mafe-decorator_125_target_left { + border-bottom: 6px solid transparent; + border-top: 6px solid transparent; + border-left: 12px solid black; +} + +.mafe-decorator_150_target_left { + border-bottom: 7px solid transparent; + border-top: 7px solid transparent; + border-left: 14px solid black; +} + +.mafe-decorator_50_target_top { + border-left: 3px solid transparent; + border-right: 3px solid transparent; + border-top: 6px solid black; +} + +.mafe-decorator_75_target_top { + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 8px solid black; +} + +.mafe-decorator_100_target_top { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-top: 10px solid black; +} + +.mafe-decorator_125_target_top { + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-top: 12px solid black; +} + +.mafe-decorator_150_target_top { + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-top: 14px solid black; +} + +/* ---------------------------- NAV ---------------------------- */ +.navBar { + background: #3397e2; + color: #fff; + height: auto; + left: 0px; + position: fixed; + /*top: 1px;*/ + width: 97%; + z-index: 2; + padding: 0 1% 0 2%; + display: none; + border: 1px solid #2979b8; +} + +.navBar .head { + background-color: #3b4753; + cursor: move; + font-size: 12px; + height: 16px; + overflow: hidden; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; +} + +.navBar nav { + position: relative; + font-size: 11px; + height: 35px; + float: right; + font-weight: 600; +} + +.navBar nav ul { + position: relative; + list-style: none; + height: 35px; + margin: 0; + padding: 0; +} + +.navBar nav ul li { + float: right; + border-right: 1px solid #70b5ec; + border-left: 1px solid #70b5ec; + padding: 2px 5px; +} + +.navBar nav ul li:hover { + background-color: #2979b4; + border-right: 1px solid #2979b8; + border-left: 1px solid #2979b8; +} + +.navBar nav ul li:last-child { + border: 0; +} + +.navBar nav ul li a { + display: inline-block; + color: #fff; + line-height: 31px; + text-align: center; + text-decoration: none; + background-color: transparent; + height: 29px; + padding: 0 10px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + cursor: pointer; +} + +.navBar nav ul li b { + display: inline-block; + color: #fff; + line-height: 31px; + text-align: center; + text-decoration: none; + background-color: transparent; + height: 29px; + padding: 0 10px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + cursor: pointer; +} + +.navBar nav ul li input { + height: 31px; + width: 58px; + padding: 5px; +} + +.navBar .processName { + width: 55%; + float: left; + /*border: 1px solid red; */ +} + +.navBar .buttonSection { + /*border: 1px solid green; */ + width: 40%; + /* don't want this */ + float: right; +} + +.navBar h2 { + /*float: left;*/ + text-align: left; + font-size: 12px; + font-weight: 700px; + line-height: 35px; + margin: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +a.mafe-button-save:link, a.mafe-button-save:visited { + width: 70px; +} + +.mafe-save-process { + color: white; + background: #19bd9b; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; + border-left: 1px solid lightgray !important; + border-right: 1px solid lightgray !important; + border-bottom: 1px solid lightgray !important; + padding-right: 25px !important; +} + +li.mafe-redo { + margin-top: -2px; +} + +li.mafe-undo { + margin-top: -2px; +} + +a.mafe-button-save:hover { + /*background: #16a085 !important;*/ + color: white; +} + +.mafe-dropdown-zoom { + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + font-size: 12px; +} + +.mafe-dropdown-zoom option { + font-size: 12px; +} + +a.mafe-button-fullscreen:link, a.mafe-button-fullscreen:visited { + float: left; + display: block; + outline: none; + text-indent: -9000px; + text-decoration: none; + background: url(../img/mafe-tools.png) no-repeat; + background-position: 0 -1036px; + width: 11px; + margin: 0 5px 0 5px; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; +} + +a.mafe-button-fullscreen:hover { + -ms-transform: scale(1); + -webkit-transform: scale(1); + -moz-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); +} + +/* ---------------------------- NAV ---------------------------- */ +/* ---------------------------- PANELES ---------------------------- */ +.content { + /*position: relative; + background: url(../img/bg_designer.gif) repeat; + width: 100%; + height: 700px; + overflow: auto;*/ +} + +.bpmn_shapes { + /*right: 20px;*/ + border: 1px solid #d6d7d9; + background-color: #e9e9e9; + /*width: 88px;*/ + padding-top: 5px; + padding-bottom: 5px; + /*overflow: visible;*/ + z-index: 1; + position: fixed; + top: 35px; + left: 0px; + height: 31px; + width: 100%; + display: none; +} + +.bpmn_shapes .head { + background-color: #d5d8dd; + height: 16px; + cursor: move; +} + +.bpmn_shapes .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.bpmn_shapes .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.bpmn_shapes ul:nth-child(2) { + border-top: none; +} + +.bpmn_shapes ul:last-child { + border-bottom: 0; +} + +.bpmn_shapes ul { + position: relative; + overflow: hidden; + list-style: none; + width: 96%; + margin: 0 0%; + padding: 4px 0; + display: inline; +} + +.bpmn_shapes ul li { + display: inline-block; + margin-top: 2px; + margin: 0 4px; + margin-top: 2px; + padding: 0; +} + +.bpmn_shapes ul li a { + float: left; + display: inline-block; + color: #fff; + line-height: 10px; + text-align: center; + text-decoration: none; + padding: 3px 4px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls { + top: 90px; + right: 20px; + font-size: 11px; + border: 1px solid #d8dbdf; + background-color: #3397e2; + width: 200px; + z-index: 1; + position: fixed; + font-weight: 700; + display: none; +} + +.content_controls .head { + background-color: #3b4753; + height: 18px; + cursor: move; +} + +.content_controls .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.content_controls ul { + float: left; + position: relative; + overflow: hidden; + list-style: none; + width: 96%; + margin: 0 2%; + padding: 0; +} + +.content_controls ul li:first-child { + border-top: 0; +} + +.content_controls ul li:last-child { + border-bottom: 0; +} + +.content_controls ul li { + float: left; + display: inline-block; + border-bottom: 1px solid #20669D; + width: 100%; + margin: 0; + padding: 3px 0; +} + +.content_controls ul li:hover { + background-color: #2979b4; +} + +.content_controls ul li a { + float: left; + display: inline-block; + color: #fff; + line-height: 23px; + text-align: center; + text-decoration: none; + padding: 3px 3px; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls li { + position: relative; +} + +a.btn_create { + float: right; + position: absolute; + right: 0px; + top: 1px; +} + +a.btn_create:link, a.btn_create:visited { + float: right; + display: block; + color: #fff; + line-height: 23px; + text-decoration: none; + background: transparent url(../img/btn_create.png) no-repeat center !important; + width: 20px; + height: 23px; + padding: 3px 0; + filter: alpha(opacity=50); + -moz-opacity: 0.50; + -khtml-opacity: 0.50; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; +} + +a.btn_create span { + filter: alpha(opacity=0); + -moz-opacity: 0.00; + -khtml-opacity: 0.00; + opacity: 0.00; +} + +a.btn_create:hover { + background: #20bb99 url(../img/btn_create.png) no-repeat 5px center !important; + width: 45px; + height: 23px; + padding: 3px 0 3px 18px; + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} + +a.btn_create:hover span { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} + +.bpmn_shapes_legend { + /*top: 1px;*/ + /*right: 20px;*/ + border: 1px solid #d6d7d9; + background-color: #e9e9e9; + width: 250px; + padding-bottom: 2px; + overflow: visible; + z-index: 1; + position: fixed; + right: 20px; + top: 70px; + display: none; +} + +.bpmn_shapes_legend .head { + background-color: #d5d8dd; + height: 16px; + cursor: move; +} + +.bpmn_shapes_legend .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.bpmn_shapes_legend .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.bpmn_shapes_legend .icon-legend { + height: 20px; + width: 50px; + margin: 5px; + display: inline-block; +} + +.bpmn_shapes_legend .text-legend { + font-size: small; + display: inline-block; + margin-top: 9px; +} + +/* ---------------------------- PANELES ---------------------------- */ +/* ---------------------------- ELEMENTOS BASE ---------------------------- */ +.bold { + font-weight: 700; +} + +.small { + font-size: 12px; +} + +.color2 { + color: #f46500; +} + +/* ---------------------------- ELEMENTOS BASE ---------------------------- */ +.mafe-shapes-toggle { + background-image: url("../img/shapes-toogle.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 16px; + margin-top: 2px; +} + +.mafe-shapes-plus { + background-image: url("../img/plus.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 16px; + margin-top: 2px; +} + +.mafe-shapes-refresh { + background-image: url("../img/shapes-refresh.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 14px; + background-size: 10px; + margin-top: 4px; +} + +.mafe-process-object { + color: white; + margin-top: 3px; + margin-left: 7px; + float: left; +} + +/* + toolbar sprite +*/ +.mafe-sprite, .mafe-fullscream, .mafe-toolbar-annotation, .mafe-toolbar-blackbox, .mafe-toolbar-boundary, .mafe-toolbar-data-object, .mafe-toolbar-data-store, .mafe-toolbar-end-message, .mafe-toolbar-end, .mafe-toolbar-gateway-exclusive, .mafe-toolbar-gateway-inclusive, .mafe-toolbar-gateway-parallel, .mafe-toolbar-group, .mafe-toolbar-horizontal-line, .mafe-toolbar-horizontal-text, .mafe-toolbar-intermediate-receive-mesage, .mafe-toolbar-intermediate-send-mesage, .mafe-toolbar-lane, .mafe-toolbar-participant, .mafe-toolbar-pool, .mafe-toolbar-start-message, .mafe-toolbar-start-timer, .mafe-toolbar-start, .mafe-toolbar-subprocess, .mafe-toolbar-task, .mafe-toolbar-vertical-line, .mafe-toolbar-vertical-text, .mafe-button-redo, .mafe-button-undo, .mafe-button-close, .mafe-toolbar-lasso, .mafe-toolbar-help, .mafe-toolbar-end-email, .mafe-toolbar-intermediate-email, .mafe-toolbar-event-intermediate-timer, .mafe-toolbar-event-start-timer, .mafe-toolbar-validation, .mafe-validator-close, .mafe-icon-error, .mafe-icon-warning { + background: url("../img/mafe-tools.png") no-repeat; + width: 23px; + height: 23px; +} + +.mafe-button-close { + background-position: 0 -966px; +} + +.mafe-button-close:hover, .mafe-button-close.button-close_hover, .mafe-button-close.button-close-hover { + background-position: 0 -1156px; +} + +.mafe-button-redo { + background-position: 0 -888px; +} + +.mafe-button-redo:hover, .mafe-button-redo.button-redo_hover, .mafe-button-redo.button-redo-hover { + background-position: 0 -863px; +} + +.mafe-button-undo { + background-position: 0 -837px; +} + +.mafe-button-undo:hover, .mafe-button-undo.button-undo_hover, .mafe-button-undo.button-undo-hover { + background-position: 0 -913px; +} + +.mafe-fullscream { + background-position: 0 -1036px; +} + +.mafe-icon-error { + background-position: 0 -1256px; +} + +.mafe-icon-warning { + background-position: 0 -1271px; +} + +.mafe-plus { + background-position: 0 -790px; +} + +.mafe-shapes-refresh { + background-position: 0 -952px; +} + +.mafe-shapes-toogle { + background-position: 0 -938px; +} + +.mafe-toolbar-annotation { + background-position: 0 -730px; +} + +.mafe-toolbar-blackbox { + background-position: 0 -530px; +} + +.mafe-toolbar-boundary { + background-position: 0 -120px; +} + +.mafe-toolbar-data-object { + background-position: 0 -1066px; +} + +.mafe-toolbar-data-store { + background-position: 0 -300px; +} + +.mafe-toolbar-easy { + background-position: 0 -450px; +} + +.mafe-toolbar-end-email { + background-position: 0 -390px; +} + +.mafe-toolbar-end-message { + background-position: 0 -150px; +} + +.mafe-toolbar-end { + background-position: 0 -240px; +} + +.mafe-toolbar-event-intermediate-timer { + background-position: 0 -270px; +} + +.mafe-toolbar-event-start-timer { + background-position: 0 -620px; +} + +.mafe-toolbar-gateway-exclusive { + background-position: 0 -420px; +} + +.mafe-toolbar-gateway-inclusive { + background-position: 0 -360px; +} + +.mafe-toolbar-gateway-parallel { + background-position: 0 -470px; +} + +.mafe-toolbar-group { + background-position: 0 -560px; +} + +.mafe-toolbar-help { + background-position: 0 -680px; +} + +.mafe-toolbar-help:hover, .mafe-toolbar-help.toolbar-help_hover, .mafe-toolbar-help.toolbar-help-hover { + background-position: 0 -705px; +} + +.mafe-toolbar-horizontal-line { + background-position: 0 -1196px; +} + +.mafe-toolbar-horizontal-text { + background-position: 0 -807px; +} + +.mafe-toolbar-intermediate-email { + background-position: 0 -210px; +} + +.mafe-toolbar-intermediate-receive-mesage { + background-position: 0 0; +} + +.mafe-toolbar-intermediate-send-mesage { + background-position: 0 -30px; +} + +.mafe-toolbar-lane { + background-position: 0 -500px; +} + +.mafe-toolbar-lasso { + background-position: 0 -330px; +} + +.mafe-toolbar-participant { + background-position: 0 -1096px; +} + +.mafe-toolbar-pool { + background-position: 0 -590px; +} + +.mafe-toolbar-start-message { + background-position: 0 -60px; +} + +.mafe-toolbar-start-timer { + background-position: 0 -650px; +} + +.mafe-toolbar-start { + background-position: 0 -180px; +} + +.mafe-toolbar-subprocess { + background-position: 0 -1006px; +} + +.mafe-toolbar-task { + background-position: 0 -1126px; +} + +.mafe-toolbar-validation { + background-position: 0 -90px; +} + +.mafe-toolbar-vertical-line { + background-position: 0 -1226px; +} + +.mafe-toolbar-vertical-text { + background-position: 0 -760px; +} + +.mafe-validator-close { + background-position: 0 -1176px; +} + +.mafe-validator-close:hover, .mafe-validator-close.validator-close_hover, .mafe-validator-close.validator-close-hover { + background-position: 0 -986px; +} + +/*end toolbar sprite**/ +span.mafe-button-redo { + width: 22px; + height: 24px; + display: block; + margin-top: 4px; +} + +span.mafe-button-undo { + width: 22px; + height: 24px; + display: block; + margin-top: 4px; +} + +span.mafe-button-close { + width: 20px; + height: 20px; + display: block; + margin-top: 7px; +} + +span.mafe-validator-close { + width: 20px; + height: 20px; + display: block; + margin: 4px 8px 4px 4px; +} + +a.mafe-close { + margin: -1px; +} + +span.mafe-toolbar-help { + width: 23px; + height: 23px; + display: block; + margin-top: 2px; +} + +span.mafe-toolbar-validation { + width: 9px; + height: 20px; + display: block; + margin-top: 6px; +} + +/** + * Tooltip for actions + */ +.mafe-action-tooltip { + font-size: 10px; + background-color: #ECF0F1; +} + +/** + * Tooltip Black + */ +.ui-tooltip.mafe-action-tooltip-black { + background: black; + color: white; +} + +/** Rotate Label **/ +.rotateText { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -ms-transform: rotate(-90deg); + /* IE9+ */ + -moz-transform: rotate(-90deg); + /* Firefox */ + -o-transform: rotate(-90deg); + /* Opera */ + -webkit-transform: rotate(-90deg); + /* Safari & Chrome */ + transform: rotate(-90deg); + display: block; + float: center; + margin: 0 10px 0; +} + +.rotateControl { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -ms-transform: rotate(90deg); + /* IE9+ */ + -moz-transform: rotate(90deg); + /* Firefox */ + -o-transform: rotate(90deg); + /* Opera */ + -webkit-transform: rotate(90deg); + /* Safari & Chrome */ + transform: rotate(90deg); + display: block; + float: right; + margin: 0 10px 0; +} + +.mafe-textarea-resize .pmui-textareacontrol { + resize: vertical; +} + +.dropableClass { + background-color: #e2eae3; +} + +.loader { + position: fixed; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + z-index: 9999; + background: url("../img/loading.gif") 50% 50% no-repeat #f9f9f9; +} + +.screencast { + position: relative; + width: 480px; + height: 161px; + z-index: 9999; + background: url("../img/bpmnProcessmaker.gif") 50% 50% no-repeat #f9f9f9; +} + +.startcoronahelp { + position: relative; + height: 100px; + z-index: 9999; + background: url("../img/startcoronahelp.png") 50% 50% no-repeat; +} + +.mafe-button-menu { + display: inline-block; + vertical-align: top; + position: absolute; + top: 0px; + bottom: 2px; + padding-top: 5px; +} + +.mafe-button-menu img { + cursor: pointer; +} + +.mafe-button-menu-option { + padding: 7px; + color: black; + cursor: pointer; + position: absolute; + height: 14px; + width: 107px; + border: 1px solid lightgray; + background-color: #e8e8e8; + top: 2px; + left: -6px; +} + +.mafe-button-menu-option:hover { + background-color: lightgray; +} + +.mafe-button-menu-container { + position: relative; +} + +.mafe-can-connect-layer { + background-color: #9dee9d; + opacity: 0.4; +} + +.mafe-can-not-connect-layer { + background-color: #f590a5; + opacity: 0.4; +} + +.arrow_box { + position: absolute; + background: #ffffff; + border: 1px solid #BCBCBC; + padding-right: 5px; + font-size: smaller; + width: auto; + min-width: 27%; +} + +.arrow_box:after, .arrow_box:before { + right: 100%; + top: 10px; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none; +} + +.arrow_box:after { + border-color: rgba(255, 255, 255, 0); + border-right-color: #ffffff; + border-width: 7px; + margin-top: -7px; +} + +.arrow_box:before { + border-color: rgba(188, 188, 188, 0); + border-right-color: #BCBCBC; + border-width: 8px; + margin-top: -8px; +} + +.bpmn_validator { + /* background: #3397e2; */ + height: auto; + /* left: 0px; */ + /* position: fixed; */ + /* top: 68%; */ + width: 99.4%; + z-index: 2; + /* display: none; */ + border: 4px solid #E5E5E5; + visibility: hidden; + width: 100%; + position: fixed; + bottom: 0; + left: 0; +} + +.validator_header { + height: 28px; + background-color: #262A35; + color: #fff; +} + +.validator_body { + background-color: white; + font-size: smaller; +} + +.validator-close { + float: right; +} + +i.mafe-icon-error { + float: left; + height: 15px; + height: 15px; +} + +i.mafe-icon-warning { + float: left; + height: 15px; + height: 15px; +} + +.validator_header h2 { + text-align: left; + font-size: 12px; + line-height: 28px; + margin: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-left: 10px; + float: left; +} + +table.dataTable thead th, table.dataTable thead td { + padding: 10px 18px; + border-bottom: none; + background-color: #B6B6B6; + color: white; +} + +.dataTables_wrapper.no-footer .dataTables_scrollBody { + border-bottom: none; +} + +/* + * Sprite Validator Icons + */ +.mafe-sprite, .mafe-style-error-marker-10, .mafe-style-error-marker-14, .mafe-style-error-marker-17, .mafe-style-error-marker-21, .mafe-style-error-marker-7, .mafe-style-warning-marker-10, .mafe-style-warning-marker-14, .mafe-style-warning-marker-17, .mafe-style-warning-marker-21, .mafe-style-warning-marker-7 { + background-image: url("../img/mafe-validate.png"); + background-repeat: no-repeat; +} + +/* Icons for Errors */ +.mafe-style-error-marker-10 { + background-position: 0 0; +} + +.mafe-style-error-marker-14 { + background-position: 0 -10px; +} + +.mafe-style-error-marker-17 { + background-position: 0 -24px; +} + +.mafe-style-error-marker-21 { + background-position: 0 -41px; +} + +.mafe-style-error-marker-7 { + background-position: 0 -62px; +} + +/* Icons for Warning */ +.mafe-style-warning-marker-10 { + background-position: 0 -69px; +} + +.mafe-style-warning-marker-14 { + background-position: 0 -78px; +} + +.mafe-style-warning-marker-17 { + background-position: 0 -91px; +} + +.mafe-style-warning-marker-21 { + background-position: 0 -107px; +} + +.mafe-style-warning-marker-7 { + background-position: 0 -127px; +} + +.crown-container { + z-index: auto; + display: table; + padding-left: 4px; +} + +.crown-container .row { + display: table-row; +} + +.crown-container .row .item-crown { + display: table-cell; +} + +.mafe-corona-task { + background: url("../img/corona-task.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-task:hover { + background: url("../img/corona-task.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-gateway-exclusive { + background: url("../img/corona-gateway-exclusive.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-gateway-exclusive:hover { + background: url("../img/corona-gateway-exclusive.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-intermediate { + background: url("../img/corona-intermediate.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-intermediate:hover { + background: url("../img/corona-intermediate.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-end { + background: url("../img/corona-end.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-end:hover { + background: url("../img/corona-end.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-flow { + background: url("../img/corona-flow.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-flow:hover { + background: url("../img/corona-flow.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-settings { + background: url("../img/corona-settings.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-settings:hover { + background: url("../img/corona-settings.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-delete { + background: url("../img/corona-delete.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-delete:hover { + background: url("../img/corona-delete.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-textfield-rename { + background: url("../img/corona-textfield-rename.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-textfield-rename:hover { + background: url("../img/corona-textfield-rename.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +/*Dynaform Creation Buttons*/ +.pmui .mafeButton .pmMafeButtonsIconBlack { + background: #474747 url(../img/form.png) no-repeat center; + background-size: contain; + height: 55px; + width: 100px; + margin-top: 15px; +} + +.pmui .mafeButton .pmMafeButtonsIconPMTable { + background: #474747 url(../img/table.png) no-repeat center; + background-size: contain; + height: 55px; + width: 80px; + margin-top: 15px; +} + +.pmui .mafeButton .pmMafeButtonsIconCopy { + background: #474747 url(../img/copy_import.png) no-repeat center; + background-size: contain; + height: 55px; + width: 80px; + margin-top: 15px; +} + +.pmui.varButton-delete { + background: #e84c3d; + padding: 0 15px; +} + +.pmui.varButton-edit { + background: #19bd9b; + padding: 0 15px; +} + +/* AccordionItem */ +.pmui-accordion-item-header { + background-color: #DFE8F6; + border-top: 1px solid #ada9a9; + border-bottom: 1px solid #ada9a9; + cursor: pointer; + overflow-wrap: break-word; + padding: 2px; + text-align: left; +} + +/*.pmtrigger .newPmtrigger .pmui-treepanel-node-icon{ + background: grey; +}*/ +.pmcustomtrigger .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmcopytrigger .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmfunction .pmui-treepanel-node-father .pmui-treepanel-node-collapsed .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +/*accordion*/ +.pmcustomtrigger { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -63px -250px; +} + +.pmcopytrigger { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -65px -271px; +} + +.pmFunctions { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -66px -120px; +} + +.pmTrSharepoint { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -79px -92px; +} + +.pmTrAlfresco { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -72px -223px; +} + +.pmZimbra { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -78px -15px; +} + +.pmSugar { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -68px -152px; +} + +.pmTalend { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -85px -48px; +} + +.ui-tooltip { + overflow-wrap: break-word; +} + + +.mafe-designer-assigment-button { + background-color: #d7d9dd; + font-size: 10; + text-transform: none; +} + +.mafe-designer-assigment-grid .pmui-gridpanelcell { + text-align: left; +} + +.mafe-grid-button { + background-color: transparent; + height: 0; + padding: 0px 0px; +} + +.mafe-grid-button.button-icon-user .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: 1px -195px; + width: 14px; + height: 17px; + display: block; +} + +.mafe-grid-button.button-icon-group .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -2px -135px; + width: 22px; + height: 17px; + display: block; +} + +.mafe-grid-button .button-label { + display: none; +} + +.mafe-designer-assigment-grid .pmui-gridpanelcolumn { + background-color: #FFFFFF; + padding: 0px 10px; +} + +.mafe-designer-assigment-grid .mafe-assigment-panel { + padding: 0px 10px; +} + +/* PANEL */ +/* +.mafe-assigment-panel .pmui-panel { + background-color: transparent; +} + + +.mafe-assigment-panel-right{ + background-color:#eaebed; + padding-left: 10px; +} + +.mafe-assigment-panel-global { + background-color: transparent; + padding-left: 20px; + padding-right: 0px; +} */ +/* TEXT SEARCH */ +.pmui.pmui-textfield.mafe-assigment-search { + text-align: left; +} + +/* BUTTONS SEARCH */ +/* GRID ASSIGNES*/ +/*.mafe-designer-assigment-grid { + background-color: #FFFFFF; + text-align: left; + padding: 0px 0px; +} + +.mafe-designer-assigment-grid .pmui-gridpanel-table{ + min-height: 0em; +}*/ +.pmui-pmtooltipmessage .pmui-button-label { + color: #999999; + font-size: 10px; +} + +.pmui-pmtooltipmessage .mafe-tooltip-close { + background: transparent; + margin: 0px 0px; + padding: 0px 0px; + width: auto; + height: auto; + color: black; +} + +.pmui-pmtooltipmessage .mafe-tooltip-header { + background: #EEF1F6; + margin: 0px 7px; + padding: 4px 0px; + width: auto; + height: 6px; + color: black; +} + +.pmui-pmtooltipmessage .mafe-tooltip-body { + background: #EEF1F6; + padding: 10px; +} + +.pmui-pmtooltipmessage { + background: #FFFFFF; + font-size: 10; + border: 1px solid #e7e7e7; + -webkit-box-shadow: 2px 2px 5px 0px #999; + -moz-box-shadow: 2px 2px 5px 0px #999; + filter: shadow(color=#999999, direction=135, strength=2); +} + +#list-usersIngroup { + width: 175px; + max-height: 100px; + background: #eef1f6; +} + +#list-usersIngroup #list-usersIngroup-iem { + font-size: 13px; + text-overflow: ellipsis; + overflow: hidden; + display: block; + white-space: nowrap; + width: 175px; + color: #333333; +} + +#tooltipmessagecustombody { + float: left; + padding: 10px; +} + +#tooltipmessagecustom #header { + width: 100%; + padding: 2px; + height: 20px; + box-sizing: border-box; + background-color: #e7e7e7; +} + +#tooltipmessagecustom #header a { + float: right; + margin-right: 4px; + cursor: pointer; +} + +.pmui .mafe-button-img-properties .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -91px -270px; +} + +.pmui .mafe-button-img-edit .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -89px -292px; +} + +.pmui .mafe-button-img-delete .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmui .mafe-button-img-delete .button-icon, .pmui .mafe-button-img-edit .button-icon, .pmui .mafe-button-img-properties .button-icon { + width: 18px; + height: 18px; + display: inline-block; +} + +a.mafe-button-img-properties, a.mafe-button-img-delete, a.mafe-button-img-edit { + background-color: transparent; +} + +.pmui .mafe-button-img-properties .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -91px -270px; +} + +.pmui .mafe-button-img-edit .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -89px -292px; +} + +.pmui .mafe-button-img-delete .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmui .mafe-button-img-delete .button-icon, .pmui .mafe-button-img-edit .button-icon, .pmui .mafe-button-img-properties .button-icon { + width: 18px; + height: 18px; + display: inline-block; +} + +a.mafe-button-img-properties, a.mafe-button-img-delete, a.mafe-button-img-edit { + background-color: transparent; +} + +.itemsSteps .pmui-treepanel-node-father > .pmui-treepanel-node-title .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.itemsSteps .pmui-treepanel-node-leaf .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.treePanelTriggers .pmui-treepanel-node-father > .pmui-treepanel-node-title .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.treePanelTriggers .pmui-treepanel-node-leaf .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.itemsSteps { + border-radius: 7px; + background: white; + box-sizing: border-box; + border: 1px solid #ccc; +} + +.treePanelTriggers { + border-radius: '7px'; + border: 1px solid #ccc; + width: 216px; + overflow: auto; +} + +#accordionPanelTriggers .pmui-gridpanelcell-content { + padding: 0px; +} + +.mafe-step-arrow-up { + background: url(../img/arrow-up.png) no-repeat; + background-size: 20px 10px; + width: 20px; + height: 10px; + margin: 0px; + padding: 0px; +} + +.mafe-step-arrow-down { + background: url(../img/arrow-down.png) no-repeat; + background-size: 20px 10px; + width: 20px; + height: 10px; + margin: 0px; + padding: 0px; +} + +.steps-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + list-style: none; + height: 2em; + text-align: center; + color: #9b9b9b; +} + +.steps-placeholder .placeholder-index { + display: block; + padding: 7px; +} + +@charset "UTF-8"; +.mafe-col { + background: #676767; + /*background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod…EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #b0b1b3 0%, #939497 10%, #727375 91%, #595959 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b0b1b3), color-stop(10%,#939497), color-stop(91%,#727375), color-stop(100%,#595959)); + background: -webkit-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -o-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -ms-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: linear-gradient(to bottom, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b0b1b3', endColorstr='#595959',GradientType=0 );*/ + color: white; + font-size: 12px; + width: auto; + padding: 6px 15px; + font-weight: inherit; +} + +.mafe-body-properties { + font-size: 11px; +} + +.mafe-field-labelCell { + padding: 2px; + border-bottom: 1px solid #D6D6D6; +} + +.pmui-rowfield:hover { + background: #D6D6D6; +} + +.mafe-field-labelCell .pmui-textcontrol { + border: 1px solid white; +} + +.mafe-field-labelCell .pmui-textcontrol, .mafe-field-labelCell .pmui-dropdownlistcontrol { + font-size: 12px; +} + +.mafe-table-properties tr:nth-child(odd) { + background-color: #E5E5E5; +} + +.mafe-table-properties tr:nth-child(even) { + background-color: #F2F2F2; +} + +.mafe-field-labelCell .pmui-button { + color: #4e4d4d; + border-radius: 2px; + float: right; + border: 1px solid #b1b1b1; + background: -moz-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 91%, #bababa 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(10%, #eaeaea), color-stop(91%, #cfcfcf), color-stop(100%, #bababa)); + background: -webkit-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: -o-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: -ms-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: linear-gradient(to bottom, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); +} + +.pmui-rowfield .error { + outline: 1px solid #ecc3c2; + border: 1px solid white; +} + +.pmui-rowfield.error { + color: red; +} + +.pmui-pmformgrid { + padding: 1em 0 1em 1em; + box-sizing: border-box; + background: #f1f1f1; +} + +.pmdesigner-initialrow { + height: 10em !important; +} + +.pmdesigner-formgrid-head, +.pmdesigner-formgrid-headrow, +.pmdesigner-formgrid-headcell { + padding: 0; + height: 0; +} + +.pmdesigner-textMessageContent { + color: #777f8b; +} + +/*.pmdesigner-mainpanel-slec, +.pmdesigner-formgrid, +.pmdesigner-formgrid-bodyrow, +.pmdesigner-formgrid-bodycell { + box-sizing: border-box; + border-collapse: collapse; + border: 1px dotted #c0c0c0; +}*/ +.pmdesigner-formgrid-bodyrow { + background: white; +} + +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell { + background: #F0F0F0; +} + +.pmdesigner-rowhandler { + box-sizing: border-box; + background: url("../img/moveUpDown.png") no-repeat center rgba(224, 222, 222, 0.8); + display: inline-block; + padding: 0.3em; + position: absolute; + top: 0; + left: 0; + color: white; + cursor: move; +} + +.pmui-window.pmdesigner-dropdownconfig .pmui-window-body { + padding: 0 1em; +} + +.pmui-gridfieldcell.gridfieldcell-bodycell.pmui-containeritembehavior-hover, +.pmdesigner-formgrid-bodycell.pmui-containeritembehavior-hover { + border-style: dashed; + background: #FCF8D6; + border-color: #e9ca27; + border-width: 2px; + color: orange; +} + +.pmdesigner-formgrid-bodycell { + min-height: 2em; + background: white; +} + +.unique-cell { + text-align: center; + font-size: 30px; + color: #aaa8a8; + height: 5em; +} + +/* +.pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell.pmdesigner-active +{ + background: #ECECE9; + background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod?EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 91%, #bababa 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(10%,#eaeaea), color-stop(91%,#cfcfcf), color-stop(100%,#bababa)); + background: -webkit-linear-gradient(top, #ffffff 0%,#F1F3CA 10%,#cfcfcf 91%,#bababa 100%); + background: -o-linear-gradient(top, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + background: -ms-linear-gradient(top, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + background: linear-gradient(to bottom, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eaeaea', endColorstr='#cfcfcf',GradientType=0 ); +} +*/ +.pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmui-gridfieldcell.gridfieldcell-bodycell.pmdesigner-active { + background: #C0C0C0; + color: white; +} + +.pmdesigner-formgrid-bodycell .pmui-field-label { + color: inherit; +} + +.pmdesigner-formgrid-headcell { + width: 8.333333333333%; + box-sizing: border-box; +} + +#pmdesigner-mainpanel .pmui-contextmenu-target { + background: #F0F0F0; +} + +.pmdesigner-formpanel { + display: block; + border: 1px solid #e0e0e0; +} + +.pmdesigner-formpanel:hover { + background: #e0e0e0; +} + +.pmui.ui-layout-pane.right-layout-panel { + padding: 0px; +} + +.pmui.pmui-panel.pmdesigner-layout-eastpanel { + overflow-x: hidden; +} + +.toolbox-title { + display: block; + padding: 5px; + background: linear-gradient(to bottom, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + font-size: 14px; +} + +/*.pmui-accordion-item-header { + background: #b0b1b3; + background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod?EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #b0b1b3 0%, #939497 10%, #727375 91%, #595959 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b0b1b3), color-stop(10%,#939497), color-stop(91%,#727375), color-stop(100%,#595959)); + background: -webkit-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -o-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -ms-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: linear-gradient(to bottom, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b0b1b3', endColorstr='#595959',GradientType=0 ); + color: #F0F0F0; + border-color: #888; +}*/ +.pmui-containeritembehavior-placeholder { + visibility: visible; + background: rgba(128, 128, 128, 0.3); + border: 2px #888 dashed; + list-style: none; + height: 2em; +} + +/* +.pmui.pmui-listpanel.components-list { + border: none; +} +*/ +.toolbox-title { + display: block; + padding: 0.5em; + font-size: 15px; + background: #2d3e50; + color: white; +} + +.pmui.pmui-listpanel.components-list .pmui-listitem { + background: none; + border: none; +} + +.pmui.pmui-listpanel.components-list .pmui-listitem:hover { + background: #e0e0e0; +} + +.pmdesigner-controlslist .pmui-listitem .pmui-listitem-icon, .otherControlsList-list .pmui-listitem .pmui-listitem-icon { + background-image: url(../img/cmp-icons.png); + width: 16px; + height: 16px; +} + +.pmui-listitem.cmp-text .pmui-listitem-icon { + background-position: 0 -128px; +} + +.pmui-listitem.cmp-dropdown .pmui-listitem-icon { + background-position: 0 -144px; +} + +.pmui-listitem.cmp-checkbox .pmui-listitem-icon { + background-position: 0 -32px; +} + +.pmui-listitem.cmp-radio .pmui-listitem-icon { + background-position: 0 0; +} + +.pmui-listitem.cmp-label .pmui-listitem-icon { + background-position: 0 -64px; +} + +.pmui-listitem.cmp-datetime .pmui-listitem-icon { + background-position: 0 -16px; +} + +.pmui-listitem.cmp-fieldset .pmui-listitem-icon { + background-position: 0 -80px; +} + +.pmui-listitem.cmp-formpanel .pmui-listitem-icon { + background-position: 0 -48px; +} + +.pmui-listitem.cmp-textarea .pmui-listitem-icon { + background-position: 0 -96px; +} + +.pmui-listitem.controls-submit .pmui-listitem-icon { + background: url("../img/submit.png") no-repeat; + width: 33px; + height: 20px; +} + +.pmui-listitem.controls-button .pmui-listitem-icon { + background: url("../img/button.png") no-repeat; + width: 33px; + height: 20px; +} + +.pmui-listitem.grid-field .pmui-listitem-icon { + background: url("../img/icon_grid.png") no-repeat; + width: 33px; + height: 30px; +} + +.pmui-listitem.label-field .pmui-listitem-icon { + background: url("../img/label.png") no-repeat; + width: 33px; + height: 30px; + background-size: contain; +} + +.pmui-listitem.subForm-field .pmui-listitem-icon { + background: url("../img/subform.png") no-repeat; + width: 33px; + height: 30px; + background-size: contain; +} + +.pmui-listitem.fiel-field .pmui-listitem-icon { + background: url("../img/file2.png") no-repeat; + width: 24px; + height: 25px; +} + +.subFormList-list .pmdesigner-subform .pmui-listitem-icon { + background: url("../img/subform.png") no-repeat; + width: 20px; + height: 20px; + background-size: contain; +} + +.pmui-listitem.image-field .pmui-listitem-icon { + background: url("../img/image.png") no-repeat; + width: 24px; + height: 25px; + background-size: contain; +} + +.pmui-listitem.link-field .pmui-listitem-icon { + background: url("../img/link.png") no-repeat; + width: 24px; + height: 25px; + background-size: contain; +} + +.pmui-listitem.controls-title .pmui-listitem-icon { + background-position: 0 -112px; +} + +.pmui-window.pmdesigner-controlselector .pmui-window-body { + padding: 1em; +} + +.pmui-window.pmdesigner-dependencyFieldWindow .pmui-window-body { + padding: 1em; +} + +.pm-titleListFields { + margin-left: 40px; + font-weight: bold; + font-size: 20px; +} + +.pm-titleListDependent { + margin-left: 14px; + font-weight: bold; + font-size: 20px; +} + +.pm-dependentFieldsGrid .pmui-button { + background: #e84c3d; +} + +.pm-listFieldGrid .pmui-button { + background: #19bd9b; +} + +.pmdesigner-dependencyFieldWindow .pmui-window-body { + background: #faf8f8; +} + +.pm_labelfield .pmui-textcontrol { + border: 1px white; +} + +.pm-listFieldGrid .pmui-gridpanelcell-content { + padding: 2px; +} + +.pm-dependentFieldsGrid .pmui-gridpanelcell-content { + padding: 2px; +} + +.pm-listFieldGrid .pmui-gridpanel-toolbar { + height: 30px; +} + +.pm-dependentFieldsGrid .pmui-gridpanel-toolbar { + height: 30px; +} + +.pmdesigner-formgrid { + /*background: rgb(150, 150, 150);*/ + width: 99%; +} + +.pmdesigner-formgrid .emptyform { + width: 100%; + height: 10em; +} + +/*.pmdesigner-formgrid-bodyrow.my_row{ + border-left: 3px solid #c0c0c0; + border-bottom: 3px solid #c0c0c0; +}*/ +.pmdesigner-formgrid-bodycell.pmui-textcontrol { + width: 100%; +} + +.pmdesigner-formgrid-bodycell .pmui-buttonfield .pmui-field-control { + width: auto; +} + +.pmdesigner-formgrid-bodycell .pmui-datetimefield .icon-field { + background: url("../img/calendar.png") no-repeat; + display: inline-block; + padding: 0.6em; +} + +.pmui-pmsuggestfield .icon-field { + background: url("../img/suggest.png") no-repeat; + display: inline-block; + padding: 0.6em; + background-size: contain; +} + +/*.pmdesigner-formgrid-bodycell .pmui-field-textLabel{ + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; + position: relative; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: inherit; +}*/ +.pmdesigner-formgrid-bodycell .pmui-field-label { + padding: 6px 3px 6px 10px; +} + +.pmdesigner-formgrid-bodycell .pmui-field-textLabel { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; +} + +.pmdesigner-formgrid-bodycell.colspan_12-11 .pmui-field-control { + width: 73%; +} + +.pmdesigner-formgrid-bodycell.colspan_10-9 .pmui-field-control { + width: 72%; +} + +.pmdesigner-formgrid-bodycell.colspan_8-7 .pmui-field-control { + width: 70%; +} + +.pmdesigner-formgrid-bodycell.colspan_6 .pmui-field-control { + width: 69%; +} + +.pmdesigner-formgrid-bodycell.colspan_5 .pmui-field-control { + width: 68%; +} + +.pmdesigner-formgrid-bodycell.colspan_4 .pmui-field-control { + width: 65%; +} + +.pmdesigner-formgrid-bodycell.colspan_3 .pmui-field-control { + width: 61%; +} + +.pmdesigner-formgrid-bodycell.colspan_2 .pmui-field-control { + width: 53%; +} + +.pmdesigner-formgrid-bodycell.colspan_1 .pmui-field-control { + width: 26%; +} + +.pmdesigner-formgrid-bodycell .pmui-buttonfield .pmui-field-control { + text-align: center; +} + +/*custom styles formdesigner*/ +/*/////////////////////////////////////////////////////// +/ +/ +/ +/ + + +/ +/ +/ +/*/ +#designer-body .pmui-accordion-item-body { + background: #FFFFFF; + padding: 0 5px 0 5px; + background: #e0e0e0; +} + +.pmdesigner-mainlayout, #designer-body .right-layout-panel, .pmdesigner-layout-eastpanel { + background: #f1f1f1; +} + +#designer-body .pmui-accordion-item-body .pmui-listitem { + padding: 3px; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem { + color: white; + border-bottom: 2px solid #d6d6d6; + background: white; + cursor: move; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem:hover { + color: black; + background: #e0e0e0; +} + +#designer-body .pmListItem-buttonEdit { + background: white; + color: white; + border: none; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem:hover .pmListItem-buttonEdit { + background-color: #19bd9b; +} + +#designer-body .pmui-accordion-item-header { + font-size: 13px; +} + +#designer-body .pmui-accordion-item-container { + border-left: 1px solid white; + border-right: 1px solid white; +} + +#designer-body .pmui-accordion-item-header .pmui-textcontrol { + outline: none; + margin-left: 10px; +} + +#designer-body .right-layout-panel .pmui-listpanel-toolbar { + display: none; +} + +#designer-body .pmui-accordion-item-header { + background: #676E7C; + color: white; + border-color: #d8dbdf; + padding: 3px 0 6px 0; +} + +#designer-body .otherControlsList-list { + background: white; +} + +#designer-body .otherControlsList-list .pmui-listitem { + background: white; + color: black; + border-style: none; +} + +#designer-body .otherControlsList-list .pmui-listitem:hover { + background: #e0e0e0; + color: black; +} + +#designer-body .ui-layout-pane { + overflow: initial; +} + +#designer-body { + background: #c0c0c0; +} + +#designer-body .label-other-controls { + padding-left: 5px; + font-size: 13px; +} + +#designer-body .pmdesigner-formgrid-tableContainer { + overflow: auto; + width: 100%; + height: 97%; + border: 1px solid #C0C0C0; +} + +#otherControlsList-firstItem .pmui-listitem-text, #otherControlsList-secondItem .pmui-listitem-text { + /*display: none;*/ +} + +#idOtherControlsList .pmui-listitem-text { + margin-left: 20px; + position: absolute; + left: 50px; + top: 10px; +} + +#designer-body .formGrid-freeCell { + width: 98%; + height: 36px; + border: 3px dotted #888888; + background: #c0c0c0; +} + +.pmui-propertiestable { + background: white; + padding: 0 2px 0 2px; +} + +.pmui-field.formview-view .pmui-textcontrol, +.pmui-field.formview-view .pmui-dropdownlistcontrol, +.pmui-field.formview-view .pmui-textareacontrol, +.pmui-field.formview-view .pmui-passwordcontrol, +.pmui-field.formview-view .pmui-uploadcontrol, +.pmui-field.formview-view .pmui-datetimecontrol { + border: 1px solid white; + background: #ECECEC; + font-style: italic; +} + +.pmui-field.formview-disabled .pmui-textcontrol, +.pmui-field.formview-disabled .pmui-dropdownlistcontrol, +.pmui-field.formview-disabled .pmui-textareacontrol, +.pmui-field.formview-disabled .pmui-passwordcontrol, +.pmui-field.formview-disabled .pmui-uploadcontrol, +.pmui-field.formview-disabled .pmui-datetimecontrol { + color: #757575; + background: #ECECEC; +} + +#designer-body .pmui-accordion-panel-container #first-item .pmui-accordion-item-body { + height: 200px; +} + +#third-item .pmui-accordion-item-body { + height: 850px; +} + +.pmTextContainer1 { + width: 60px; + display: inline-block; + font-size: 12px; + margin: 1px; + color: #ee710f; +} + +.pmTextContainer1 span, .pmNameContent { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; +} + +.pmTextContainer2 { + width: auto; + display: inline-block; + font-size: 12px; + color: #21366d; +} + +.pmNameContent { + width: 130px; +} + +.pmdesigner-formgrid-bodycell .pmui-pmsub-titlefield h5 { + background-color: #9FA1AA; + color: white; + margin: 0.5em 0 0.5em 0; + padding: 8px; +} + +.pmdesigner-formgrid-bodycell.pmdesigner-active .pmui-pmsub-titlefield h5 { + background: none; +} + +.pmdesigner-formgrid-bodycell .pmui-pmtitlefield h4 { + background-color: #383D41; + color: white; + font-size: 18px; + padding: 10px; + margin: 0.5em 0 0.5em 0; +} + +.pmdesigner-formgrid-bodycell.pmdesigner-active .pmui-pmtitlefield h4 { + background: none; +} + +.pmdesigner-itemcontrol-x { + margin-left: 5px; + vertical-align: super; + cursor: pointer; + color: #e7e7e7; +} + +.pmdesigner-itemcontrol-x:hover { + color: #8b8888; +} + +.pmdesigner-itemcontrol-itemselected, +.pmdesigner-itemcontrol-optselected, +.pmdesigner-itemcontrol-bracketsselected { + position: relative; + display: inline-block; +} + +.pmdesigner-itemcontrol-itemselected > a { + background: #f5f2f2; + padding: 5px; + margin: 1px; +} + +.pmdesigner-itemcontrol-itemselected > a:hover { + background: #e7e7e7; +} + +.pmdesigner-itemcontrol-bracketsselected > a { + color: red; + padding: 1px; + background: #f5f2f2; +} + +.pmdesigner-itemcontrol-optselected > a { + color: blue; + padding: 1px; + background: #f5f2f2; +} + +/* areacontrol*/ +.pmdesigner-areacontrol { + background: white; + height: auto; +} + +.pmdesigner-suggestcontrol { + height: 20%; + padding: 5px; +} + +.pmdesigner-suggestcontrol input { + height: 20px; + width: 90%; +} + +.pmdesigner-suggestfields { + position: absolute; + width: 52%; + z-index: 5; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); + -webkit-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); +} + +.pmdesigner-suggestfields ul { + list-style-type: none; + padding: 0; + margin: 0; +} + +.pmdesigner-suggestfields a { + display: block; + background: #DFDFDF; + color: #2d3e50; + text-decoration: none; + padding: 0.4em 0.6em; +} + +.pmdesigner-suggestfields li { + left: 0px; + top: 0px; + width: auto; + height: auto; + position: relative; + z-index: auto; +} + +.pmdesigner-suggestfields a:hover { + background: #838486; + color: white; + cursor: pointer; +} + +.pmdesigner-areacontrol-operations { + height: 10%; +} + +.pmdesigner-areacontrol-operationsitem { + background: #c4c9ca; + height: 12px; + padding: 3px 9px; + margin: 0 2px; + text-align: center; + cursor: pointer; + border-radius: 3px; + opacity: 0.5; +} + +.pmdesigner-areacontrol-operationsitem:hover { + opacity: 1; +} + +.pmdesigner-areacontrol-areaformula { + height: auto; + margin: 2px; + background: #f5f2f2; + padding: 10px 2px; +} + +.GridFieldItem .pmui-field-label { + background: #888888; + color: white; + font-size: 12px; + padding: 2px; + display: inline-block; + margin: initial; +} + +.GridFieldItem .pmui-field-control { + padding: 3%; +} + +.GridFieldItem { + padding: initial; +} + +.gridfielditem-header { + border-bottom: 1px solid #c0c0c0; +} + +.GridFieldItem-textarea .pmui-textareacontrol { + resize: vertical; +} + +.GridFieldItem-configFieldIcon { + background: url("../img/config.png") no-repeat white; + display: inline-block; + width: 20%; + background-size: contain; + vertical-align: top; + height: 20px; +} + +.GridFieldItem-suggest .icon-field { + background: url("../img/suggest.png") no-repeat; + display: inline-block; + padding: 0.7em; + background-size: contain; + vertical-align: top; + float: right; +} + +.GridFieldItem-datetime .icon-field { + background: url("../img/datetime.png") no-repeat; + display: inline-block; + padding: 0.7em; + background-size: contain; + vertical-align: top; + float: right; +} + +.pmui-gridfield .gridfieldcell-bodycell { + vertical-align: top; + float: left; + background: white; + border-left: 1px solid #c0c0c0; +} + +.pmui-gridfield .GridField-list { + padding: 1px; + margin: 0px; + background: #c0c0c0; +} + +/*GridField-black-cell-contain +GridField-black-cell-icon +GridField-black-cell-message +*/ +.gridfieldcell-bodycell .GridField-black-cell-icon { + background: url(../img/addControl.png) no-repeat; + width: 100%; + height: 50%; + margin-left: 20%; + display: block; + background-size: contain; +} + +.gridfieldcell-bodycell .GridField-black-cell-contain { + text-align: center; + text-align: center; + color: black; + font-size: 14px; +} + +/*.pmui-gridfield { + box-sizing : border-box; + border : 2px solid #c0c0c0; + padding : 5px 5px 5px 8px; +}*/ +.GridFieldItem.GridFieldItem-text .GridFieldItem-iconControl { + background: url(../img/inputext.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-textarea .GridFieldItem-iconControl { + background: url(../img/textarea.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-dropdown .GridFieldItem-iconControl { + background: url(../img/select.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-checkbox .GridFieldItem-iconControl { + background: url(../img/checkbox.png) no-repeat; + background-size: cover; + width: 47%; + height: 14px; + /* padding: 25px 75px 1px 1px; */ + margin: 3% 0 0 25%; +} + +.GridFieldItem.GridFieldItem-radio .GridFieldItem-iconControl { + background: url(../img/radio.png) no-repeat; + background-size: cover; + width: 47%; + height: 14px; + /* padding: 25px 75px 1px 1px; */ + margin: 3% 0 0 25%; +} + +.GridFieldItem.GridFieldItem-suggest .GridFieldItem-iconControl { + background: url(../img/inputext.png) no-repeat; + width: 80%; + height: 1.7em; + background-size: contain; + margin: 2% 1% 1% 11%; +} + +.GridField-listContainer { + overflow: auto; + height: inherit; + padding-left: 9px; +} + +.pmimagefield-imageContainer { + background: url(../img/image.png) no-repeat center #e7e7e7; + padding: 15px; + background-size: contain; + opacity: 0.5; +} + +.pmimagefield-commentContainer { + font-size: 12px; + font-style: italic; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-link { + background: url("../img/link_web.png") no-repeat center; + background-size: contain; + height: 30px; + width: 100%; + display: block; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-linkContainer { + text-align: center; + background-color: #F5F5F5; + border: 1px solid #DFDDDD; + height: 30px; + width: 100%; +} + +.pmui-pmlinkfield .PMLinkField-linkContainer { + padding-top: 8px; +} + +.pmui-pmlinkfield .PMLinkField-linkContainer .PMLinkField-link { + text-decoration: underline; + color: #53539e; + font-style: italic; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-linkContainer { + padding-top: initial; +} + +.pmui-pm-textlabelfield .pmui-textlabel-field { + margin-left: 10px; +} + +.pmui-pmformfield .pmFormField-formContainer { + text-align: center; + background-color: #F5F5F5; + border: 1px solid #DFDDDD; + height: 30px; + width: 100%; + padding-bottom: 2px; + padding-top: 2px; +} + +.pmui-pmformfield .pmFormField-formIcon { + background: url("../img/subform.png") no-repeat; + width: 28px; + height: 28px; + display: inline-block; + background-size: contain; +} + +.pmui-pmformfield .pmui-field-label { + background: #d3d0d0; + color: white; +} + +.pmui-pmformfield .pmFormField-editIcon { + background: url("../img/edit.png") no-repeat; + width: 18px; + height: 18px; + display: inline-block; + background-size: contain; + float: right; +} + +@font-face { + font-family: "SourceSansPro"; + src: url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot'); + src: url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf') format('truetype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot') format('embedded-opentype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff') format('woff'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg') format('svg'); +} +@font-face { + font-family: "SourceSansProBold"; + src: url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot'); + src: url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf') format('truetype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot') format('embedded-opentype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff') format('woff'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg') format('svg'); +} +body { + font-family: 'SourceSansProRegular', Arial, Tahoma, Verdana; + background: #fff; + margin: 0; + padding: 0; +} +.fd-list { + /*list-style: none;*/ + border-color: #bbb; + border-style: solid; + border-width: 0 0 1px 0; + background: #f8f8f8; + font-size:11px; + padding: 0.3em; + cursor: pointer; +} +.fd-list:nth-child(odd) { + background: #eaebed; +} +.fd-list:hover { + background: #e0e0e0; +} +.fd-list-responsive { + position: relative; + font-size: 11px; + width: 54px; + height: 54px; + float: left; + text-align: center; + background: white; + margin: 4px; + padding: 2px; + border: 1px solid darkgray; +} +.fd-button-panel{ + text-align: right; + border-top: 1px solid #e5e5e5; + position: absolute; + right: 0; + bottom: 0; + left: 0; + padding: 10px; +} +.fd-button { + font-family: "SourceSansPro", Arial, Tahoma, Verdana; + font-size: 14px; + display: inline-block; + text-decoration: none; + background-color: #1e91d1; + text-align: center; + transition: all .5s; + box-sizing: border-box; + border-radius: 2px; + margin: 0px 0px 0px 10px; + padding: 7px 20px; +} +.fd-button:hover { + opacity: 1; + opacity: 0.8; +} +.fd-button-success { + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; +} +.fd-button-link { + color: #383838; + text-decoration: underline; + background: none; + padding: initial; +} +.fd-button-create { + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; + background: #1fbc99 url(../img/ico_mor2.png) no-repeat 5px center; +} +.fd-button-yes{ + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; +} +.fd-button-no{ + color: #fff !important; + background-color: #e4655f; + border: 1px solid #e14333; + font-size: 16px; +} +.fd-table tr:nth-child(odd) { + background-color: #E5E5E5; +} +.fd-table tr:nth-child(even) { + background-color: #F2F2F2; +} +.fd-tbody { + font-size: 11px; +} +.fd-table-th { + background: #3397e1; + color : white; + font-size: 11px; + padding: 6px 15px; + font-weight: inherit; +} +.fd-table-td { + padding: 2px; + border-bottom: 1px solid #D6D6D6; +} +.fd-table-td-error { + border: 1px solid red; +} +.fd-gridForm-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + height: 40px; + width: 100%; + margin-top:6px; +} +.fd-gridForm-grid { + list-style-type: none; + border:1px solid #C0C0C0; + height:84px; + overflow: hidden; + margin:20px 6px 6px 6px; + padding:6px; + white-space:nowrap; + /*overflow-x: scroll; + width: 600px;*/ +} +.fd-gridForm-grid > * { + padding: 1px 1px 1px 1px; + display: inline-block; + width: 130px; + text-align: left; + overflow: hidden; + vertical-align: top; + border:1px solid #C0C0C0; + margin-right:1px; + margin-top:20px; +} +.fd-gridForm-grid-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + height: 59px; + margin-top: 20px; +} +.grid-item-field{ + margin:20px 6px 6px 6px; + padding:4px; + position:relative; + border:1px solid white; + height: 30px; +} +.fd-gridForm-field-label{ + position: absolute; + top: 20px; + width: 60px; + overflow: hidden; +} +.fd-gridForm-grid-contentRequired { + position: absolute; + top: 20px; + left: 65px; + color:red; + display:none; +} +.fd-gridForm-grid-text { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-textarea { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-dropdown { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-checkbox { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-checkgroup { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-radio { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-datetime { + height: 17px; + border: 1px solid #c0c0c0; + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-suggest { + height: 17px; + border: 1px solid #c0c0c0; + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-suggest-placeholder{ + color: gray; +} +.fd-gridForm-grid-hidden { + height: 17px; + border: 1px dashed #c0c0c0; + position: absolute; + left: 1px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-title { + padding: 4px; + font-family: "Montserrat",sans-serif; + font-size: 20px; + border-radius: 3px; + background: white; + color: #555151; + position: absolute; + left: 1px; + right: 1px; + overflow: hidden; +} +.fd-gridForm-grid-subtitle { + padding: 3px; + font-family: "Montserrat",sans-serif; + font-size: 15px; + border-radius: 3px; + background: white; + color: #555151; + position: absolute; + left: 1px; + right: 1px; + overflow: hidden; +} +.fd-gridForm-grid-annotation { + position: absolute; + left: 1px; + right: 1px; + top:18px; + overflow: hidden; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-link { + position: absolute; + left: 70px; + right: 1px; + top:18px; + overflow: hidden; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-image { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-file { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; + overflow: hidden; +} +.fd-gridForm-grid-submit { + position: absolute; + left: 1px; + right: 1px; + top: 18px; + overflow: hidden; +} +.fd-gridForm-grid-button { + position: absolute; + left: 1px; + right: 1px; + top: 18px; + overflow: hidden; +} +.fd-gridForm-grid-panel{ + border: 1px solid #DADADA; + background-color: #F6F5F3; + font-weight: bold; + position: absolute; + left: 1px; + right: 1px; + top: 1px; + overflow: hidden; + height: 34px; +} +.fd-gridForm-grid-msgpanel{ + border: 1px solid #DADADA; + background-color: #F6F5F3; + font-weight: bold; + position: absolute; + left: 1px; + right: 1px; + top: 1px; + overflow: hidden; + height: 34px; + color: red; +} +.fd-gridForm-grid-geomap { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-qrcode { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-signature { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-imagem { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-audiom { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-videom { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-griditem-gridtitle{ + position:absolute; + border:none; + margin:0px; + font-weight:bold; + left:6px; + width:auto; +} +.fd-gridForm-grid-griditem-gridplaceholder{ + position:absolute; + border:none; + margin:25px 0px 0px 0px; + color:gray; + left:6px; + width:auto; +} +.fd-gridForm-grid-griditem-columnRequired { + color: red; + display: none; +} +.fd-gridForm-grid-text-column { + box-sizing: border-box; + width: 100%; +} +.fd-gridForm-grid-textarea-column { + box-sizing: border-box; + width: 100%; + resize: vertical; +} +.fd-gridForm-grid-dropdown-column { + box-sizing: border-box; + width: 100%; +} +.fd-gridForm-grid-link-column { + margin-bottom: 2px; + color: blue; + text-decoration: underline; +} +.fd-designer-button{ + display:inline-block; + border-left:1px solid #70b5ec; + padding: 5px 6px; + cursor:pointer; + width:24px; + height:24px; +} +.fd-designer-button:hover{ + background: #2481c5; + color: #fff; +} +.fd-drag-drop{ + vertical-align:top; + cursor: move; +} +.fd-drag-drop-placeholder{ + background: rgba(128, 128, 128, 0.3); + border: 2px dashed #888; + height: 31px; +} +.fd-tooltip-date-format>div{ + overflow-x: hidden; + overflow-y: scroll; + height: 400px; + width: 309px; +} +.fd-tooltip{ + padding:3px; + border-radius: 0px; +} +.fd-message-error{ + color: #fff; + background: #F5736D; + padding: 4px 10px; + display: inline-block; +} + +ul.CodeMirror-hints { + z-index: 10000; +} +.ui-accordion-header { + color:white; + background:#3397e1; + border-top: 1px solid #3397e1; + border-bottom:1px solid #262932; + border-left:1px solid #262932; + border-right:1px solid #262932; + border-radius:initial; + font-size:12px; + text-align:center; +} +.ui-accordion-header.ui-state-active { + background: white; + color:#3397e1; +} +.ui-layout-pane-north{ + border:1px solid #2979b8; +} +.ui-layout-pane-center{ + border-top: none; + border-right: none; + border-bottom: none; +} +.ui-layout-toggler-west div { + width: 8px; + height: 35px; +} +.ui-datepicker { + border: 1px solid #DADADA; + background: #fcfdfd; + color: #222222; +} +.ui-datepicker-header { + border: 1px solid #fcfdfd; + background: white; + color: black; + font-weight: bold; +} +.ui-datepicker .ui-state-default:not(.ui-state-active):not(.ui-state-highlight) { + border: 1px solid #DADADA; + background: #fcfdfd; + font-weight: bold; + color: #2e6e9e; +} + +/* -- begin PMPopOver -- */ + +.mafe-popover { + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + padding: 1px; + background-color: #fff; + background-clip: padding-box; + border: 1px solid rgba(0,0,0,.2); + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2); + box-shadow: 0 5px 10px rgba(0,0,0,.2); + white-space: normal; + text-align: center; + max-width: 300px; + opacity: 0; + -webkit-transition: opacity .15s linear; + transition: opacity .15s linear; +} + +.mafe-popover.in { + opacity: 1; +} + +.mafe-popover-content { + padding: 9px 14px; +} + +.mafe-popover>.arrow, .mafe-popover>.arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} + +.mafe-popover>.arrow:after { + border-width: 10px; + content: ""; +} + +.mafe-popover.right>.arrow:after { + content: " "; + left: 1px; + bottom: -10px; + border-left-width: 0; + border-right-color: #fff; +} + +.mafe-popover.left>.arrow:after { + content: " "; + right: 1px; + bottom: -10px; + border-right-width: 0; + border-left-color: #fff; +} + +.mafe-popover.top>.arrow:after { + content: " "; + bottom: 1px; + right: -10px; + border-bottom-width: 0; + border-top-color: #fff; +} + +.mafe-popover.bottom>.arrow:after { + content: " "; + top: 1px; + right: -10px; + border-top-width: 0; + border-bottom-color: #fff; +} + +.mafe-popover>.arrow { + border-width: 11px; +} + +.mafe-popover.right>.arrow { + top: 50%; + left: -11px; + margin-top: -11px; + border-left-width: 0; + border-right-color: rgba(0,0,0,.25); +} + +.mafe-popover.left>.arrow { + top: 50%; + right: -11px; + margin-top: -11px; + border-right-width: 0; + border-left-color: rgba(0,0,0,.25); +} + +.mafe-popover.top>.arrow { + right: 50%; + bottom: -11px; + margin-right: -11px; + border-bottom-width: 0; + border-top-color: rgba(0,0,0,.25); +} + +.mafe-popover.bottom>.arrow { + right: 50%; + top: -11px; + margin-right: -11px; + border-top-width: 0; + border-bottom-color: rgba(0,0,0,.25); +} + +.mafe-popover :before, .mafe-popover :after { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +/* -- end PMPopOver -- */ + +.mafe-deprecated-control { + line-height: 1; + position: absolute; + top: 0; + right: 0; +} + +.mafe-deprecated-control::before { + font-family: FontAwesome; + content: "\f12a"; + color: white; + font-size: 10px; + width: 1.2em; + cursor: pointer; + height: 1.2em; + background: red; + display: inline-block; + text-align: center; + line-height: 1.2em; + border-radius: 100%; +} + +.mafe-popover.deprecated { + font-size: 11px; +} + +.mafe-deprecated-title { + font-size: 12px; + color: #B65858; + backgroud: none; + text-align: center; + font-weight: bold; +} + +.deprecated-ok-btn { + display: inline-block; + margin-bottom: 0; + font-weight: 400; + text-align: center; + vertical-align: middle; + cursor: pointer; + background-image: none; + border: 1px solid transparent; + white-space: nowrap; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + color: #fff; + background-color: #5cb85c; + border-color: #4cae4c; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} + +.grid-item-field .mafe-deprecated-control { + left: 0; + width: 1.2em; + display: inline-block; +} + +.mafe-alert { + font-size: 12px; + text-align: left; + font-weight: normal; + padding: 15px 30px 15px 15px; + border: 1px solid #ebccd1; + color: #a94442; + background-color: #f2dede; + border-radius: 4px; +} + +.mafe-alert .button-close { + background: none; + border: none; + color: inherit; + position: relative; + right: -22px; + float: right; + outline: none; + cursor: pointer; +} + +.pm-mafe-grid-item .mafe-deprecated-control { + float: left; + position: relative; +} + +.datetime-gadget-class { + position: absolute; +} + diff --git a/workflow/public_html/lib/fonts/Chivo/Chivo-Black.ttf b/workflow/public_html/lib/fonts/Chivo/Chivo-Black.ttf new file mode 100644 index 000000000..307da3031 Binary files /dev/null and b/workflow/public_html/lib/fonts/Chivo/Chivo-Black.ttf differ diff --git a/workflow/public_html/lib/fonts/Chivo/Chivo-BlackItalic.ttf b/workflow/public_html/lib/fonts/Chivo/Chivo-BlackItalic.ttf new file mode 100644 index 000000000..382f50975 Binary files /dev/null and b/workflow/public_html/lib/fonts/Chivo/Chivo-BlackItalic.ttf differ diff --git a/workflow/public_html/lib/fonts/Chivo/Chivo-Italic.ttf b/workflow/public_html/lib/fonts/Chivo/Chivo-Italic.ttf new file mode 100644 index 000000000..f86d6e0a7 Binary files /dev/null and b/workflow/public_html/lib/fonts/Chivo/Chivo-Italic.ttf differ diff --git a/workflow/public_html/lib/fonts/Chivo/Chivo-Regular.ttf b/workflow/public_html/lib/fonts/Chivo/Chivo-Regular.ttf new file mode 100644 index 000000000..30f8143c8 Binary files /dev/null and b/workflow/public_html/lib/fonts/Chivo/Chivo-Regular.ttf differ diff --git a/workflow/public_html/lib/fonts/Chivo/OFL.txt b/workflow/public_html/lib/fonts/Chivo/OFL.txt new file mode 100644 index 000000000..ac2d55525 --- /dev/null +++ b/workflow/public_html/lib/fonts/Chivo/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2010, Omnibus-Type (www.omnibus-type.com|omnibus.type@gmail.com), +Copyright (c) 2010, Igino Marini. (www.ikern.com|mail@iginomarini.com), +with Reserved Font Name Chivo. +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/workflow/public_html/lib/fonts/Montserrat/Montserrat-Bold.ttf b/workflow/public_html/lib/fonts/Montserrat/Montserrat-Bold.ttf new file mode 100644 index 000000000..ae33a4538 Binary files /dev/null and b/workflow/public_html/lib/fonts/Montserrat/Montserrat-Bold.ttf differ diff --git a/workflow/public_html/lib/fonts/Montserrat/Montserrat-Regular.ttf b/workflow/public_html/lib/fonts/Montserrat/Montserrat-Regular.ttf new file mode 100644 index 000000000..5b4b5afe6 Binary files /dev/null and b/workflow/public_html/lib/fonts/Montserrat/Montserrat-Regular.ttf differ diff --git a/workflow/public_html/lib/fonts/Montserrat/OFL.txt b/workflow/public_html/lib/fonts/Montserrat/OFL.txt new file mode 100644 index 000000000..3968b2265 --- /dev/null +++ b/workflow/public_html/lib/fonts/Montserrat/OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2011-2012, Julieta Ulanovsky (julieta.ulanovsky@gmail.com), with Reserved Font Names 'Montserrat' +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot new file mode 100644 index 000000000..0ed0cd462 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot differ diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg new file mode 100644 index 000000000..7cd4bef46 --- /dev/null +++ b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg @@ -0,0 +1,173 @@ + + + + +This is a custom SVG webfont generated by Font Squirrel. +Copyright : 2010 2012 Adobe Systems Incorporated All Rights Reserved +Designer : Paul D Hunt +Foundry : Adobe Systems Incorporated +Foundry URL : httpwwwadobecomtype + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf new file mode 100644 index 000000000..07cea1717 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf differ diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff new file mode 100644 index 000000000..d2bd820d0 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff differ diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot new file mode 100644 index 000000000..5733b8e13 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot differ diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg new file mode 100644 index 000000000..9dc3296c1 --- /dev/null +++ b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg @@ -0,0 +1,173 @@ + + + + +This is a custom SVG webfont generated by Font Squirrel. +Copyright : 2010 2012 Adobe Systems Incorporated All Rights Reserved +Designer : Paul D Hunt +Foundry : Adobe Systems Incorporated +Foundry URL : httpwwwadobecomtype + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf new file mode 100644 index 000000000..2fcb0e683 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf differ diff --git a/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff new file mode 100644 index 000000000..41b74b460 Binary files /dev/null and b/workflow/public_html/lib/fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff differ diff --git a/workflow/public_html/lib/img/15px-Edit.png b/workflow/public_html/lib/img/15px-Edit.png new file mode 100644 index 000000000..4eb28e558 Binary files /dev/null and b/workflow/public_html/lib/img/15px-Edit.png differ diff --git a/workflow/public_html/lib/img/PM.png b/workflow/public_html/lib/img/PM.png new file mode 100644 index 000000000..02761f090 Binary files /dev/null and b/workflow/public_html/lib/img/PM.png differ diff --git a/workflow/public_html/lib/img/TalendOpenStudio.gif b/workflow/public_html/lib/img/TalendOpenStudio.gif new file mode 100644 index 000000000..de83636bf Binary files /dev/null and b/workflow/public_html/lib/img/TalendOpenStudio.gif differ diff --git a/workflow/public_html/lib/img/_bg-blue.gif b/workflow/public_html/lib/img/_bg-blue.gif new file mode 100644 index 000000000..f06db4d7b Binary files /dev/null and b/workflow/public_html/lib/img/_bg-blue.gif differ diff --git a/workflow/public_html/lib/img/_editcopy.png b/workflow/public_html/lib/img/_editcopy.png new file mode 100644 index 000000000..b7c938a99 Binary files /dev/null and b/workflow/public_html/lib/img/_editcopy.png differ diff --git a/workflow/public_html/lib/img/activate.png b/workflow/public_html/lib/img/activate.png new file mode 100644 index 000000000..1be605c56 Binary files /dev/null and b/workflow/public_html/lib/img/activate.png differ diff --git a/workflow/public_html/lib/img/add.png b/workflow/public_html/lib/img/add.png new file mode 100644 index 000000000..bd17836ce Binary files /dev/null and b/workflow/public_html/lib/img/add.png differ diff --git a/workflow/public_html/lib/img/addtext.png b/workflow/public_html/lib/img/addtext.png new file mode 100644 index 000000000..b97dcfa52 Binary files /dev/null and b/workflow/public_html/lib/img/addtext.png differ diff --git a/workflow/public_html/lib/img/alfrescoIcon.png b/workflow/public_html/lib/img/alfrescoIcon.png new file mode 100644 index 000000000..a65ce4667 Binary files /dev/null and b/workflow/public_html/lib/img/alfrescoIcon.png differ diff --git a/workflow/public_html/lib/img/ar_01.gif b/workflow/public_html/lib/img/ar_01.gif new file mode 100644 index 000000000..427b9dda2 Binary files /dev/null and b/workflow/public_html/lib/img/ar_01.gif differ diff --git a/workflow/public_html/lib/img/ar_dwn.png b/workflow/public_html/lib/img/ar_dwn.png new file mode 100644 index 000000000..9d23088f9 Binary files /dev/null and b/workflow/public_html/lib/img/ar_dwn.png differ diff --git a/workflow/public_html/lib/img/arrow-down.png b/workflow/public_html/lib/img/arrow-down.png new file mode 100644 index 000000000..58bea5165 Binary files /dev/null and b/workflow/public_html/lib/img/arrow-down.png differ diff --git a/workflow/public_html/lib/img/arrow-grid.png b/workflow/public_html/lib/img/arrow-grid.png new file mode 100644 index 000000000..5f156d28d Binary files /dev/null and b/workflow/public_html/lib/img/arrow-grid.png differ diff --git a/workflow/public_html/lib/img/arrow-up.png b/workflow/public_html/lib/img/arrow-up.png new file mode 100644 index 000000000..ef6a98d9b Binary files /dev/null and b/workflow/public_html/lib/img/arrow-up.png differ diff --git a/workflow/public_html/lib/img/bg_dd.png b/workflow/public_html/lib/img/bg_dd.png new file mode 100644 index 000000000..aa8006075 Binary files /dev/null and b/workflow/public_html/lib/img/bg_dd.png differ diff --git a/workflow/public_html/lib/img/bg_designer.gif b/workflow/public_html/lib/img/bg_designer.gif new file mode 100644 index 000000000..c23c986f4 Binary files /dev/null and b/workflow/public_html/lib/img/bg_designer.gif differ diff --git a/workflow/public_html/lib/img/bpmnProcessmaker.gif b/workflow/public_html/lib/img/bpmnProcessmaker.gif new file mode 100644 index 000000000..406b654d5 Binary files /dev/null and b/workflow/public_html/lib/img/bpmnProcessmaker.gif differ diff --git a/workflow/public_html/lib/img/bpmn_sprite_with_zoom.png b/workflow/public_html/lib/img/bpmn_sprite_with_zoom.png new file mode 100644 index 000000000..3a3617c3d Binary files /dev/null and b/workflow/public_html/lib/img/bpmn_sprite_with_zoom.png differ diff --git a/workflow/public_html/lib/img/btn_create.png b/workflow/public_html/lib/img/btn_create.png new file mode 100644 index 000000000..9cc1e7b22 Binary files /dev/null and b/workflow/public_html/lib/img/btn_create.png differ diff --git a/workflow/public_html/lib/img/button.png b/workflow/public_html/lib/img/button.png new file mode 100644 index 000000000..471e96df9 Binary files /dev/null and b/workflow/public_html/lib/img/button.png differ diff --git a/workflow/public_html/lib/img/calendar.png b/workflow/public_html/lib/img/calendar.png new file mode 100644 index 000000000..35f4105f4 Binary files /dev/null and b/workflow/public_html/lib/img/calendar.png differ diff --git a/workflow/public_html/lib/img/caret-down-w.png b/workflow/public_html/lib/img/caret-down-w.png new file mode 100644 index 000000000..67299151a Binary files /dev/null and b/workflow/public_html/lib/img/caret-down-w.png differ diff --git a/workflow/public_html/lib/img/caret-down.png b/workflow/public_html/lib/img/caret-down.png new file mode 100644 index 000000000..32cba195c Binary files /dev/null and b/workflow/public_html/lib/img/caret-down.png differ diff --git a/workflow/public_html/lib/img/casa.png b/workflow/public_html/lib/img/casa.png new file mode 100644 index 000000000..66c26946f Binary files /dev/null and b/workflow/public_html/lib/img/casa.png differ diff --git a/workflow/public_html/lib/img/close-grid.png b/workflow/public_html/lib/img/close-grid.png new file mode 100644 index 000000000..e907aad86 Binary files /dev/null and b/workflow/public_html/lib/img/close-grid.png differ diff --git a/workflow/public_html/lib/img/close.png b/workflow/public_html/lib/img/close.png new file mode 100644 index 000000000..3103f63dd Binary files /dev/null and b/workflow/public_html/lib/img/close.png differ diff --git a/workflow/public_html/lib/img/close_.png b/workflow/public_html/lib/img/close_.png new file mode 100644 index 000000000..3c6d4cea2 Binary files /dev/null and b/workflow/public_html/lib/img/close_.png differ diff --git a/workflow/public_html/lib/img/cmp-icons.png b/workflow/public_html/lib/img/cmp-icons.png new file mode 100644 index 000000000..0f3a8f99a Binary files /dev/null and b/workflow/public_html/lib/img/cmp-icons.png differ diff --git a/workflow/public_html/lib/img/copy_import.png b/workflow/public_html/lib/img/copy_import.png new file mode 100644 index 000000000..88ab55b86 Binary files /dev/null and b/workflow/public_html/lib/img/copy_import.png differ diff --git a/workflow/public_html/lib/img/corona-delete.png b/workflow/public_html/lib/img/corona-delete.png new file mode 100644 index 000000000..1043f08b2 Binary files /dev/null and b/workflow/public_html/lib/img/corona-delete.png differ diff --git a/workflow/public_html/lib/img/corona-end-message.png b/workflow/public_html/lib/img/corona-end-message.png new file mode 100644 index 000000000..3f4047f82 Binary files /dev/null and b/workflow/public_html/lib/img/corona-end-message.png differ diff --git a/workflow/public_html/lib/img/corona-end.png b/workflow/public_html/lib/img/corona-end.png new file mode 100644 index 000000000..dfc912447 Binary files /dev/null and b/workflow/public_html/lib/img/corona-end.png differ diff --git a/workflow/public_html/lib/img/corona-flow.png b/workflow/public_html/lib/img/corona-flow.png new file mode 100644 index 000000000..d2196458e Binary files /dev/null and b/workflow/public_html/lib/img/corona-flow.png differ diff --git a/workflow/public_html/lib/img/corona-gateway-exclusive.png b/workflow/public_html/lib/img/corona-gateway-exclusive.png new file mode 100644 index 000000000..451c2a744 Binary files /dev/null and b/workflow/public_html/lib/img/corona-gateway-exclusive.png differ diff --git a/workflow/public_html/lib/img/corona-gateway-inclusive.png b/workflow/public_html/lib/img/corona-gateway-inclusive.png new file mode 100644 index 000000000..f7783b65a Binary files /dev/null and b/workflow/public_html/lib/img/corona-gateway-inclusive.png differ diff --git a/workflow/public_html/lib/img/corona-gateway-parallel.png b/workflow/public_html/lib/img/corona-gateway-parallel.png new file mode 100644 index 000000000..cdca84e65 Binary files /dev/null and b/workflow/public_html/lib/img/corona-gateway-parallel.png differ diff --git a/workflow/public_html/lib/img/corona-intermediate-receive-message.png b/workflow/public_html/lib/img/corona-intermediate-receive-message.png new file mode 100644 index 000000000..4b7116fd8 Binary files /dev/null and b/workflow/public_html/lib/img/corona-intermediate-receive-message.png differ diff --git a/workflow/public_html/lib/img/corona-intermediate-send-message.png b/workflow/public_html/lib/img/corona-intermediate-send-message.png new file mode 100644 index 000000000..e778057fe Binary files /dev/null and b/workflow/public_html/lib/img/corona-intermediate-send-message.png differ diff --git a/workflow/public_html/lib/img/corona-intermediate.png b/workflow/public_html/lib/img/corona-intermediate.png new file mode 100644 index 000000000..e778057fe Binary files /dev/null and b/workflow/public_html/lib/img/corona-intermediate.png differ diff --git a/workflow/public_html/lib/img/corona-lane.png b/workflow/public_html/lib/img/corona-lane.png new file mode 100644 index 000000000..ebaf427c3 Binary files /dev/null and b/workflow/public_html/lib/img/corona-lane.png differ diff --git a/workflow/public_html/lib/img/corona-pool.png b/workflow/public_html/lib/img/corona-pool.png new file mode 100644 index 000000000..74d442245 Binary files /dev/null and b/workflow/public_html/lib/img/corona-pool.png differ diff --git a/workflow/public_html/lib/img/corona-settings.png b/workflow/public_html/lib/img/corona-settings.png new file mode 100644 index 000000000..fa95bf446 Binary files /dev/null and b/workflow/public_html/lib/img/corona-settings.png differ diff --git a/workflow/public_html/lib/img/corona-start-message.png b/workflow/public_html/lib/img/corona-start-message.png new file mode 100644 index 000000000..28c5f0e72 Binary files /dev/null and b/workflow/public_html/lib/img/corona-start-message.png differ diff --git a/workflow/public_html/lib/img/corona-start.png b/workflow/public_html/lib/img/corona-start.png new file mode 100644 index 000000000..6c51e99cb Binary files /dev/null and b/workflow/public_html/lib/img/corona-start.png differ diff --git a/workflow/public_html/lib/img/corona-task.png b/workflow/public_html/lib/img/corona-task.png new file mode 100644 index 000000000..4dac2ae2f Binary files /dev/null and b/workflow/public_html/lib/img/corona-task.png differ diff --git a/workflow/public_html/lib/img/corona-textfield-rename.png b/workflow/public_html/lib/img/corona-textfield-rename.png new file mode 100644 index 000000000..1b599bf3a Binary files /dev/null and b/workflow/public_html/lib/img/corona-textfield-rename.png differ diff --git a/workflow/public_html/lib/img/deactivate.png b/workflow/public_html/lib/img/deactivate.png new file mode 100644 index 000000000..6b10925b8 Binary files /dev/null and b/workflow/public_html/lib/img/deactivate.png differ diff --git a/workflow/public_html/lib/img/delete.png b/workflow/public_html/lib/img/delete.png new file mode 100644 index 000000000..cd09b8170 Binary files /dev/null and b/workflow/public_html/lib/img/delete.png differ diff --git a/workflow/public_html/lib/img/delete_rules.png b/workflow/public_html/lib/img/delete_rules.png new file mode 100644 index 000000000..1254a6dfb Binary files /dev/null and b/workflow/public_html/lib/img/delete_rules.png differ diff --git a/workflow/public_html/lib/img/dynaforms.gif b/workflow/public_html/lib/img/dynaforms.gif new file mode 100644 index 000000000..4cf878679 Binary files /dev/null and b/workflow/public_html/lib/img/dynaforms.gif differ diff --git a/workflow/public_html/lib/img/edit-table.png b/workflow/public_html/lib/img/edit-table.png new file mode 100644 index 000000000..a41b4b806 Binary files /dev/null and b/workflow/public_html/lib/img/edit-table.png differ diff --git a/workflow/public_html/lib/img/edit.gif b/workflow/public_html/lib/img/edit.gif new file mode 100644 index 000000000..8958354d4 Binary files /dev/null and b/workflow/public_html/lib/img/edit.gif differ diff --git a/workflow/public_html/lib/img/elbow-end.gif b/workflow/public_html/lib/img/elbow-end.gif new file mode 100644 index 000000000..406a88dff Binary files /dev/null and b/workflow/public_html/lib/img/elbow-end.gif differ diff --git a/workflow/public_html/lib/img/elbow-line.gif b/workflow/public_html/lib/img/elbow-line.gif new file mode 100644 index 000000000..e25ed03fb Binary files /dev/null and b/workflow/public_html/lib/img/elbow-line.gif differ diff --git a/workflow/public_html/lib/img/elbow-minus-nl.gif b/workflow/public_html/lib/img/elbow-minus-nl.gif new file mode 100644 index 000000000..928779e92 Binary files /dev/null and b/workflow/public_html/lib/img/elbow-minus-nl.gif differ diff --git a/workflow/public_html/lib/img/elbow-minus.gif b/workflow/public_html/lib/img/elbow-minus.gif new file mode 100644 index 000000000..97dcc7110 Binary files /dev/null and b/workflow/public_html/lib/img/elbow-minus.gif differ diff --git a/workflow/public_html/lib/img/elbow-plus-nl.gif b/workflow/public_html/lib/img/elbow-plus-nl.gif new file mode 100644 index 000000000..9f7f69880 Binary files /dev/null and b/workflow/public_html/lib/img/elbow-plus-nl.gif differ diff --git a/workflow/public_html/lib/img/elbow-plus.gif b/workflow/public_html/lib/img/elbow-plus.gif new file mode 100644 index 000000000..698de4793 Binary files /dev/null and b/workflow/public_html/lib/img/elbow-plus.gif differ diff --git a/workflow/public_html/lib/img/elbow.gif b/workflow/public_html/lib/img/elbow.gif new file mode 100644 index 000000000..201c413e3 Binary files /dev/null and b/workflow/public_html/lib/img/elbow.gif differ diff --git a/workflow/public_html/lib/img/email.png b/workflow/public_html/lib/img/email.png new file mode 100644 index 000000000..d73df4334 Binary files /dev/null and b/workflow/public_html/lib/img/email.png differ diff --git a/workflow/public_html/lib/img/engranaje.gif b/workflow/public_html/lib/img/engranaje.gif new file mode 100644 index 000000000..d235cf293 Binary files /dev/null and b/workflow/public_html/lib/img/engranaje.gif differ diff --git a/workflow/public_html/lib/img/events.gif b/workflow/public_html/lib/img/events.gif new file mode 100644 index 000000000..1a0cd8fe9 Binary files /dev/null and b/workflow/public_html/lib/img/events.gif differ diff --git a/workflow/public_html/lib/img/examples/icon-save.png b/workflow/public_html/lib/img/examples/icon-save.png new file mode 100644 index 000000000..81828d865 Binary files /dev/null and b/workflow/public_html/lib/img/examples/icon-save.png differ diff --git a/workflow/public_html/lib/img/facebook-16.png b/workflow/public_html/lib/img/facebook-16.png new file mode 100644 index 000000000..13b6356cb Binary files /dev/null and b/workflow/public_html/lib/img/facebook-16.png differ diff --git a/workflow/public_html/lib/img/fd-annotation.png b/workflow/public_html/lib/img/fd-annotation.png new file mode 100644 index 000000000..46b319190 Binary files /dev/null and b/workflow/public_html/lib/img/fd-annotation.png differ diff --git a/workflow/public_html/lib/img/fd-application-form.png b/workflow/public_html/lib/img/fd-application-form.png new file mode 100644 index 000000000..a1638fe10 Binary files /dev/null and b/workflow/public_html/lib/img/fd-application-form.png differ diff --git a/workflow/public_html/lib/img/fd-arrow-left.png b/workflow/public_html/lib/img/fd-arrow-left.png new file mode 100644 index 000000000..be2ed88d4 Binary files /dev/null and b/workflow/public_html/lib/img/fd-arrow-left.png differ diff --git a/workflow/public_html/lib/img/fd-arrow-right.png b/workflow/public_html/lib/img/fd-arrow-right.png new file mode 100644 index 000000000..973cfcf7e Binary files /dev/null and b/workflow/public_html/lib/img/fd-arrow-right.png differ diff --git a/workflow/public_html/lib/img/fd-audio-card.png b/workflow/public_html/lib/img/fd-audio-card.png new file mode 100644 index 000000000..aaa790700 Binary files /dev/null and b/workflow/public_html/lib/img/fd-audio-card.png differ diff --git a/workflow/public_html/lib/img/fd-audio-mobile.png b/workflow/public_html/lib/img/fd-audio-mobile.png new file mode 100644 index 000000000..9058ca040 Binary files /dev/null and b/workflow/public_html/lib/img/fd-audio-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-button.png b/workflow/public_html/lib/img/fd-button.png new file mode 100644 index 000000000..2ecc1e54a Binary files /dev/null and b/workflow/public_html/lib/img/fd-button.png differ diff --git a/workflow/public_html/lib/img/fd-calendar.png b/workflow/public_html/lib/img/fd-calendar.png new file mode 100644 index 000000000..3ee3c205c Binary files /dev/null and b/workflow/public_html/lib/img/fd-calendar.png differ diff --git a/workflow/public_html/lib/img/fd-checkbox.png b/workflow/public_html/lib/img/fd-checkbox.png new file mode 100644 index 000000000..a02d8832f Binary files /dev/null and b/workflow/public_html/lib/img/fd-checkbox.png differ diff --git a/workflow/public_html/lib/img/fd-checkgroup.png b/workflow/public_html/lib/img/fd-checkgroup.png new file mode 100644 index 000000000..4f191f073 Binary files /dev/null and b/workflow/public_html/lib/img/fd-checkgroup.png differ diff --git a/workflow/public_html/lib/img/fd-clear.png b/workflow/public_html/lib/img/fd-clear.png new file mode 100644 index 000000000..5e8e82280 Binary files /dev/null and b/workflow/public_html/lib/img/fd-clear.png differ diff --git a/workflow/public_html/lib/img/fd-clearw.png b/workflow/public_html/lib/img/fd-clearw.png new file mode 100644 index 000000000..4d2f0e52d Binary files /dev/null and b/workflow/public_html/lib/img/fd-clearw.png differ diff --git a/workflow/public_html/lib/img/fd-close.png b/workflow/public_html/lib/img/fd-close.png new file mode 100644 index 000000000..8ff3f66cf Binary files /dev/null and b/workflow/public_html/lib/img/fd-close.png differ diff --git a/workflow/public_html/lib/img/fd-close_delete.png b/workflow/public_html/lib/img/fd-close_delete.png new file mode 100644 index 000000000..5b39f7c21 Binary files /dev/null and b/workflow/public_html/lib/img/fd-close_delete.png differ diff --git a/workflow/public_html/lib/img/fd-closew.png b/workflow/public_html/lib/img/fd-closew.png new file mode 100644 index 000000000..226f3b52d Binary files /dev/null and b/workflow/public_html/lib/img/fd-closew.png differ diff --git a/workflow/public_html/lib/img/fd-datetime.png b/workflow/public_html/lib/img/fd-datetime.png new file mode 100644 index 000000000..97dafadde Binary files /dev/null and b/workflow/public_html/lib/img/fd-datetime.png differ diff --git a/workflow/public_html/lib/img/fd-desktop.png b/workflow/public_html/lib/img/fd-desktop.png new file mode 100644 index 000000000..2bdf8b5eb Binary files /dev/null and b/workflow/public_html/lib/img/fd-desktop.png differ diff --git a/workflow/public_html/lib/img/fd-desktopw.png b/workflow/public_html/lib/img/fd-desktopw.png new file mode 100644 index 000000000..5b6d4ca1b Binary files /dev/null and b/workflow/public_html/lib/img/fd-desktopw.png differ diff --git a/workflow/public_html/lib/img/fd-document-horizontal-text.png b/workflow/public_html/lib/img/fd-document-horizontal-text.png new file mode 100644 index 000000000..f1a100aa7 Binary files /dev/null and b/workflow/public_html/lib/img/fd-document-horizontal-text.png differ diff --git a/workflow/public_html/lib/img/fd-document-text-image.png b/workflow/public_html/lib/img/fd-document-text-image.png new file mode 100644 index 000000000..56c4f0bfc Binary files /dev/null and b/workflow/public_html/lib/img/fd-document-text-image.png differ diff --git a/workflow/public_html/lib/img/fd-dragdrop.png b/workflow/public_html/lib/img/fd-dragdrop.png new file mode 100644 index 000000000..aa8006075 Binary files /dev/null and b/workflow/public_html/lib/img/fd-dragdrop.png differ diff --git a/workflow/public_html/lib/img/fd-dropdown.png b/workflow/public_html/lib/img/fd-dropdown.png new file mode 100644 index 000000000..241d1e714 Binary files /dev/null and b/workflow/public_html/lib/img/fd-dropdown.png differ diff --git a/workflow/public_html/lib/img/fd-export.png b/workflow/public_html/lib/img/fd-export.png new file mode 100644 index 000000000..78fa97617 Binary files /dev/null and b/workflow/public_html/lib/img/fd-export.png differ diff --git a/workflow/public_html/lib/img/fd-exportw.png b/workflow/public_html/lib/img/fd-exportw.png new file mode 100644 index 000000000..013ad50fe Binary files /dev/null and b/workflow/public_html/lib/img/fd-exportw.png differ diff --git a/workflow/public_html/lib/img/fd-file-upload.png b/workflow/public_html/lib/img/fd-file-upload.png new file mode 100644 index 000000000..db8b3aff5 Binary files /dev/null and b/workflow/public_html/lib/img/fd-file-upload.png differ diff --git a/workflow/public_html/lib/img/fd-file.png b/workflow/public_html/lib/img/fd-file.png new file mode 100644 index 000000000..ad6f4c511 Binary files /dev/null and b/workflow/public_html/lib/img/fd-file.png differ diff --git a/workflow/public_html/lib/img/fd-geomap-mobile.png b/workflow/public_html/lib/img/fd-geomap-mobile.png new file mode 100644 index 000000000..f0cc83e63 Binary files /dev/null and b/workflow/public_html/lib/img/fd-geomap-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-grid.png b/workflow/public_html/lib/img/fd-grid.png new file mode 100644 index 000000000..c461d4c0b Binary files /dev/null and b/workflow/public_html/lib/img/fd-grid.png differ diff --git a/workflow/public_html/lib/img/fd-h1.png b/workflow/public_html/lib/img/fd-h1.png new file mode 100644 index 000000000..96b3e3592 Binary files /dev/null and b/workflow/public_html/lib/img/fd-h1.png differ diff --git a/workflow/public_html/lib/img/fd-h2.png b/workflow/public_html/lib/img/fd-h2.png new file mode 100644 index 000000000..ba5497a09 Binary files /dev/null and b/workflow/public_html/lib/img/fd-h2.png differ diff --git a/workflow/public_html/lib/img/fd-help.png b/workflow/public_html/lib/img/fd-help.png new file mode 100644 index 000000000..5c870176d Binary files /dev/null and b/workflow/public_html/lib/img/fd-help.png differ diff --git a/workflow/public_html/lib/img/fd-hidden.png b/workflow/public_html/lib/img/fd-hidden.png new file mode 100644 index 000000000..12f83b7a2 Binary files /dev/null and b/workflow/public_html/lib/img/fd-hidden.png differ diff --git a/workflow/public_html/lib/img/fd-image-instagram.png b/workflow/public_html/lib/img/fd-image-instagram.png new file mode 100644 index 000000000..e1a8b2ca4 Binary files /dev/null and b/workflow/public_html/lib/img/fd-image-instagram.png differ diff --git a/workflow/public_html/lib/img/fd-image-mobile.png b/workflow/public_html/lib/img/fd-image-mobile.png new file mode 100644 index 000000000..7384e288d Binary files /dev/null and b/workflow/public_html/lib/img/fd-image-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-image.png b/workflow/public_html/lib/img/fd-image.png new file mode 100644 index 000000000..c485c2016 Binary files /dev/null and b/workflow/public_html/lib/img/fd-image.png differ diff --git a/workflow/public_html/lib/img/fd-image2.png b/workflow/public_html/lib/img/fd-image2.png new file mode 100644 index 000000000..b648f7aca Binary files /dev/null and b/workflow/public_html/lib/img/fd-image2.png differ diff --git a/workflow/public_html/lib/img/fd-import.png b/workflow/public_html/lib/img/fd-import.png new file mode 100644 index 000000000..37f55e35f Binary files /dev/null and b/workflow/public_html/lib/img/fd-import.png differ diff --git a/workflow/public_html/lib/img/fd-importw.png b/workflow/public_html/lib/img/fd-importw.png new file mode 100644 index 000000000..7b16ce535 Binary files /dev/null and b/workflow/public_html/lib/img/fd-importw.png differ diff --git a/workflow/public_html/lib/img/fd-label.png b/workflow/public_html/lib/img/fd-label.png new file mode 100644 index 000000000..306e57429 Binary files /dev/null and b/workflow/public_html/lib/img/fd-label.png differ diff --git a/workflow/public_html/lib/img/fd-language.png b/workflow/public_html/lib/img/fd-language.png new file mode 100644 index 000000000..871d53d09 Binary files /dev/null and b/workflow/public_html/lib/img/fd-language.png differ diff --git a/workflow/public_html/lib/img/fd-languagew.png b/workflow/public_html/lib/img/fd-languagew.png new file mode 100644 index 000000000..a854854a3 Binary files /dev/null and b/workflow/public_html/lib/img/fd-languagew.png differ diff --git a/workflow/public_html/lib/img/fd-link.png b/workflow/public_html/lib/img/fd-link.png new file mode 100644 index 000000000..5cdf5a70a Binary files /dev/null and b/workflow/public_html/lib/img/fd-link.png differ diff --git a/workflow/public_html/lib/img/fd-magnifier.png b/workflow/public_html/lib/img/fd-magnifier.png new file mode 100644 index 000000000..31e2cd8f6 Binary files /dev/null and b/workflow/public_html/lib/img/fd-magnifier.png differ diff --git a/workflow/public_html/lib/img/fd-map.png b/workflow/public_html/lib/img/fd-map.png new file mode 100644 index 000000000..f90ef25ec Binary files /dev/null and b/workflow/public_html/lib/img/fd-map.png differ diff --git a/workflow/public_html/lib/img/fd-mobile_phone.png b/workflow/public_html/lib/img/fd-mobile_phone.png new file mode 100644 index 000000000..ba195316a Binary files /dev/null and b/workflow/public_html/lib/img/fd-mobile_phone.png differ diff --git a/workflow/public_html/lib/img/fd-mobile_phonew.png b/workflow/public_html/lib/img/fd-mobile_phonew.png new file mode 100644 index 000000000..08228588f Binary files /dev/null and b/workflow/public_html/lib/img/fd-mobile_phonew.png differ diff --git a/workflow/public_html/lib/img/fd-move.png b/workflow/public_html/lib/img/fd-move.png new file mode 100644 index 000000000..0c4ed0b82 Binary files /dev/null and b/workflow/public_html/lib/img/fd-move.png differ diff --git a/workflow/public_html/lib/img/fd-move2.png b/workflow/public_html/lib/img/fd-move2.png new file mode 100644 index 000000000..eecbc4252 Binary files /dev/null and b/workflow/public_html/lib/img/fd-move2.png differ diff --git a/workflow/public_html/lib/img/fd-panel32.png b/workflow/public_html/lib/img/fd-panel32.png new file mode 100644 index 000000000..d33760970 Binary files /dev/null and b/workflow/public_html/lib/img/fd-panel32.png differ diff --git a/workflow/public_html/lib/img/fd-panel_blank.png b/workflow/public_html/lib/img/fd-panel_blank.png new file mode 100644 index 000000000..7a135f443 Binary files /dev/null and b/workflow/public_html/lib/img/fd-panel_blank.png differ diff --git a/workflow/public_html/lib/img/fd-preview.png b/workflow/public_html/lib/img/fd-preview.png new file mode 100644 index 000000000..4bfcbd593 Binary files /dev/null and b/workflow/public_html/lib/img/fd-preview.png differ diff --git a/workflow/public_html/lib/img/fd-previeww.png b/workflow/public_html/lib/img/fd-previeww.png new file mode 100644 index 000000000..e53fe7f2f Binary files /dev/null and b/workflow/public_html/lib/img/fd-previeww.png differ diff --git a/workflow/public_html/lib/img/fd-qr-code.png b/workflow/public_html/lib/img/fd-qr-code.png new file mode 100644 index 000000000..41a84aa1d Binary files /dev/null and b/workflow/public_html/lib/img/fd-qr-code.png differ diff --git a/workflow/public_html/lib/img/fd-qrcode-mobile.png b/workflow/public_html/lib/img/fd-qrcode-mobile.png new file mode 100644 index 000000000..c33bf3c10 Binary files /dev/null and b/workflow/public_html/lib/img/fd-qrcode-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-radio.png b/workflow/public_html/lib/img/fd-radio.png new file mode 100644 index 000000000..4d79e4606 Binary files /dev/null and b/workflow/public_html/lib/img/fd-radio.png differ diff --git a/workflow/public_html/lib/img/fd-refresh.png b/workflow/public_html/lib/img/fd-refresh.png new file mode 100644 index 000000000..77e12d1c6 Binary files /dev/null and b/workflow/public_html/lib/img/fd-refresh.png differ diff --git a/workflow/public_html/lib/img/fd-remove.png b/workflow/public_html/lib/img/fd-remove.png new file mode 100644 index 000000000..e1b498c14 Binary files /dev/null and b/workflow/public_html/lib/img/fd-remove.png differ diff --git a/workflow/public_html/lib/img/fd-save.png b/workflow/public_html/lib/img/fd-save.png new file mode 100644 index 000000000..d23844f37 Binary files /dev/null and b/workflow/public_html/lib/img/fd-save.png differ diff --git a/workflow/public_html/lib/img/fd-savew.png b/workflow/public_html/lib/img/fd-savew.png new file mode 100644 index 000000000..e73020b7e Binary files /dev/null and b/workflow/public_html/lib/img/fd-savew.png differ diff --git a/workflow/public_html/lib/img/fd-signature-mobile.png b/workflow/public_html/lib/img/fd-signature-mobile.png new file mode 100644 index 000000000..3bf1389bf Binary files /dev/null and b/workflow/public_html/lib/img/fd-signature-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-subform.png b/workflow/public_html/lib/img/fd-subform.png new file mode 100644 index 000000000..3b51be86e Binary files /dev/null and b/workflow/public_html/lib/img/fd-subform.png differ diff --git a/workflow/public_html/lib/img/fd-submit.png b/workflow/public_html/lib/img/fd-submit.png new file mode 100644 index 000000000..b1863d07a Binary files /dev/null and b/workflow/public_html/lib/img/fd-submit.png differ diff --git a/workflow/public_html/lib/img/fd-suggest.png b/workflow/public_html/lib/img/fd-suggest.png new file mode 100644 index 000000000..c80fc8992 Binary files /dev/null and b/workflow/public_html/lib/img/fd-suggest.png differ diff --git a/workflow/public_html/lib/img/fd-table.png b/workflow/public_html/lib/img/fd-table.png new file mode 100644 index 000000000..b0cd69fc5 Binary files /dev/null and b/workflow/public_html/lib/img/fd-table.png differ diff --git a/workflow/public_html/lib/img/fd-tablet.png b/workflow/public_html/lib/img/fd-tablet.png new file mode 100644 index 000000000..1eaa9bc7e Binary files /dev/null and b/workflow/public_html/lib/img/fd-tablet.png differ diff --git a/workflow/public_html/lib/img/fd-tabletw.png b/workflow/public_html/lib/img/fd-tabletw.png new file mode 100644 index 000000000..262325452 Binary files /dev/null and b/workflow/public_html/lib/img/fd-tabletw.png differ diff --git a/workflow/public_html/lib/img/fd-text.png b/workflow/public_html/lib/img/fd-text.png new file mode 100644 index 000000000..bfbc44fc7 Binary files /dev/null and b/workflow/public_html/lib/img/fd-text.png differ diff --git a/workflow/public_html/lib/img/fd-text_heading_1.png b/workflow/public_html/lib/img/fd-text_heading_1.png new file mode 100644 index 000000000..632c113b3 Binary files /dev/null and b/workflow/public_html/lib/img/fd-text_heading_1.png differ diff --git a/workflow/public_html/lib/img/fd-text_heading_2.png b/workflow/public_html/lib/img/fd-text_heading_2.png new file mode 100644 index 000000000..a2ef293ff Binary files /dev/null and b/workflow/public_html/lib/img/fd-text_heading_2.png differ diff --git a/workflow/public_html/lib/img/fd-text_signature.png b/workflow/public_html/lib/img/fd-text_signature.png new file mode 100644 index 000000000..c72fd8088 Binary files /dev/null and b/workflow/public_html/lib/img/fd-text_signature.png differ diff --git a/workflow/public_html/lib/img/fd-textarea.png b/workflow/public_html/lib/img/fd-textarea.png new file mode 100644 index 000000000..57202f302 Binary files /dev/null and b/workflow/public_html/lib/img/fd-textarea.png differ diff --git a/workflow/public_html/lib/img/fd-toggle.png b/workflow/public_html/lib/img/fd-toggle.png new file mode 100644 index 000000000..facf1cd41 Binary files /dev/null and b/workflow/public_html/lib/img/fd-toggle.png differ diff --git a/workflow/public_html/lib/img/fd-ui-button-default.png b/workflow/public_html/lib/img/fd-ui-button-default.png new file mode 100644 index 000000000..c59f595ed Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-button-default.png differ diff --git a/workflow/public_html/lib/img/fd-ui-button.png b/workflow/public_html/lib/img/fd-ui-button.png new file mode 100644 index 000000000..32a4eeb71 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-button.png differ diff --git a/workflow/public_html/lib/img/fd-ui-check-boxes-list.png b/workflow/public_html/lib/img/fd-ui-check-boxes-list.png new file mode 100644 index 000000000..4bf58d1de Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-check-boxes-list.png differ diff --git a/workflow/public_html/lib/img/fd-ui-combo-box.png b/workflow/public_html/lib/img/fd-ui-combo-box.png new file mode 100644 index 000000000..53d306e74 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-combo-box.png differ diff --git a/workflow/public_html/lib/img/fd-ui-label-link.png b/workflow/public_html/lib/img/fd-ui-label-link.png new file mode 100644 index 000000000..98bca0570 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-label-link.png differ diff --git a/workflow/public_html/lib/img/fd-ui-label.png b/workflow/public_html/lib/img/fd-ui-label.png new file mode 100644 index 000000000..2fc5ccc4f Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-label.png differ diff --git a/workflow/public_html/lib/img/fd-ui-labels.png b/workflow/public_html/lib/img/fd-ui-labels.png new file mode 100644 index 000000000..4e40d2436 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-labels.png differ diff --git a/workflow/public_html/lib/img/fd-ui-list-box.png b/workflow/public_html/lib/img/fd-ui-list-box.png new file mode 100644 index 000000000..60a8db537 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-list-box.png differ diff --git a/workflow/public_html/lib/img/fd-ui-radio-buttons-list.png b/workflow/public_html/lib/img/fd-ui-radio-buttons-list.png new file mode 100644 index 000000000..095ba543c Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-radio-buttons-list.png differ diff --git a/workflow/public_html/lib/img/fd-ui-text-area.png b/workflow/public_html/lib/img/fd-ui-text-area.png new file mode 100644 index 000000000..d2ca913d2 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-text-area.png differ diff --git a/workflow/public_html/lib/img/fd-ui-text-field-hidden.png b/workflow/public_html/lib/img/fd-ui-text-field-hidden.png new file mode 100644 index 000000000..dc8b275b6 Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-text-field-hidden.png differ diff --git a/workflow/public_html/lib/img/fd-ui-text-field.png b/workflow/public_html/lib/img/fd-ui-text-field.png new file mode 100644 index 000000000..7fc1c7f7e Binary files /dev/null and b/workflow/public_html/lib/img/fd-ui-text-field.png differ diff --git a/workflow/public_html/lib/img/fd-video-mobile.png b/workflow/public_html/lib/img/fd-video-mobile.png new file mode 100644 index 000000000..0da5939fe Binary files /dev/null and b/workflow/public_html/lib/img/fd-video-mobile.png differ diff --git a/workflow/public_html/lib/img/fd-video.png b/workflow/public_html/lib/img/fd-video.png new file mode 100644 index 000000000..d720c4c2e Binary files /dev/null and b/workflow/public_html/lib/img/fd-video.png differ diff --git a/workflow/public_html/lib/img/folder-open.gif b/workflow/public_html/lib/img/folder-open.gif new file mode 100644 index 000000000..361e1be3e Binary files /dev/null and b/workflow/public_html/lib/img/folder-open.gif differ diff --git a/workflow/public_html/lib/img/folder.gif b/workflow/public_html/lib/img/folder.gif new file mode 100644 index 000000000..b2fd81a12 Binary files /dev/null and b/workflow/public_html/lib/img/folder.gif differ diff --git a/workflow/public_html/lib/img/form.gif b/workflow/public_html/lib/img/form.gif new file mode 100644 index 000000000..3503f66a1 Binary files /dev/null and b/workflow/public_html/lib/img/form.gif differ diff --git a/workflow/public_html/lib/img/form.png b/workflow/public_html/lib/img/form.png new file mode 100644 index 000000000..b2ffdaca9 Binary files /dev/null and b/workflow/public_html/lib/img/form.png differ diff --git a/workflow/public_html/lib/img/gear.png b/workflow/public_html/lib/img/gear.png new file mode 100644 index 000000000..06f18b690 Binary files /dev/null and b/workflow/public_html/lib/img/gear.png differ diff --git a/workflow/public_html/lib/img/grid.jpg b/workflow/public_html/lib/img/grid.jpg new file mode 100644 index 000000000..059006101 Binary files /dev/null and b/workflow/public_html/lib/img/grid.jpg differ diff --git a/workflow/public_html/lib/img/grid_10.png b/workflow/public_html/lib/img/grid_10.png new file mode 100644 index 000000000..3b0d06a88 Binary files /dev/null and b/workflow/public_html/lib/img/grid_10.png differ diff --git a/workflow/public_html/lib/img/grid_20.png b/workflow/public_html/lib/img/grid_20.png new file mode 100644 index 000000000..c8a2b6d87 Binary files /dev/null and b/workflow/public_html/lib/img/grid_20.png differ diff --git a/workflow/public_html/lib/img/grid_30.png b/workflow/public_html/lib/img/grid_30.png new file mode 100644 index 000000000..d4794a01a Binary files /dev/null and b/workflow/public_html/lib/img/grid_30.png differ diff --git a/workflow/public_html/lib/img/help.png b/workflow/public_html/lib/img/help.png new file mode 100644 index 000000000..7515d1ba8 Binary files /dev/null and b/workflow/public_html/lib/img/help.png differ diff --git a/workflow/public_html/lib/img/i_dept_med.png b/workflow/public_html/lib/img/i_dept_med.png new file mode 100644 index 000000000..1c21a9697 Binary files /dev/null and b/workflow/public_html/lib/img/i_dept_med.png differ diff --git a/workflow/public_html/lib/img/i_dept_small.png b/workflow/public_html/lib/img/i_dept_small.png new file mode 100644 index 000000000..7b1edef9f Binary files /dev/null and b/workflow/public_html/lib/img/i_dept_small.png differ diff --git a/workflow/public_html/lib/img/i_group_big.png b/workflow/public_html/lib/img/i_group_big.png new file mode 100644 index 000000000..6d80a6256 Binary files /dev/null and b/workflow/public_html/lib/img/i_group_big.png differ diff --git a/workflow/public_html/lib/img/i_group_med.png b/workflow/public_html/lib/img/i_group_med.png new file mode 100644 index 000000000..1f8bb958b Binary files /dev/null and b/workflow/public_html/lib/img/i_group_med.png differ diff --git a/workflow/public_html/lib/img/i_group_med_white.gif b/workflow/public_html/lib/img/i_group_med_white.gif new file mode 100644 index 000000000..392983134 Binary files /dev/null and b/workflow/public_html/lib/img/i_group_med_white.gif differ diff --git a/workflow/public_html/lib/img/i_group_med_white.png b/workflow/public_html/lib/img/i_group_med_white.png new file mode 100644 index 000000000..23989623b Binary files /dev/null and b/workflow/public_html/lib/img/i_group_med_white.png differ diff --git a/workflow/public_html/lib/img/i_group_small.png b/workflow/public_html/lib/img/i_group_small.png new file mode 100644 index 000000000..48abf3ca4 Binary files /dev/null and b/workflow/public_html/lib/img/i_group_small.png differ diff --git a/workflow/public_html/lib/img/i_us_med.png b/workflow/public_html/lib/img/i_us_med.png new file mode 100644 index 000000000..057ff2f10 Binary files /dev/null and b/workflow/public_html/lib/img/i_us_med.png differ diff --git a/workflow/public_html/lib/img/i_us_small.png b/workflow/public_html/lib/img/i_us_small.png new file mode 100644 index 000000000..186dbecb9 Binary files /dev/null and b/workflow/public_html/lib/img/i_us_small.png differ diff --git a/workflow/public_html/lib/img/i_us_white.png b/workflow/public_html/lib/img/i_us_white.png new file mode 100644 index 000000000..56edac540 Binary files /dev/null and b/workflow/public_html/lib/img/i_us_white.png differ diff --git a/workflow/public_html/lib/img/ico_full_scr.png b/workflow/public_html/lib/img/ico_full_scr.png new file mode 100644 index 000000000..48766e814 Binary files /dev/null and b/workflow/public_html/lib/img/ico_full_scr.png differ diff --git a/workflow/public_html/lib/img/ico_hiden2.png b/workflow/public_html/lib/img/ico_hiden2.png new file mode 100644 index 000000000..095297a19 Binary files /dev/null and b/workflow/public_html/lib/img/ico_hiden2.png differ diff --git a/workflow/public_html/lib/img/ico_hiden3.png b/workflow/public_html/lib/img/ico_hiden3.png new file mode 100644 index 000000000..904df5272 Binary files /dev/null and b/workflow/public_html/lib/img/ico_hiden3.png differ diff --git a/workflow/public_html/lib/img/ico_mor02.png b/workflow/public_html/lib/img/ico_mor02.png new file mode 100644 index 000000000..81828d865 Binary files /dev/null and b/workflow/public_html/lib/img/ico_mor02.png differ diff --git a/workflow/public_html/lib/img/ico_mor2.png b/workflow/public_html/lib/img/ico_mor2.png new file mode 100644 index 000000000..dbb394a07 Binary files /dev/null and b/workflow/public_html/lib/img/ico_mor2.png differ diff --git a/workflow/public_html/lib/img/ico_ok.png b/workflow/public_html/lib/img/ico_ok.png new file mode 100644 index 000000000..149b3a804 Binary files /dev/null and b/workflow/public_html/lib/img/ico_ok.png differ diff --git a/workflow/public_html/lib/img/ico_save.png b/workflow/public_html/lib/img/ico_save.png new file mode 100644 index 000000000..211e18bdc Binary files /dev/null and b/workflow/public_html/lib/img/ico_save.png differ diff --git a/workflow/public_html/lib/img/ico_show2.png b/workflow/public_html/lib/img/ico_show2.png new file mode 100644 index 000000000..0e9b9396a Binary files /dev/null and b/workflow/public_html/lib/img/ico_show2.png differ diff --git a/workflow/public_html/lib/img/ico_show3.png b/workflow/public_html/lib/img/ico_show3.png new file mode 100644 index 000000000..9c76ea58a Binary files /dev/null and b/workflow/public_html/lib/img/ico_show3.png differ diff --git a/workflow/public_html/lib/img/icon_SugarCRM.gif b/workflow/public_html/lib/img/icon_SugarCRM.gif new file mode 100644 index 000000000..deb1a679e Binary files /dev/null and b/workflow/public_html/lib/img/icon_SugarCRM.gif differ diff --git a/workflow/public_html/lib/img/icons/arrow.png b/workflow/public_html/lib/img/icons/arrow.png new file mode 100644 index 000000000..cccce0e75 Binary files /dev/null and b/workflow/public_html/lib/img/icons/arrow.png differ diff --git a/workflow/public_html/lib/img/icons/arrow_expanded.png b/workflow/public_html/lib/img/icons/arrow_expanded.png new file mode 100644 index 000000000..a0fe310ef Binary files /dev/null and b/workflow/public_html/lib/img/icons/arrow_expanded.png differ diff --git a/workflow/public_html/lib/img/icons/cancel.png b/workflow/public_html/lib/img/icons/cancel.png new file mode 100644 index 000000000..33c876b23 Binary files /dev/null and b/workflow/public_html/lib/img/icons/cancel.png differ diff --git a/workflow/public_html/lib/img/icons/elbow-minus.gif b/workflow/public_html/lib/img/icons/elbow-minus.gif new file mode 100644 index 000000000..97dcc7110 Binary files /dev/null and b/workflow/public_html/lib/img/icons/elbow-minus.gif differ diff --git a/workflow/public_html/lib/img/icons/elbow-plus.gif b/workflow/public_html/lib/img/icons/elbow-plus.gif new file mode 100644 index 000000000..698de4793 Binary files /dev/null and b/workflow/public_html/lib/img/icons/elbow-plus.gif differ diff --git a/workflow/public_html/lib/img/icons/error.png b/workflow/public_html/lib/img/icons/error.png new file mode 100644 index 000000000..dbfda2297 Binary files /dev/null and b/workflow/public_html/lib/img/icons/error.png differ diff --git a/workflow/public_html/lib/img/icons/folder.gif b/workflow/public_html/lib/img/icons/folder.gif new file mode 100644 index 000000000..20412f7c1 Binary files /dev/null and b/workflow/public_html/lib/img/icons/folder.gif differ diff --git a/workflow/public_html/lib/img/icons/help.png b/workflow/public_html/lib/img/icons/help.png new file mode 100644 index 000000000..723c404a9 Binary files /dev/null and b/workflow/public_html/lib/img/icons/help.png differ diff --git a/workflow/public_html/lib/img/icons/information.png b/workflow/public_html/lib/img/icons/information.png new file mode 100644 index 000000000..85c1876b5 Binary files /dev/null and b/workflow/public_html/lib/img/icons/information.png differ diff --git a/workflow/public_html/lib/img/icons/leaf.gif b/workflow/public_html/lib/img/icons/leaf.gif new file mode 100644 index 000000000..445769d3f Binary files /dev/null and b/workflow/public_html/lib/img/icons/leaf.gif differ diff --git a/workflow/public_html/lib/img/leaf.gif b/workflow/public_html/lib/img/leaf.gif new file mode 100644 index 000000000..445769d3f Binary files /dev/null and b/workflow/public_html/lib/img/leaf.gif differ diff --git a/workflow/public_html/lib/img/linhori.png b/workflow/public_html/lib/img/linhori.png new file mode 100644 index 000000000..6a28defa7 Binary files /dev/null and b/workflow/public_html/lib/img/linhori.png differ diff --git a/workflow/public_html/lib/img/linkedin-16.png b/workflow/public_html/lib/img/linkedin-16.png new file mode 100644 index 000000000..45fad66dc Binary files /dev/null and b/workflow/public_html/lib/img/linkedin-16.png differ diff --git a/workflow/public_html/lib/img/linver.png b/workflow/public_html/lib/img/linver.png new file mode 100644 index 000000000..5f1074faa Binary files /dev/null and b/workflow/public_html/lib/img/linver.png differ diff --git a/workflow/public_html/lib/img/load_big.gif b/workflow/public_html/lib/img/load_big.gif new file mode 100644 index 000000000..11c23f8b7 Binary files /dev/null and b/workflow/public_html/lib/img/load_big.gif differ diff --git a/workflow/public_html/lib/img/load_small.gif b/workflow/public_html/lib/img/load_small.gif new file mode 100644 index 000000000..3fd77e34b Binary files /dev/null and b/workflow/public_html/lib/img/load_small.gif differ diff --git a/workflow/public_html/lib/img/loading.gif b/workflow/public_html/lib/img/loading.gif new file mode 100644 index 000000000..20efc1283 Binary files /dev/null and b/workflow/public_html/lib/img/loading.gif differ diff --git a/workflow/public_html/lib/img/mafe-icons-s4e9dfa1250.png b/workflow/public_html/lib/img/mafe-icons-s4e9dfa1250.png new file mode 100644 index 000000000..74c2155f5 Binary files /dev/null and b/workflow/public_html/lib/img/mafe-icons-s4e9dfa1250.png differ diff --git a/workflow/public_html/lib/img/mafe-sprite.png b/workflow/public_html/lib/img/mafe-sprite.png new file mode 100644 index 000000000..e1bbdfac2 Binary files /dev/null and b/workflow/public_html/lib/img/mafe-sprite.png differ diff --git a/workflow/public_html/lib/img/mafe-tools.png b/workflow/public_html/lib/img/mafe-tools.png new file mode 100644 index 000000000..fc7ba6da4 Binary files /dev/null and b/workflow/public_html/lib/img/mafe-tools.png differ diff --git a/workflow/public_html/lib/img/mafe-validate.png b/workflow/public_html/lib/img/mafe-validate.png new file mode 100644 index 000000000..e37f36f81 Binary files /dev/null and b/workflow/public_html/lib/img/mafe-validate.png differ diff --git a/workflow/public_html/lib/img/mafe_sprite.png b/workflow/public_html/lib/img/mafe_sprite.png new file mode 100644 index 000000000..c5ea733be Binary files /dev/null and b/workflow/public_html/lib/img/mafe_sprite.png differ diff --git a/workflow/public_html/lib/img/mafe_sprite_monochrome.png b/workflow/public_html/lib/img/mafe_sprite_monochrome.png new file mode 100644 index 000000000..e0f73f4a4 Binary files /dev/null and b/workflow/public_html/lib/img/mafe_sprite_monochrome.png differ diff --git a/workflow/public_html/lib/img/mafe_sprite_old.png b/workflow/public_html/lib/img/mafe_sprite_old.png new file mode 100644 index 000000000..f09c06983 Binary files /dev/null and b/workflow/public_html/lib/img/mafe_sprite_old.png differ diff --git a/workflow/public_html/lib/img/mafe_sprite_with_zoom.gif b/workflow/public_html/lib/img/mafe_sprite_with_zoom.gif new file mode 100644 index 000000000..5544317d6 Binary files /dev/null and b/workflow/public_html/lib/img/mafe_sprite_with_zoom.gif differ diff --git a/workflow/public_html/lib/img/mafe_tools.png b/workflow/public_html/lib/img/mafe_tools.png new file mode 100644 index 000000000..4201914ba Binary files /dev/null and b/workflow/public_html/lib/img/mafe_tools.png differ diff --git a/workflow/public_html/lib/img/menuParent.gif b/workflow/public_html/lib/img/menuParent.gif new file mode 100644 index 000000000..1e375622f Binary files /dev/null and b/workflow/public_html/lib/img/menuParent.gif differ diff --git a/workflow/public_html/lib/img/moveUpDown.png b/workflow/public_html/lib/img/moveUpDown.png new file mode 100644 index 000000000..d3a633c43 Binary files /dev/null and b/workflow/public_html/lib/img/moveUpDown.png differ diff --git a/workflow/public_html/lib/img/moveUpDown3.png b/workflow/public_html/lib/img/moveUpDown3.png new file mode 100644 index 000000000..9d99626b0 Binary files /dev/null and b/workflow/public_html/lib/img/moveUpDown3.png differ diff --git a/workflow/public_html/lib/img/msk_us.png b/workflow/public_html/lib/img/msk_us.png new file mode 100644 index 000000000..c0c5eb640 Binary files /dev/null and b/workflow/public_html/lib/img/msk_us.png differ diff --git a/workflow/public_html/lib/img/object_permission.gif b/workflow/public_html/lib/img/object_permission.gif new file mode 100644 index 000000000..1bec8aacd Binary files /dev/null and b/workflow/public_html/lib/img/object_permission.gif differ diff --git a/workflow/public_html/lib/img/pager-next-icon.png b/workflow/public_html/lib/img/pager-next-icon.png new file mode 100644 index 000000000..dd9614b5f Binary files /dev/null and b/workflow/public_html/lib/img/pager-next-icon.png differ diff --git a/workflow/public_html/lib/img/pager-previous-icon.png b/workflow/public_html/lib/img/pager-previous-icon.png new file mode 100644 index 000000000..6c5837f45 Binary files /dev/null and b/workflow/public_html/lib/img/pager-previous-icon.png differ diff --git a/workflow/public_html/lib/img/plus.png b/workflow/public_html/lib/img/plus.png new file mode 100644 index 000000000..f90ba62c5 Binary files /dev/null and b/workflow/public_html/lib/img/plus.png differ diff --git a/workflow/public_html/lib/img/plus_.png b/workflow/public_html/lib/img/plus_.png new file mode 100644 index 000000000..638da8207 Binary files /dev/null and b/workflow/public_html/lib/img/plus_.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite-s947c1ade08.png b/workflow/public_html/lib/img/pmui-sprite-s947c1ade08.png new file mode 100644 index 000000000..d7a380286 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite-s947c1ade08.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite-sc9cf09aadd.png b/workflow/public_html/lib/img/pmui-sprite-sc9cf09aadd.png new file mode 100644 index 000000000..f307a538c Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite-sc9cf09aadd.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/arrow-down.png b/workflow/public_html/lib/img/pmui-sprite/arrow-down.png new file mode 100644 index 000000000..a0fe310ef Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/arrow-down.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/arrow-right.png b/workflow/public_html/lib/img/pmui-sprite/arrow-right.png new file mode 100644 index 000000000..cccce0e75 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/arrow-right.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/checkbox-off.png b/workflow/public_html/lib/img/pmui-sprite/checkbox-off.png new file mode 100644 index 000000000..11765214b Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/checkbox-off.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/checkbox-on.png b/workflow/public_html/lib/img/pmui-sprite/checkbox-on.png new file mode 100644 index 000000000..f88404e6a Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/checkbox-on.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/delete-16.png b/workflow/public_html/lib/img/pmui-sprite/delete-16.png new file mode 100644 index 000000000..3fdf31ad3 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/delete-16.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/error-16.png b/workflow/public_html/lib/img/pmui-sprite/error-16.png new file mode 100644 index 000000000..33c876b23 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/error-16.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/error-64.png b/workflow/public_html/lib/img/pmui-sprite/error-64.png new file mode 100644 index 000000000..06306e8d0 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/error-64.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/info-16.png b/workflow/public_html/lib/img/pmui-sprite/info-16.png new file mode 100644 index 000000000..85c1876b5 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/info-16.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/info-64.png b/workflow/public_html/lib/img/pmui-sprite/info-64.png new file mode 100644 index 000000000..95926f21d Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/info-64.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/question-16.png b/workflow/public_html/lib/img/pmui-sprite/question-16.png new file mode 100644 index 000000000..723c404a9 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/question-16.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/question-64.png b/workflow/public_html/lib/img/pmui-sprite/question-64.png new file mode 100644 index 000000000..5bea98888 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/question-64.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/success-64.png b/workflow/public_html/lib/img/pmui-sprite/success-64.png new file mode 100644 index 000000000..79fcb4535 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/success-64.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/warning-16.png b/workflow/public_html/lib/img/pmui-sprite/warning-16.png new file mode 100644 index 000000000..dbfda2297 Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/warning-16.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/warning-64.png b/workflow/public_html/lib/img/pmui-sprite/warning-64.png new file mode 100644 index 000000000..82306e77c Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/warning-64.png differ diff --git a/workflow/public_html/lib/img/pmui-sprite/window-close.png b/workflow/public_html/lib/img/pmui-sprite/window-close.png new file mode 100644 index 000000000..3103f63dd Binary files /dev/null and b/workflow/public_html/lib/img/pmui-sprite/window-close.png differ diff --git a/workflow/public_html/lib/img/process_maker.png b/workflow/public_html/lib/img/process_maker.png new file mode 100644 index 000000000..89fed39eb Binary files /dev/null and b/workflow/public_html/lib/img/process_maker.png differ diff --git a/workflow/public_html/lib/img/refreshIcon.png b/workflow/public_html/lib/img/refreshIcon.png new file mode 100644 index 000000000..c72b685b1 Binary files /dev/null and b/workflow/public_html/lib/img/refreshIcon.png differ diff --git a/workflow/public_html/lib/img/rules.png b/workflow/public_html/lib/img/rules.png new file mode 100644 index 000000000..70fa7b2ec Binary files /dev/null and b/workflow/public_html/lib/img/rules.png differ diff --git a/workflow/public_html/lib/img/shape01.png b/workflow/public_html/lib/img/shape01.png new file mode 100644 index 000000000..4a9ebab34 Binary files /dev/null and b/workflow/public_html/lib/img/shape01.png differ diff --git a/workflow/public_html/lib/img/shape02.png b/workflow/public_html/lib/img/shape02.png new file mode 100644 index 000000000..27887759b Binary files /dev/null and b/workflow/public_html/lib/img/shape02.png differ diff --git a/workflow/public_html/lib/img/shape03.png b/workflow/public_html/lib/img/shape03.png new file mode 100644 index 000000000..beb37b686 Binary files /dev/null and b/workflow/public_html/lib/img/shape03.png differ diff --git a/workflow/public_html/lib/img/shape04.png b/workflow/public_html/lib/img/shape04.png new file mode 100644 index 000000000..e5d5eff20 Binary files /dev/null and b/workflow/public_html/lib/img/shape04.png differ diff --git a/workflow/public_html/lib/img/shape05.png b/workflow/public_html/lib/img/shape05.png new file mode 100644 index 000000000..950adfcf7 Binary files /dev/null and b/workflow/public_html/lib/img/shape05.png differ diff --git a/workflow/public_html/lib/img/shape06.png b/workflow/public_html/lib/img/shape06.png new file mode 100644 index 000000000..9cb7648ac Binary files /dev/null and b/workflow/public_html/lib/img/shape06.png differ diff --git a/workflow/public_html/lib/img/shape07.png b/workflow/public_html/lib/img/shape07.png new file mode 100644 index 000000000..1b15dae15 Binary files /dev/null and b/workflow/public_html/lib/img/shape07.png differ diff --git a/workflow/public_html/lib/img/shape08.png b/workflow/public_html/lib/img/shape08.png new file mode 100644 index 000000000..f48e89218 Binary files /dev/null and b/workflow/public_html/lib/img/shape08.png differ diff --git a/workflow/public_html/lib/img/shape09.png b/workflow/public_html/lib/img/shape09.png new file mode 100644 index 000000000..1ee31b0e7 Binary files /dev/null and b/workflow/public_html/lib/img/shape09.png differ diff --git a/workflow/public_html/lib/img/shape10.png b/workflow/public_html/lib/img/shape10.png new file mode 100644 index 000000000..5b3ec2551 Binary files /dev/null and b/workflow/public_html/lib/img/shape10.png differ diff --git a/workflow/public_html/lib/img/shapes-refresh.png b/workflow/public_html/lib/img/shapes-refresh.png new file mode 100644 index 000000000..5fa7444a2 Binary files /dev/null and b/workflow/public_html/lib/img/shapes-refresh.png differ diff --git a/workflow/public_html/lib/img/shapes-toogle.png b/workflow/public_html/lib/img/shapes-toogle.png new file mode 100644 index 000000000..06700a801 Binary files /dev/null and b/workflow/public_html/lib/img/shapes-toogle.png differ diff --git a/workflow/public_html/lib/img/sharepoint.gif b/workflow/public_html/lib/img/sharepoint.gif new file mode 100644 index 000000000..d32159193 Binary files /dev/null and b/workflow/public_html/lib/img/sharepoint.gif differ diff --git a/workflow/public_html/lib/img/sort_asc.png b/workflow/public_html/lib/img/sort_asc.png new file mode 100644 index 000000000..e1ba61a80 Binary files /dev/null and b/workflow/public_html/lib/img/sort_asc.png differ diff --git a/workflow/public_html/lib/img/sort_asc_disabled.png b/workflow/public_html/lib/img/sort_asc_disabled.png new file mode 100644 index 000000000..fb11dfe24 Binary files /dev/null and b/workflow/public_html/lib/img/sort_asc_disabled.png differ diff --git a/workflow/public_html/lib/img/sort_both.png b/workflow/public_html/lib/img/sort_both.png new file mode 100644 index 000000000..af5bc7c5a Binary files /dev/null and b/workflow/public_html/lib/img/sort_both.png differ diff --git a/workflow/public_html/lib/img/sort_desc.png b/workflow/public_html/lib/img/sort_desc.png new file mode 100644 index 000000000..0e156deb5 Binary files /dev/null and b/workflow/public_html/lib/img/sort_desc.png differ diff --git a/workflow/public_html/lib/img/sort_desc_disabled.png b/workflow/public_html/lib/img/sort_desc_disabled.png new file mode 100644 index 000000000..c9fdd8a15 Binary files /dev/null and b/workflow/public_html/lib/img/sort_desc_disabled.png differ diff --git a/workflow/public_html/lib/img/spriteOld.png b/workflow/public_html/lib/img/spriteOld.png new file mode 100644 index 000000000..9d022f06f Binary files /dev/null and b/workflow/public_html/lib/img/spriteOld.png differ diff --git a/workflow/public_html/lib/img/startcoronahelp.png b/workflow/public_html/lib/img/startcoronahelp.png new file mode 100644 index 000000000..7530d11d9 Binary files /dev/null and b/workflow/public_html/lib/img/startcoronahelp.png differ diff --git a/workflow/public_html/lib/img/step.png b/workflow/public_html/lib/img/step.png new file mode 100644 index 000000000..fc20b3571 Binary files /dev/null and b/workflow/public_html/lib/img/step.png differ diff --git a/workflow/public_html/lib/img/steps.png b/workflow/public_html/lib/img/steps.png new file mode 100644 index 000000000..d1e2d8778 Binary files /dev/null and b/workflow/public_html/lib/img/steps.png differ diff --git a/workflow/public_html/lib/img/subProcess.png b/workflow/public_html/lib/img/subProcess.png new file mode 100644 index 000000000..5f200fa30 Binary files /dev/null and b/workflow/public_html/lib/img/subProcess.png differ diff --git a/workflow/public_html/lib/img/subm.png b/workflow/public_html/lib/img/subm.png new file mode 100644 index 000000000..95228c17d Binary files /dev/null and b/workflow/public_html/lib/img/subm.png differ diff --git a/workflow/public_html/lib/img/submit.png b/workflow/public_html/lib/img/submit.png new file mode 100644 index 000000000..0f56f59cd Binary files /dev/null and b/workflow/public_html/lib/img/submit.png differ diff --git a/workflow/public_html/lib/img/suggest.png b/workflow/public_html/lib/img/suggest.png new file mode 100644 index 000000000..aaa1ba729 Binary files /dev/null and b/workflow/public_html/lib/img/suggest.png differ diff --git a/workflow/public_html/lib/img/table.png b/workflow/public_html/lib/img/table.png new file mode 100644 index 000000000..5ec4a185d Binary files /dev/null and b/workflow/public_html/lib/img/table.png differ diff --git a/workflow/public_html/lib/img/tracker.gif b/workflow/public_html/lib/img/tracker.gif new file mode 100644 index 000000000..2d83cb730 Binary files /dev/null and b/workflow/public_html/lib/img/tracker.gif differ diff --git a/workflow/public_html/lib/img/trigger.png b/workflow/public_html/lib/img/trigger.png new file mode 100644 index 000000000..6c8218cde Binary files /dev/null and b/workflow/public_html/lib/img/trigger.png differ diff --git a/workflow/public_html/lib/img/triggerContent.png b/workflow/public_html/lib/img/triggerContent.png new file mode 100644 index 000000000..ced18fc98 Binary files /dev/null and b/workflow/public_html/lib/img/triggerContent.png differ diff --git a/workflow/public_html/lib/img/triggerWizard.png b/workflow/public_html/lib/img/triggerWizard.png new file mode 100644 index 000000000..8b95f589d Binary files /dev/null and b/workflow/public_html/lib/img/triggerWizard.png differ diff --git a/workflow/public_html/lib/img/tumblr-16.png b/workflow/public_html/lib/img/tumblr-16.png new file mode 100644 index 000000000..f1c0ae021 Binary files /dev/null and b/workflow/public_html/lib/img/tumblr-16.png differ diff --git a/workflow/public_html/lib/img/twitter-16.png b/workflow/public_html/lib/img/twitter-16.png new file mode 100644 index 000000000..261396b4e Binary files /dev/null and b/workflow/public_html/lib/img/twitter-16.png differ diff --git a/workflow/public_html/lib/img/users.png b/workflow/public_html/lib/img/users.png new file mode 100644 index 000000000..b70f90da3 Binary files /dev/null and b/workflow/public_html/lib/img/users.png differ diff --git a/workflow/public_html/lib/img/zimbra.gif b/workflow/public_html/lib/img/zimbra.gif new file mode 100644 index 000000000..e63cb8df6 Binary files /dev/null and b/workflow/public_html/lib/img/zimbra.gif differ diff --git a/workflow/public_html/lib/js/jquery-1.10.2.min.js b/workflow/public_html/lib/js/jquery-1.10.2.min.js new file mode 100644 index 000000000..8569bc49f --- /dev/null +++ b/workflow/public_html/lib/js/jquery-1.10.2.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license*/ +(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="
",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
t
",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t +}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/\s*$/g,At={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X
","
"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); +u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x(""); + this.iframe.attr("id", defaultIframeOptions.id); + this.iframe.attr("name", defaultIframeOptions.name); + this.iframe.css("border", "none"); + this.iframe.css("width", "100%"); + this.iframe.css("height", "100%"); + + this.body = $("
"); + this.body.append(this.toolbar); + this.body.append(this.iframe); + }; + Preview.prototype.show = function () { + jQuery('body').append(this.body); + this.body.show(); + }; + Preview.prototype.close = function () { + this.onClose(); + this.body.remove(); + }; + Preview.prototype.setData = function () { + var that = this; + that.iframe[0].src = this.srcPreview; + that.iframe[0].onload = function () { + var pm = this.contentWindow.window; + if (pm && pm.PMDynaform) { + pm.dynaform = new pm.PMDynaform.core.Project({ + data: this.contentWindow.window.jsonData, + keys: { + server: HTTP_SERVER_HOSTNAME, + projectId: PMDesigner.project.id, + workspace: WORKSPACE + }, + token: { + accessToken: PMDesigner.project.keys.access_token + }, + isPreview: true, + isRTL: this.contentWindow ? this.contentWindow.window.isRTL : false + }); + $(this.contentWindow.document).find('form').submit(function (e) { + e.preventDefault(); + return false; + }); + if (pm.PMDynaform.view && pm.PMDynaform.view.ModalProgressBar) { + pm.PMDynaform.view.ModalProgressBar.prototype.render = function () { + return this; + }; + } + } + }; + }; + FormDesigner.extendNamespace('FormDesigner.main.Preview', Preview); +}()); + + +(function () { + var DialogConfirmClose = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmClose.prototype.init.call(this, appendTo); + }; + DialogConfirmClose.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to close? All your changes will be lost if you close it.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmClose', DialogConfirmClose); +}()); +(function () { + var DialogInvalidProperties = function (appendTo) { + this.onAccept = new Function(); + DialogInvalidProperties.prototype.init.call(this, appendTo); + }; + DialogInvalidProperties.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: true, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "alert"); + + var msg = ""; + var dt = $.globalInvalidProperties; + for (var i = 0; i < dt.length; i++) { + msg = msg + dt[i] + "
"; + } + msg = msg.replace(/[,\s]+$/, ""); + this.dialog.append("
" + + "Properties invalid elements:

".translate() + msg + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogInvalidProperties', DialogInvalidProperties); +}()); +(function () { + var DialogConfirmImport = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmImport.prototype.init.call(this, appendTo); + }; + DialogConfirmImport.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to import? All your changes will be lost if you import it.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmImport', DialogConfirmImport); +}()); +(function () { + var DialogConfirmClear = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmClear.prototype.init.call(this, appendTo); + }; + DialogConfirmClear.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to clear? All your changes will be lost if you clear it.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmClear', DialogConfirmClear); +}()); +(function () { + var DialogInformation = function (appendTo) { + this.onAccept = new Function(); + DialogInformation.prototype.init.call(this, appendTo); + }; + DialogInformation.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "The variable is being used.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogInformation', DialogInformation); +}()); +(function () { + var DialogScript = function (appendTo) { + this.onSave = new Function(); + this.onClose = new Function(); + DialogScript.prototype.init.call(this, appendTo); + }; + DialogScript.prototype.init = function (appendTo) { + var that = this; + this.save = $("" + "Save".translate() + ""); + this.save.on("click", function () { + that.onSave(); + that.dialog.dialog("close").remove(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.save); + + $.ui.keyCode.TAB = null;//focus button prevents dialog with CodeMirror tab + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 940, + height: 500, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + $.ui.keyCode.TAB = 9; + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.textarea = $(""); + this.body = $("
"); + this.body.append(this.textarea); + this.dialog.append(this.body); + this.dialog.append("

" + "Press".translate() + " ctrl-space " + "to activate autocompletion".translate() + ".

"); + this.dialog.append(this.buttons); + + this.editor = CodeMirror.fromTextArea(this.textarea[0], { + lineNumbers: true, + matchBrackets: true, + autoCloseBrackets: true, + extraKeys: {"Ctrl-Space": "autocomplete"}, + mode: "application/javascript", + viewportMargin: Infinity, + className: "CodeMirror-hints-custom-mafe" + }); + this.editor.setSize(910, 350); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogScript', DialogScript); +}()); +(function () { + var DialogFormula = function (appendTo, fields) { + this.onSave = new Function(); + this.onClose = new Function(); + this.fields = fields; + DialogFormula.prototype.init.call(this, appendTo); + }; + DialogFormula.prototype.init = function (appendTo) { + var that = this; + this.save = $("" + "Save".translate() + ""); + this.save.on("click", function () { + that.onSave(); + that.dialog.dialog("close").remove(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.save); + + $.ui.keyCode.TAB = null;//focus button prevents dialog with CodeMirror tab + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 940, + height: 500, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + $.ui.keyCode.TAB = 9; + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.textarea = $(""); + this.body = $("
"); + this.body.append(this.textarea); + this.dialog.append(this.body); + this.dialog.append("

" + "Press".translate() + " ctrl-space " + "to activate autocompletion".translate() + ".

"); + this.dialog.append(this.buttons); + + this.editor = CodeMirror.fromTextArea(this.textarea[0], { + lineNumbers: true, + matchBrackets: true, + autoCloseBrackets: true, + extraKeys: {"Ctrl-Space": "autocomplete"}, + mode: "application/javascript", + viewportMargin: Infinity, + className: "CodeMirror-hints-custom-mafe" + }); + this.editor.setSize(910, 350); + //add elements for codemirror autocomplete + CodeMirror.hint.javascript = function (cm) { + var inner = {from: cm.getCursor(), to: cm.getCursor(), list: []}; + for (var i = 0; i < that.fields.length; i++) { + if (that.fields[i].var_name) { + inner.list.push(that.fields[i].var_name); + } + } + var others = [ + "parseInt()", + "parseFloat()", + ".concat()", + ".toString()", + ".toUpperCase()", + ".toLowerCase()", + ".indexOf()", + ".substring()", + ".lastIndexOf()", + ".split()" + ]; + for (var i = 0; i < others.length; i++) { + inner.list.push(others[i]); + } + return inner; + }; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogFormula', DialogFormula); +}()); +(function () { + var DialogInvalidFile = function (appendTo, msg) { + this.onAccept = new Function(); + this.msg = msg; + DialogInvalidFile.prototype.init.call(this, appendTo); + }; + DialogInvalidFile.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "alert"); + + this.dialog.append("
" + + "Invalid file: ".translate() + that.msg + ". " + + "Please upload a file with a valid extension (.json)".translate() + "." + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogInvalidFile', DialogInvalidFile); +}()); +(function () { + var DialogVariable = function (appendTo, render) { + this.render = render; + this.onClose = new Function(); + this.onLoad = new Function(); + this.onClick = new Function(); + DialogVariable.prototype.init.call(this, appendTo); + }; + DialogVariable.prototype.init = function (appendTo) { + var that = this; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.search = $("
" + "Search".translate() + " :
"); + this.search.find("input").on("keyup", function () { + var input = this; + that.body.find(">div").each(function (i, e) { + var sw = false; + $(e).find(">div").each(function (i, e) { + sw = sw || $(e).text().toLowerCase().indexOf(input.value.toLowerCase()) > -1; + }); + if (sw) + $(e).show(); + else + $(e).hide(); + }); + }); + this.search.find("img").on("click", function () { + that.load(); + }); + + this.body = $("
"); + this.dialog.append(this.search); + this.dialog.append(this.body); + }; + DialogVariable.prototype.load = function () { + var that = this; + this.body.find(">div").remove(); + var restProxy = new PMRestClient({ + endpoint: 'process-variables', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + response.sort(function (a, b) { + if (a.var_name < b.var_name) + return -1; + if (a.var_name > b.var_name) + return 1; + return 0; + }); + for (var i = 0; i < response.length; i++) { + $.validDataTypeAndControlType(response[i].var_field_type, that.render, function () { + that.addItem(response[i]); + }); + } + that.onLoad(response); + } + }); + restProxy.executeRestClient(); + }; + DialogVariable.prototype.addItem = function (variable) { + var that = this; + var item = $("
" + + "
[" + variable.var_field_type + "]
" + + "
" + variable.var_name + "
" + + "
"); + item.on("click", function () { + that.onClick(variable); + }); + this.body.append(item); + return item; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogVariable', DialogVariable); +}()); +(function () { + var DialogDBConnection = function (appendTo) { + this.onClose = new Function(); + this.onLoad = new Function(); + this.onClick = new Function(); + DialogDBConnection.prototype.init.call(this, appendTo); + }; + DialogDBConnection.prototype.init = function (appendTo) { + var that = this; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.search = $("

" + "Search".translate() + " :

"); + this.search.find(">input").on("keyup", function () { + var input = this; + that.body.find(">div").each(function (i, e) { + var sw = false; + $(e).find(">div").each(function (i, e) { + sw = sw || $(e).text().toLowerCase().indexOf(input.value.toLowerCase()) > -1; + }); + if (sw) + $(e).show(); + else + $(e).hide(); + }); + }); + this.search.find("img").on("click", function () { + that.load(); + }); + this.body = $("
"); + this.dialog.append(this.search); + this.dialog.append(this.body); + this.load(); + }; + DialogDBConnection.prototype.load = function () { + var that = this; + this.body.find(">div").remove(); + that.addItem({label: "PM Database", value: "workflow"}); + var restProxy = new PMRestClient({ + endpoint: "database-connections", + typeRequest: "get", + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i++) { + if (response[i].dbs_connection_type === "TNS") { + that.addItem({ + label: "[" + response[i].dbs_tns + "] " + response[i].dbs_type + " : " + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } else { + that.addItem({ + label: "[" + response[i].dbs_server + ":" + response[i].dbs_port + "] " + response[i].dbs_type + ": " + response[i].dbs_database_name + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } + } + that.onLoad(response); + } + }); + restProxy.executeRestClient(); + }; + DialogDBConnection.prototype.addItem = function (variable) { + var that = this; + var item = $("
" + + "
" + variable.label + "
" + + "
"); + item.on("click", function () { + that.onClick(variable); + }); + this.body.append(item); + return item; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogDBConnection', DialogDBConnection); +}()); +(function () { + var DialogSql = function (appendTo) { + this.onSave = new Function(); + this.onClose = new Function(); + DialogSql.prototype.init.call(this, appendTo); + }; + DialogSql.prototype.init = function (appendTo) { + var that = this; + this.save = $("" + "Save".translate() + ""); + this.save.on("click", function () { + that.onSave(); + that.dialog.dialog("close").remove(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.save); + + $.ui.keyCode.TAB = null;//focus button prevents dialog with CodeMirror tab + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 940, + height: 500, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + $.ui.keyCode.TAB = 9; + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.textarea = $(""); + this.body = $("
"); + this.body.append(this.textarea); + this.dialog.append(this.body); + this.dialog.append("

" + "Press".translate() + " ctrl-space " + "to activate autocompletion".translate() + ".

"); + this.dialog.append(this.buttons); + + this.editor = CodeMirror.fromTextArea(this.textarea[0], { + lineNumbers: true, + matchBrackets: true, + autoCloseBrackets: true, + extraKeys: {"Ctrl-Space": "autocomplete"}, + mode: "text/x-sql", + viewportMargin: Infinity, + className: "CodeMirror-hints-custom-mafe" + }); + this.editor.setSize(910, 350); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogSql', DialogSql); +}()); +(function () { + var DialogOptions = function (appendTo, options) { + this.onApply = new Function(); + this.onClose = new Function(); + this.appendTo = appendTo; + this.options = options; + DialogOptions.prototype.init.call(this); + }; + DialogOptions.prototype.init = function () { + var that = this; + this.save = $("" + "Apply".translate() + ""); + this.save.on("click", function () { + if (!that.isValid()) { + return false; + } + that.onApply(); + that.dialog.dialog("close").remove(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.save); + + this.edit = $(""); + this.add = $("" + "Create".translate() + ""); + this.add.on("click", function () { + var row = that.addItem("", ""); + var cells = row.find(".fd-table-td-edit"); + that.setInputEdit($(cells[0])); + return false; + }); + this.add.on("keydown", function (e) { + var row = that.table.find("tr"); + if (row.length > 0 && e.keyCode === 9 && !e.shiftKey) { + that.setInputEdit($($(row[1]).find(".fd-table-td-edit")[0])); + return false; + } + }); + + this.tbody = $(""); + this.tbody.sortable({ + placeholder: "fd-drag-drop-placeholder", + handle: ".fd-drag-drop", + stop: function (event, ui) { + + }, + start: function (event, ui) { + ui.placeholder.html("") + } + }).droppable({ + drop: function (event, ui) { + } + }); + + this.table = $( + "
" + + "" + + "" + + "" + + "" + + "" + + "
" + "Key".translate() + "" + "Label".translate() + "
"); + this.table.append(this.tbody); + this.msgError = $("
"); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: this.appendTo ? this.appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.dialog.append("

" + "Please add option and click in cell for editing the cell value".translate() + ".

"); + this.dialog.append(this.add); + this.dialog.append($("
").append(this.table)); + this.dialog.append(this.msgError); + this.dialog.append(this.buttons); + this.load(); + }; + DialogOptions.prototype.load = function () { + for (var i = 0; i < this.options.length; i++) + this.addItem(this.options[i].value, this.options[i].label); + }; + DialogOptions.prototype.addItem = function (value, label) { + var that = this, cell; + var del = $("" + + "" + "Delete".translate() + "" + + "" + + ""); + del.find(".fd-button").on("click", function () { + var a = new FormDesigner.main.DialogConfirmDeleteOption(); + a.onAccept = function () { + del.parent().remove(); + }; + return false; + }); + del.find(".fd-button").on("keydown", function (e) { + var ri = $(this).parent().parent()[0].rowIndex + 1; + if (e.keyCode === 9 && !e.shiftKey && that.table.find("tr").length > ri) { + that.setInputEdit($($(that.table.find("tr")[ri]).find(".fd-table-td-edit")[0])); + return false; + } + if (e.keyCode === 9 && e.shiftKey) { + var row = $(this).parent().parent(); + that.setInputEdit($($(row).find(".fd-table-td-edit")[1])); + return false; + } + }); + var row = $(""); + cell = $("").text(value); + row.append(cell); + cell = $("").text(label); + row.append(cell); + row.append(del); + row.find(".fd-table-td-edit").on("click", function (e) { + e.stopPropagation(); + that.setInputEdit($(e.target)); + return false; + }); + this.tbody.append(row); + return row; + }; + DialogOptions.prototype.getOptions = function () { + var a = []; + if (this.edit.parent()[0] && this.edit.parent()[0].nodeName === "TD") { + this.edit.parent().text(this.edit.val().trim()); + this.edit.remove(); + } + var aux = ""; + this.tbody.find(".fd-table-td-edit").each(function (i, e) { + if (i % 2 === 1) { + a.push({ + value: aux, + label: $(e).text() + }); + } + aux = $(e).text(); + }); + return a; + }; + DialogOptions.prototype.isValid = function () { + this.tbody.find(".fd-table-td-edit").removeClass("fd-table-td-error"); + var options = this.getOptions(); + for (var i = 0; i < options.length; i++) { + for (var j = 0; j < options.length; j++) { + if (i !== j && options[j].value === options[i].value) { + this.msgError.text("Duplicate value for key".translate() + "."); + $(this.tbody.find("tr")[j]).find(".fd-table-td-edit").addClass("fd-table-td-error"); + return false; + } + if (options[j].label === "") { + this.msgError.text("The label is empty".translate() + "."); + $(this.tbody.find("tr")[j]).find(".fd-table-td-edit").addClass("fd-table-td-error"); + return false; + } + } + } + this.msgError.text(""); + return true; + }; + DialogOptions.prototype.setOptionsBoolean = function () { + this.tbody.find("tr").each(function (i, e) { + $(e).find(".fd-table-td-edit").each(function (i, cell) { + if (0 === i) + $(cell).off(); + }); + $(e).find(".fd-button").hide(); + $(e).find(".fd-drag-drop").hide(); + }); + this.add.hide(); + }; + DialogOptions.prototype.setInputEdit = function (cell) { + var that = this; + if (that.edit.parent()[0] && that.edit.parent()[0].nodeName === "TD") { + that.edit.parent().text(that.edit.val().trim()); + } + that.edit.val(cell.text()); + cell.text(""); + cell.append(that.edit); + setTimeout(function () { + that.edit.focus(); + }, 50); + that.edit.on("click", function (e) { + e.stopPropagation(); + return false; + }); + that.edit.on("keydown", function (e) { + var cell = that.edit.parent(); + var ci = cell[0].cellIndex; + if (e.keyCode === 9 && ci === 0 && !e.shiftKey) { + that.setInputEdit(cell.next()); + return false; + } + if (e.keyCode === 9 && ci === 1 && e.shiftKey) { + that.setInputEdit(cell.prev()); + return false; + } + }); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogOptions', DialogOptions); +}()); +(function () { + var DialogLanguage = function (appendTo, dyn_uid) { + this.onClose = new Function(); + this.onLoad = new Function(); + this.dyn_uid = dyn_uid; + DialogLanguage.prototype.init.call(this, appendTo); + }; + DialogLanguage.prototype.init = function (appendTo) { + var that = this; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.uploadFile = $("
" + + "" + + "
"); + this.uploadFile.find(".fd-gridform-language-upload").on("change", function (e) { + var win = window, fd = new FormData(), xhr, val = 'LANGUAGE'; + fd.append(val, e.target.files[0]); + if (win.XMLHttpRequest) + xhr = new XMLHttpRequest(); + else if (win.ActiveXObject) + xhr = new ActiveXObject('Microsoft.XMLHTTP'); + xhr.open('POST', '/api/1.0/' + WORKSPACE + '/project/' + PMDesigner.project.id + '/dynaform/' + that.dyn_uid + '/upload-language', true); + xhr.setRequestHeader('Authorization', 'Bearer ' + PMDesigner.project.keys.access_token); + xhr.onload = function () { + if (this.status === 200) { + that.uploadFile[0].reset(); + that.load(); + } else { + that.uploadFile[0].reset(); + } + }; + xhr.send(fd); + }); + + this.search = $("

" + "Search".translate() + " :

"); + this.search.find(">input").on("keyup", function () { + var input = this; + that.body.find(">div").each(function (i, e) { + var sw = false; + $(e).find(">div").each(function (i, e) { + sw = sw || $(e).text().toLowerCase().indexOf(input.value.toLowerCase()) > -1; + }); + if (sw) + $(e).show(); + else + $(e).hide(); + }); + }); + this.search.find("img").on("click", function () { + that.load(); + }); + this.body = $("
"); + this.dialog.append(this.uploadFile); + this.dialog.append(this.search); + this.dialog.append(this.body); + this.load(); + }; + DialogLanguage.prototype.load = function () { + var that = this; + this.body.find(">div").remove(); + var restProxy = new PMRestClient({ + endpoint: "dynaform/" + this.dyn_uid + "/list-language", + typeRequest: "get", + functionSuccess: function (xhr, response) { + //default lang + var item = that.addItem({ + label: "English [processmaker.en.po]", + value: "en" + }); + item.find(".fd-button").hide(); + //lang + for (var i = 0; i < response.length; i++) { + that.addItem({ + label: response[i]["X-Poedit-Language"] + " [" + response[i]["File-Name"] + "]", + value: response[i].Lang + }); + } + that.onLoad(response); + } + }); + restProxy.executeRestClient(); + }; + DialogLanguage.prototype.addItem = function (variable) { + var that = this; + var item = $("
" + + "
" + variable.label + "
" + + "
" + + "" + "Delete".translate() + "" + + "
" + + "
"); + item.find(".fd-button").on("click", function (e) { + e.stopPropagation(); + var a = new FormDesigner.main.DialogConfirmDeleteLang(); + a.onAccept = function () { + var restProxy = new PMRestClient({ + endpoint: "dynaform/" + that.dyn_uid + "/delete-language/" + variable.value, + typeRequest: "post", + functionSuccess: function (xhr, response) { + that.load(); + } + }); + restProxy.executeRestClient(); + } + return false; + }); + item.on("click", function (e) { + e.stopPropagation(); + var restProxy = new PMRestClient({ + endpoint: "dynaform/" + that.dyn_uid + "/download-language/" + variable.value, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var name = "processmaker." + response.lang + ".po"; + if (window.navigator.msSaveBlob) { + window.navigator.msSaveBlob(new Blob([response.labels], {'type': 'application/octet-stream'}), name); + return false; + } + var a = document.createElement('a'); + document.body.appendChild(a); + a.href = window.URL.createObjectURL(new Blob([response.labels], {'type': 'application/octet-stream'})); + a.download = name; + a.click(); + document.body.removeChild(a); + } + }); + restProxy.executeRestClient(); + return false; + }); + this.body.append(item); + return item; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogLanguage', DialogLanguage); +}()); +(function () { + var DialogConfirmDeleteLang = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmDeleteLang.prototype.init.call(this, appendTo); + }; + DialogConfirmDeleteLang.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to delete this lang?".translate() + "." + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmDeleteLang', DialogConfirmDeleteLang); +}()); +(function () { + var DialogConfirmDeleteOption = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmDeleteOption.prototype.init.call(this, appendTo); + }; + DialogConfirmDeleteOption.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to delete this option?".translate() + "." + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmDeleteOption', DialogConfirmDeleteOption); +}()); +(function () { + var DialogInvalid = function (appendTo, property, type, config) { + this.property = property; + this.type = type; + this.config = config || null; + this.onAccept = new Function(); + this.onClose = new Function(); + DialogInvalid.prototype.init.call(this, appendTo); + }; + DialogInvalid.prototype.init = function (appendTo) { + var that = this, + configDialog = this.getErrorMessage(this.type, this.property, this.config); + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.onClose(); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "alert"); + + this.dialog.append("
" + + configDialog.message + + "
"); + this.dialog.append(this.buttons); + this.accept.focus(); + }; + /** + * Get error message + * @param type + * @param property + * @param config + * @returns {Object} + */ + DialogInvalid.prototype.getErrorMessage = function (type, property, config) { + var conf = {}; + conf.title = (config) ? this.config.title.translate() : 'Errors'.translate(); + switch (type) { + case 'required': + conf.message = "The ".translate() + property + " is required.".translate(); + break; + case 'invalid': + conf.message = "The ".translate() + property + " is invalid.".translate(); + break; + case 'duplicated': + conf.message = "The ".translate() + property + " is duplicated.".translate(); + break; + case 'custom': + conf.message = (config) ? config.msg.translate() : ''; + break; + } + return conf; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogInvalid', DialogInvalid); +}()); + +(function () { + var DialogRegularExpression = function (appendTo, dataType) { + this.dataType = dataType; + this.onClose = new Function(); + this.onClick = new Function(); + DialogRegularExpression.prototype.init.call(this, appendTo); + }; + DialogRegularExpression.prototype.init = function (appendTo) { + var that = this; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.body = $("
"); + this.dialog.append("" + + "Enter a regular expression which is a search pattern which matches the text entered in the field. ".translate() + + "To learn more about regular expressions, see the wiki.

".translate() + + "Examples:
".translate() + + "
"); + this.dialog.append(this.body); + this.load(); + }; + DialogRegularExpression.prototype.load = function () { + var that = this, data; + data = [{ + dataType: "integer", name: "An integer".translate(), value: "^[-+]?[0-9]+$" + }, { + dataType: "float", name: "An integer or decimal number".translate(), value: "[-+]?[0-9]+\\.[0-9]+$" + }, { + dataType: "string", name: "An email address".translate(), value: "^\\w+(\\.\\w+)*@(\\w+\\.)+\\w{2,4}$" + } + ]; + this.body.find(">div").remove(); + for (var i = 0; i < data.length; i++) { + if (that.dataType === data[i].dataType || that.dataType === "") { + that.addItem(data[i]); + } + } + }; + DialogRegularExpression.prototype.addItem = function (regex) { + var that = this; + var item = $("
" + + "
" + regex.name + "
" + + "
" + regex.value + "
" + + "
"); + item.on("click", function () { + that.onClick(regex); + }); + this.body.append(item); + return item; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogRegularExpression', DialogRegularExpression); +}()); +(function () { + var DialogConfirmClearVariable = function (appendTo) { + this.onAccept = new Function(); + DialogConfirmClearVariable.prototype.init.call(this, appendTo); + }; + DialogConfirmClearVariable.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.dialog.append("
" + + "Do you want to clear this variable? The following properties are reset: Variable, Data Type, DB Connection, SQL and Options.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirmClearVariable', DialogConfirmClearVariable); +}()); +(function () { + var DialogContent = function (appendTo) { + this.onSave = new Function(); + this.onClose = new Function(); + DialogContent.prototype.init.call(this, appendTo); + }; + DialogContent.prototype.init = function (appendTo) { + var that = this; + this.save = $("" + "Save".translate() + ""); + this.save.on("click", function () { + that.onSave(); + that.dialog.dialog("close").remove(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.save); + + $.ui.keyCode.TAB = null;//focus button prevents dialog with CodeMirror tab + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 940, + height: 500, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + $.ui.keyCode.TAB = 9; + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.textarea = $(""); + this.body = $("
"); + this.body.append(this.textarea); + this.dialog.append(this.body); + this.dialog.append("

" + "Press".translate() + " ctrl-space " + "to activate autocompletion".translate() + ".

"); + this.dialog.append(this.buttons); + + this.editor = CodeMirror.fromTextArea(this.textarea[0], { + lineNumbers: true, + matchBrackets: true, + autoCloseBrackets: true, + extraKeys: {"Ctrl-Space": "autocomplete"}, + mode: "text/html", + viewportMargin: Infinity, + className: "CodeMirror-hints-custom-mafe" + }); + this.editor.setSize(910, 350); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogContent', DialogContent); +}()); +(function () { + var DialogUnsupported = function (appendTo) { + this.onAccept = new Function(); + DialogUnsupported.prototype.init.call(this, appendTo); + }; + DialogUnsupported.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: true, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "success"); + + var msg = ""; + var dt = $.globalInvalidProperties; + for (var i = 0; i < dt.length; i++) { + msg = msg + dt[i] + "
"; + } + msg = msg.replace(/[,\s]+$/, ""); + this.dialog.append("
" + + "Unsupported element.".translate() + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogUnsupported', DialogUnsupported); +}()); +(function () { + var DialogChangedVariables = function (appendTo, message) { + this.onAccept = new Function(); + this.message = message; + DialogChangedVariables.prototype.init.call(this, appendTo); + }; + DialogChangedVariables.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 200, + resizable: true, + close: function (event, ui) { + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, "warning"); + + this.message = this.message.replace(/[,\s]+$/, ""); + this.dialog.append("
" + + "The imported dynaform include new variables and existing variables that require changes.".translate() + " " + + "The changed variables have been added with the suffix “_1”.".translate() + " " + + "Please take note of the changes to update your process logic.".translate() + " " + + "The following variables have been created:
".translate() + this.message + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogChangedVariables', DialogChangedVariables); +}()); +(function () { + var DialogCreateVariable = function (appendTo, type, options, var_name) { + this.onSave = new Function(); + this.onSelect = new Function(); + this.onClose = new Function(); + this.appendTo = appendTo; + this.type = type; + this.options = options; + this.var_name = var_name; + DialogCreateVariable.prototype.init.call(this); + }; + DialogCreateVariable.prototype.init = function () { + var that = this; + this.var_dbconnection = "workflow"; + this.var_sql = ""; + this.var_accepted_values = that.options; + this.inp_doc_uid = ""; + + this.add = $("" + "Variables".translate() + ""); + this.add.on("click", function () { + that.dialog.dialog("close"); + var pmvariables = new PMVariables(); + pmvariables.onWindowClose = function (variable) { + if (variable !== null && variable.var_name_old === that.var_name) { + that.onSave(variable); + } + }; + pmvariables.load(); + return false; + }); + + this.buttonSave = $("" + "Save".translate() + ""); + this.buttonSave.on("click", function () { + that.save(); + return false; + }); + this.cancel = $("" + "Cancel".translate() + ""); + this.cancel.on("click", function () { + that.dialog.dialog("close").remove(); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.buttonSave); + + this.optionSelect = $( + "
" + + " " + + " " + + "
"); + this.optionSelect.find("#optionCreate").on("click", function () { + that.buttonSave.show(); + that.content.show(); + that.selectVariable.dialog.hide(); + that.dialog.css({height: heightCreate}); + }); + this.optionSelect.find("#optionSelect").on("click", function () { + that.buttonSave.hide(); + that.content.hide(); + that.selectVariable.dialog.show(); + that.selectVariable.load(); + that.dialog.css({height: 452}); + }); + + this.selectVariable = new FormDesigner.main.DialogVariable(null, this.type); + this.selectVariable.onClick = function (variable) { + that.onSelect(variable); + }; + this.selectVariable.dialog.dialog("destroy"); + this.selectVariable.dialog.hide(); + + this.content = $( + "
" + + "
" + + " " + + "
" + + "
" + + " " + "Settings".translate() + "" + + "
" + + "
" + + " " + + " " + + " " + + " " + + " " + + "
" + + "
" + ); + + this.content.find("#settings").css({display: "none"}); + + var show = true; + var heightCreate = 180; + this.content.find("#buttonSettings").on("click", function () { + if (show) { + heightCreate = 260; + that.dialog.css({height: heightCreate}); + that.content.find("#settings").css({display: "block"}); + show = false; + } else { + heightCreate = 165; + that.dialog.css({height: heightCreate}); + that.content.find("#settings").css({display: "none"}); + show = true; + } + return false; + }); + + var a; + this.content.find("#buttonDbConnection").on("click", function () { + a = new FormDesigner.main.DialogDBConnection(null); + a.onClick = function (option) { + a.dialog.dialog("close").remove(); + that.var_dbconnection = option.value; + that.content.find("#buttonDbConnection").text(option.label); + }; + return false; + }); + this.content.find("#buttonSql").on("click", function () { + a = new FormDesigner.main.DialogSql(null); + a.onSave = function () { + that.var_sql = a.editor.getValue(); + that.content.find("#buttonSql").text(a.editor.getValue()); + }; + a.editor.setValue(that.var_sql); + return false; + }); + this.content.find("#buttonOptions").on("click", function () { + a = new FormDesigner.main.DialogOptions(null, that.var_accepted_values); + a.onApply = function () { + that.var_accepted_values = a.getOptions(); + that.content.find("#buttonOptions").text(JSON.stringify(a.getOptions())); + }; + if (that.content.find("#var_field_type").val() === "boolean") { + a.setOptionsBoolean(); + } + return false; + }); + this.content.find("#buttonInputDocument").on("click", function () { + a = new FormDesigner.main.DialogInputDocument(null); + a.onClick = function (option) { + a.dialog.dialog("close").remove(); + that.inp_doc_uid = option.value; + that.content.find("#buttonInputDocument").text(option.label); + }; + return false; + }); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: this.appendTo ? this.appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 195, + resizable: false, + position: ["center", 50], + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + this.dialog.append(this.optionSelect); + this.dialog.append(this.content); + this.dialog.append(this.selectVariable.dialog); + this.dialog.append(this.buttons); + this.dialog.append(this.add); + FormDesigner.main.DialogStyle(this.dialog); + + $.validkeys(that.content.find("#var_name")[0], ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + that.content.find("#var_name").focus(); + + //data + that.content.find("#var_field_type").on("change", function () { + that.setFieldsVisibility(this.value); + }); + var types = [{ + value: "string", label: "String" + }, { + value: "integer", label: "Integer" + }, { + value: "float", label: "Float" + }, { + value: "boolean", label: "Boolean" + }, { + value: "datetime", label: "Datetime" + }, { + value: "grid", label: "Grid" + }, { + value: "array", label: "Array" + }, { + value: "file", label: "File" + }, { + value: "multiplefile", label: "Multiple File" + } + ]; + that.content.find("#var_field_type").empty(); + for (var i = 0; i < types.length; i++) { + $.validDataTypeAndControlType(types[i].value, that.type, function () { + that.addItem(types[i]); + }); + } + that.setFieldsVisibility(that.content.find("#var_field_type").val()); + }; + DialogCreateVariable.prototype.save = function () { + var that = this; + if (!that.isValid()) { + var a = new FormDesigner.main.DialogMessage(null, "alert", "A valid variable starts with a letter or underscore, followed by any number of letters, numbers, or underscores.".translate()); + a.onClose = function () { + }; + a.onAccept = function () { + }; + return false; + } + if (!that.isValidInputDocument()) { + var a = new FormDesigner.main.DialogMessage(null, "alert", "The input document is required, please select the value.".translate()); + a.onClose = function () { + }; + a.onAccept = function () { + }; + return false; + } + $.ajax({ + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id + "/process-variable", + data: JSON.stringify({ + var_name: that.content.find("#var_name").val(), + var_field_type: that.content.find("#var_field_type").val(), + var_dbconnection: that.var_dbconnection, + var_sql: that.var_sql, + var_label: that.content.find("#var_field_type").val(), + var_default: "", + var_accepted_values: that.var_accepted_values, + var_field_size: 10, + inp_doc_uid: that.inp_doc_uid + }), + method: "POST", + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + PMDesigner.project.keys.access_token); + }, + success: function (variable) { + that.dialog.dialog("close").remove(); + that.onSave(variable); + }, + error: function (responses) { + var msg; + try { + msg = JSON.parse(responses.responseText).error.message; + } catch (e) { + msg = "Error"; + } + var a = new FormDesigner.main.DialogMessage(null, "alert", msg); + a.onClose = function () { + }; + a.onAccept = function () { + }; + } + }); + }; + DialogCreateVariable.prototype.isValid = function () { + return /^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/.test(this.content.find("#var_name").val()); + }; + DialogCreateVariable.prototype.isValidInputDocument = function () { + if (this.content.find("#var_field_type").val() === "file" || this.content.find("#var_field_type").val() === "multipleFile") { + return this.inp_doc_uid !== ""; + } + return true; + }; + DialogCreateVariable.prototype.setVarName = function (var_name) { + this.content.find("#var_name").val(var_name); + }; + DialogCreateVariable.prototype.addItem = function (type) { + var that = this; + that.content.find("#var_field_type").append(""); + }; + DialogCreateVariable.prototype.setFieldsVisibility = function (type) { + var that = this; + that.content.find("#var_dbconnection").show(); + that.content.find("#var_sql").show(); + that.content.find("#var_accepted_values").show(); + that.content.find("#inp_doc_uid").hide(); + if (type === "boolean") { + that.content.find("#var_dbconnection").hide(); + that.content.find("#var_sql").hide(); + that.var_accepted_values = [{value: "1", label: "true"}, {value: "0", label: "false"}]; + that.content.find("#buttonOptions").text(JSON.stringify(that.var_accepted_values)); + } + if (type === "datetime" || type === "grid" || type === "file" || type === "multiplefile") { + that.content.find("#var_dbconnection").hide(); + that.content.find("#var_sql").hide(); + that.content.find("#var_accepted_values").hide(); + } + if (type === "file") { + that.content.find("#inp_doc_uid").show(); + } + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogCreateVariable', DialogCreateVariable); +}()); +(function () { + var DialogMessage = function (appendTo, type, message) { + this.type = type; + this.message = message; + this.onAccept = new Function(); + this.onClose = new Function(); + DialogMessage.prototype.init.call(this, appendTo); + }; + DialogMessage.prototype.init = function (appendTo) { + var that = this, + title; + this.accept = $("" + "Ok".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.accept); + + title = that.type === "success"? "Information" : "Errors"; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.onClose(); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, this.type); + + this.dialog.append("
" + + this.message + + "
"); + this.dialog.append(this.buttons); + this.accept.focus(); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogMessage', DialogMessage); +}()); + +(function () { + var DialogConfirm = function (appendTo, type, message) { + this.type = type; + this.message = message; + this.onAccept = new Function(); + this.onCancel = new Function(); + this.onClose = new Function(); + DialogConfirm.prototype.init.call(this, appendTo); + }; + DialogConfirm.prototype.init = function (appendTo) { + var that = this; + this.accept = $("" + "Yes".translate() + ""); + this.accept.on("click", function () { + that.onAccept(); + that.dialog.dialog("close"); + return false; + }); + this.cancel = $("" + "No".translate() + ""); + this.cancel.on("click", function () { + that.onCancel(); + that.dialog.dialog("close"); + return false; + }); + this.buttons = $("
"); + this.buttons.find("div:nth-child(1)").append(this.cancel); + this.buttons.find("div:nth-child(1)").append(this.accept); + + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 470, + height: 170, + resizable: false, + close: function (event, ui) { + that.dialog.remove(); + that.onClose(); + } + }); + FormDesigner.main.DialogStyle(this.dialog, this.type); + + this.dialog.append("
" + + this.message + + "
"); + this.dialog.append(this.buttons); + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogConfirm', DialogConfirm); +}()); +(function () { + var DialogInputDocument = function (appendTo) { + this.onClose = new Function(); + this.onLoad = new Function(); + this.onClick = new Function(); + DialogInputDocument.prototype.init.call(this, appendTo); + }; + DialogInputDocument.prototype.init = function (appendTo) { + var that = this; + this.dialog = $("
"); + this.dialog.dialog({ + appendTo: appendTo ? appendTo : document.body, + modal: true, + autoOpen: true, + width: 500, + height: 400, + resizable: false, + close: function (event, ui) { + that.onClose(event, ui); + that.dialog.remove(); + } + }); + FormDesigner.main.DialogStyle(this.dialog); + + this.search = $("

" + "Search".translate() + " :

"); + this.search.find(">input").on("keyup", function () { + var input = this; + that.body.find(">div").each(function (i, e) { + var sw = false; + $(e).find(">div").each(function (i, e) { + sw = sw || $(e).text().toLowerCase().indexOf(input.value.toLowerCase()) > -1; + }); + if (sw) + $(e).show(); + else + $(e).hide(); + }); + }); + this.search.find("img").on("click", function () { + that.load(); + }); + this.body = $("
"); + this.dialog.append(this.search); + this.dialog.append(this.body); + this.load(); + }; + DialogInputDocument.prototype.load = function () { + var that = this; + this.body.find(">div").remove(); + var restProxy = new PMRestClient({ + endpoint: "input-documents", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var resp; + for (var i = 0; i < response.length; i++) { + resp = response[i]; + resp["label"] = response[i].inp_doc_title; + resp["value"] = response[i].inp_doc_uid; + that.addItem(resp); + } + that.onLoad(response); + } + }); + restProxy.executeRestClient(); + }; + DialogInputDocument.prototype.addItem = function (variable) { + var that = this; + var item = $("
" + + "
" + variable.label + "
" + + "
"); + item.on("click", function () { + that.onClick(variable); + }); + this.body.append(item); + return item; + }; + FormDesigner.extendNamespace('FormDesigner.main.DialogInputDocument', DialogInputDocument); +}()); +(function () { + /** + * PopOver for PM Dynaform's designer. + * @param {Object} settings An object containing the config options for the new PopOver. + * @cfg {String|JQuery Object| Element} body The content for the PopOver, it casn be an HTML string, a JQuery Object + * or an Element. + * @cfg {String} [class=""] The class name for the popover, useful for applying custom styles through a css class. + * @cfg {String} [placement=PMPopOver.PLACEMENT.RIGHT] A string that determines the placement of the popover related + * to its target element. Please Use one of the keys defined under PMPopOver.PLACEMENT. + * + * @constructor + */ + var PMPopOver = function (settings) { + this._body = null; + this._targetElement = null; + this._dom = {}; + this._class = null; + this._placement = null; + this._visible = false; + + PMPopOver.prototype._init.call(this, settings); + }; + /** + * All the possible values for placement config option. + * @type {{TOP: string, RIGHT: string, BOTTOM: string, LEFT: string}} + */ + PMPopOver.PLACEMENT = { + TOP: 'top', + RIGHT: 'right', + BOTTOM: 'bottom', + LEFT: 'left' + }; + /** + * Initialize the class + * @param settings + * @private + */ + PMPopOver.prototype._init = function (settings) { + settings = $.extend({ + body: "", + class: "", + placement: PMPopOver.PLACEMENT.RIGHT + }, settings); + + this._placement = settings.placement; + this._class = settings.class; + + this.setBody(settings.body) + .setTargetElement(settings.targetElement); + }; + /** + * Sets the element the PopOver belongs to. + * @param targetElement + * @chainable + */ + PMPopOver.prototype.setTargetElement = function (targetElement) { + if (!targetElement) { + throw new Error('setTargetElement(): Invalid parameter.'); + } + + this._clickHandler = this._clickHandler || this.toggleVisible.bind(this); + + if (this._targetElement) { + $(this._targetElement).off("click", this._clickHandler); + } + + this._targetElement = targetElement; + + $(this._targetElement).on("click", this._clickHandler); + + return this; + }; + /** + * Sets the PopOver body. + * @param body + * @chainable + */ + PMPopOver.prototype.setBody = function (body) { + if (!(body instanceof Element || body instanceof jQuery || typeof body === 'string')) { + throw new Error("setBody(): The parameter must be a DOM Element, jQuery element or a string."); + } + + this._body = body; + + if (this._dom.content) { + $(this._dom.content).empty().append(body); + } + + return this; + }; + /** + * Returns the position of the PopOver target element. + * @returns {Object} + * @private + */ + PMPopOver.prototype._getTargetPosition = function () { + var $element = this._targetElement instanceof jQuery ? this._targetElement : $(this._targetElement), + element = this._targetElement instanceof jQuery ? this._targetElement.get(0) : this._targetElement; + + return $.extend(element.getBoundingClientRect ? element.getBoundingClientRect() : { + width: element.offsetWidth, + height: element.offsetHeight + }, $element.offset()); + }; + /** + * Returns the final position for the popover. + * @returns {{top: *, left: *}} + * @private + */ + PMPopOver.prototype._getPosition = function () { + var targetPosition = this._getTargetPosition(), + arrowOffset = 10, + html = this.getHTML(), + htmlWidth, + htmlHeight, + placement, + top, + left; + + document.body.appendChild(html); + html.style.display = 'block'; + + htmlWidth = html.offsetWidth; + htmlHeight = html.offsetHeight; + placement = this._placement; + + switch (placement) { + case PMPopOver.PLACEMENT.TOP: + top = targetPosition.top - htmlHeight - arrowOffset; + left = targetPosition.left + (targetPosition.width / 2) - (htmlWidth / 2); + break; + case PMPopOver.PLACEMENT.RIGHT: + top = targetPosition.top + (targetPosition.height / 2) - (htmlHeight / 2); + left = targetPosition.left + targetPosition.width + arrowOffset; + break; + case PMPopOver.PLACEMENT.BOTTOM: + top = targetPosition.top + targetPosition.height + arrowOffset; + left = targetPosition.left + (targetPosition.width / 2) - (htmlWidth / 2); + break; + case PMPopOver.PLACEMENT.LEFT: + top = targetPosition.top + (targetPosition.height / 2) - (htmlHeight / 2); + left = targetPosition.left - htmlWidth - arrowOffset; + break; + default: + throw new Error('_getPosition(): Invalid placement parameter.'); + } + + return { + top: top, + left: left + }; + }; + /** + * Displays the PopOver. + * @chainable + * @return {body} + */ + PMPopOver.prototype.show = function () { + var position = this._getPosition(); + + $(this._html).removeClass("top right bottom left").addClass(this._placement).addClass("in"); + this._html.style.top = position.top + 'px'; + this._html.style.left = position.left + 'px'; + + this._visible = true; + + return this; + }; + /** + * Hides the PopOver. + * @chainable + * @return {body} + */ + PMPopOver.prototype.hide = function () { + if (this._html) { + $(this._html).fadeOut(150, "linear", function () { + this.style.display = 'none'; + $(this).removeClass('in'); + }); + } + + this._visible = false; + + return this; + }; + /** + * Toggles the PopOver visibility. + * @chainable + */ + PMPopOver.prototype.toggleVisible = function () { + return this._visible ? this.hide() : this.show(); + }; + /** + * Creates the PopOver HTML. + * @chainable + * @return {body} + * @private + */ + PMPopOver.prototype._createHTML = function () { + var container, + arrow, + content; + + if (this._html) { + return this; + } + + container = document.createElement('div'); + arrow = document.createElement('div'); + content = document.createElement('div'); + + container.className = "mafe-popover fade " + this._class; + arrow.className = "arrow"; + content.className = "mafe-popover-content"; + + container.appendChild(arrow); + container.appendChild(content); + + this._dom.container = container; + this._dom.arrow = arrow; + this._dom.content = content; + + this._html = container; + + this.setBody(this._body); + + this._html.addEventListener("mousedown", function (e) { + e.stopPropagation(); + }); + + document.addEventListener("mousedown", this.hide.bind(this), false); + + return this; + }; + /** + * Returns the PopOver HTML. + * @returns {Element} + */ + PMPopOver.prototype.getHTML = function () { + if (!this._html) { + this._createHTML(); + } + + return this._html; + }; + + FormDesigner.extendNamespace('FormDesigner.main.PMPopOver', PMPopOver); +})(); + +/** + * @class ItemRule + * @param object + * @constructor + */ +var ItemRule = function (object) { + /** + * Code of the Rule + * @type {String} + */ + this.code = null; + /** + * Type Shape + * @type {String} + */ + this.type = null; + /** + * Category of the Rule (BPMN | ENGINE) + * @type {String} + */ + this.category = null; + /** + * Type of alert (Error | Warning) + * @type {String} + */ + this.severity = null; + /** + * Description rule + * @type {String} + */ + this.description = null; + /** + * Criteria of validation + * @type {Function} + */ + this.criteria = null; + + this.init(object); +}; +/** + * Inicialize ItemRules. + * @param object + */ +ItemRule.prototype.init = function (object) { + if (typeof object === "object") { + this.setCode(object.code); + this.setTypeElement(object.type); + this.setCategory("BPMN"); + this.setSeverity(object.severity); + this.setDescription(object.description); + this.setCriteria(object.criteria); + } +}; +/** + * Get code rule + * @returns {String} + */ +ItemRule.prototype.getCode = function () { + return this.code; +}; +/** + * Get type rule + * @returns {String} + */ +ItemRule.prototype.getTypeElement = function () { + return this.type; +}; +/** + * Get category + * @returns {String} + */ +ItemRule.prototype.getCategory = function () { + return this.category; +}; +/** + * Get severity + * @returns {String} + */ +ItemRule.prototype.getSeverity = function () { + return this.severity; +}; +/** + * Get description + * @returns {String} + */ +ItemRule.prototype.getDescription = function () { + return this.description; +}; +/** + * Get criteria + * @returns {function} + */ +ItemRule.prototype.getCriteria = function () { + return this.criteria; +}; +/** + * Validate code + * @param codeRule {String} + * @returns {Boolean} + */ +ItemRule.prototype.isCodeRule = function (codeRule) { + var isCode = false; + if (codeRule === this.code) { + isCode = true; + } + return isCode; +}; +/** + * Set code + * @param code + * @returns {ItemRule} + */ +ItemRule.prototype.setCode = function (code) { + if (code && typeof code === "string") { + this.code = code; + } + return this; +}; +/** + * Set type element + * @param typeElement {String} + * @returns {ItemRule} + */ +ItemRule.prototype.setTypeElement = function (typeElement) { + if (typeElement && typeof typeElement === "string") { + this.type = typeElement; + } + return this; +}; +/** + * Set type element + * @param typeElement {String} + * @returns {ItemRule} + */ +ItemRule.prototype.setCategory = function (category) { + if (category && typeof category === "string") { + this.category = category; + } + return this; +}; +/** + * Set severity + * @param severity {String} + * @returns {ItemRule} + */ +ItemRule.prototype.setSeverity = function (severity) { + if (severity && typeof severity === "string") { + this.severity = severity; + } + return this; +}; +/** + * Set description + * @param description {String} + * @returns {ItemRule} + */ +ItemRule.prototype.setDescription = function (description) { + if (description && typeof description === "string") { + this.description = description; + } + return this; +}; +/** + * Set criteria + * @param criteria {Function} + * @returns {ItemRule} + */ +ItemRule.prototype.setCriteria = function (criteria) { + if (criteria && typeof criteria === "function") { + this.criteria = criteria; + } + return this; +}; +/** + * @class CollectionRules + * @param collectionRules + * @constructor + */ +var CollectionRules = function (collectionRules) { + /** + * Type Shape + * @type {String} + */ + this.typeShape = null; + /** + * Array of Rules + * @type {Rules} + */ + this.rules = new PMUI.util.ArrayList(); + this.init(collectionRules); +}; +/** + * Inicialize CollectionRules + * @param collectionRules + */ +CollectionRules.prototype.init = function (collectionRules) { + if (typeof collectionRules === "object") { + this.setTypeShape(collectionRules.typeShape); + this.loadRules(collectionRules.rules); + } +}; +/** + * Get type shape + * @returns {String} + */ +CollectionRules.prototype.getTypeShape = function () { + return this.typeShape; +}; +/** + * Validate type shape + * @param typeShape + * @returns {Boolean} + */ +CollectionRules.prototype.isTypeShape = function (typeShape) { + var isType = false; + if (typeShape === this.getTypeShape()) { + isType = true; + } + return isType; +}; +/** + * Get Array Rules + * @returns {Array Rules} + */ +CollectionRules.prototype.getRules = function () { + return this.rules; +}; +/** + * Get Item Rule + * @returns {ItemRule} + */ +CollectionRules.prototype.getItemRule = function (codeRule) { + var itemRule, + itemsRules; + if (codeRule) { + itemsRules = this.getRules(); + itemRule = itemsRules.find("code", codeRule); + } + return itemRule; +}; +/** + * Set type shape + * @param typeShape + * @returns {CollectionRules} + */ +CollectionRules.prototype.setTypeShape = function (typeShape) { + this.typeShape = (typeShape && typeof typeShape === "string") ? typeShape : this.typeShape; + return this; +}; +/** + * Set array rules + * @param arrRules + * @returns {CollectionRules} + */ +CollectionRules.prototype.setRules = function (arrRules) { + if (arrRules && Array.isArray(arrRules)) { + this.rules = arrRules; + } + return this; +}; +/** + * Load rules array + * @param arrRules + * @returns {CollectionRules} + */ +CollectionRules.prototype.loadRules = function (arrRules) { + var itemRule, + i, + max; + if (arrRules && Array.isArray(arrRules) && arrRules.length > 0) { + max = arrRules.length; + for (i = 0; i < max; i += 1) { + itemRule = new ItemRule(arrRules[i]); + this.rules.insert(itemRule); + } + } + return this; +}; +/** + * Add new ItemRule object + * @param itemRule {Object} + */ +CollectionRules.prototype.addItemRule = function (itemRule) { + if (itemRule && typeof itemRule === "object") { + this.rules.insert(itemRule); + } + return this; +}; +/** + * Remove ItemRule object + * @param itemRule + * @returns {CollectionRules} + */ +CollectionRules.prototype.removeItemRule = function (itemRule) { + if (itemRule && typeof itemRule === "object") { + this.rules.remove(itemRule); + } + return this; +}; +/** + * @class ModelRules + * @param object + * @constructor + */ +var ModelRules = function (object, status) { + /** + * Status Rules + * @type {Boolean} + */ + this.enable = true; + /** + * Items collection + * @type {PMUI.util.ArrayList} + */ + this.itemsCollection = new PMUI.util.ArrayList(); + this.init(object, status); +}; +/** + * Inicialize Model Rules + * @param object + */ +ModelRules.prototype.init = function (object, status) { + var prop; + this.setStatus(status); + if (object && typeof object === "object") { + for (prop in object) { + this.enable + this.loadCollection(prop, object[prop]); + } + } +}; +/** + * Load Collection Rules + * @param type + * @param arrRules + * @returns {ModelRules} + */ +ModelRules.prototype.loadCollection = function (type, arrRules) { + var collectionObject; + if (type && arrRules) { + if (typeof type === "string" && Array.isArray(arrRules)) { + collectionObject = new CollectionRules({ + 'typeShape': type, + 'rules': arrRules + }); + this.itemsCollection.insert(collectionObject); + } + } + return this; +}; +/** + * Get the status of the enable property (true | false) + * @returns {Boolean} + */ +ModelRules.prototype.getStatus = function () { + return this.enable; +}; +/** + * Get Items Collection Arralist + * @returns {PMUI.util.ArrayList} + */ +ModelRules.prototype.getItemsCollection = function () { + return this.itemsCollection; +}; +/** + * Set the status of the enable property + * @param status + * @returns {ModelRules} + */ +ModelRules.prototype.setStatus = function (status) { + this.enable = (typeof status === "boolean") ? status : this.enable; + return this; +}; + +/** + * Get Collection Rules for type Bpmn Element + * Example: + * PMDesigner.modelRules.getCollectionType('bpmnActivity'); + * @param type {String} + * @returns CollectionRules {PMUI.util.ArrayList} + */ +ModelRules.prototype.getCollectionType = function (type) { + var collection, + i, + itemCollection, + max; + if (type && typeof type === "string") { + max = this.itemsCollection.getSize(); + for (i = 0; i < max; i += 1) { + itemCollection = this.itemsCollection.get(i); + if (itemCollection.isTypeShape(type)) { + collection = itemCollection.getRules(); + break; + } + } + } + return collection; +}; +/** + * Add Item Rule + * Example: + * PMDesigner.modelRules.addItemRuleToCollection('bpmnActivity', { + * code: '123456', + * description: 'This is a Message of Error'.translate(), + * type: 'bpmnActivity', + * severity: 'Warning', {'Warning | Error'} + * criteria: function (shape, error) { + * //Validation Rule +* shape.addErrorLog(error); + * } + * }); + * @param type {String} + * @param item {Object} + * @returns {ModelRules} + */ +ModelRules.prototype.addItemRuleToCollection = function (type, item) { + var itemCollection, + itemRule, + max, + index = 0; + if (type && item) { + max = this.itemsCollection.getSize(); + while (index < max) { + itemCollection = this.itemsCollection.get(index); + if (itemCollection.isTypeShape(type)) { + itemRule = new ItemRule(item); + itemCollection.addItemRule(itemRule); + index = max; + } + index += 1; + } + } + return this; +}; +/** + * Remove Item Rule + * Example: + * PMDesigner.modelRules.removeItemRuleFromCollection('123465'); + * @param code {String} + * @returns {ModelRules} + */ +ModelRules.prototype.removeItemRuleFromCollection = function (code) { + var itemCollection, + itemRule, + max, + index = 0; + if (code && typeof code === "string") { + max = this.itemsCollection.getSize(); + while (index < max) { + itemCollection = this.itemsCollection.get(index); + itemRule = itemCollection.getItemRule(code); + if (itemRule) { + itemCollection.removeItemRule(itemRule); + index = max; + } + index += 1; + } + } + return this; +}; +/** + * Add Collection Rules + * Example: + * PMDesigner.modelRules.addItemRuleToCollection('bpmnActivity' + * [ + * {Object ItemRule}, + * {Object ItemRule}, + * {Object ItemRule} + * ] + * ); + * @param typeShape {String} + * @param collectionRules {Array} + * @returns {ModelRules} + */ +ModelRules.prototype.addCollectionRules = function (typeShape, arrayRules) { + var max, + i; + if (type && arrayRules && Array.isArray(arrayRules)) { + max = arrayRules.length; + for (i = 0; i < max; i += 1) { + this.addItemRuleToCollection(typeShape, arrayRules[i]); + } + } + return this; +}; + + +/** + * Crown Class + * @param options + * @constructor + */ +var Corona = function (options) { + /** + * Call Shape Contructor + */ + PMUI.draw.Shape.call(this, options); + /** + * Define parent crown + * @type {shape} + */ + this.parent = null; + /** + * Define Type Especific of the parent + * @type {null} + */ + this.parentType = null; + /** + * Define number rows + * @type {number} + */ + this.rows = 1; + /** + * Define number cols + * @type {number} + */ + this.cols = 1; + /** + * Define Items of the Crown + * @type {PMUI.util.ArrayList} + */ + this.itemsCrown = new PMUI.util.ArrayList(); + /** + * Event OnMouseOut + * @type {null} + */ + this.eventOnMouseOut = null; + this.init(options); +}; +/** + * Define New Object Shape + * @type {PMUI.draw.Shape} + */ +Corona.prototype = new PMUI.draw.Shape(); +/** + * Defines the object type + * @type {String} + */ +Corona.prototype.type = 'Crown'; +/** + * Inicializate Crown + * @param options + * @returns {Crown} + */ +Corona.prototype.init = function (options) { + var config; + if (typeof options === "object" && !jQuery.isEmptyObject(options)) { + this.setParent(options.parent); + this.setParentType(options.parentType); + config = this.getConfigItems(options.parentType); + if (config) { + this.populateItemsCrown(config); + this.setRows(config.rows); + this.setCols(config.cols); + } + } + return this; +}; +/** + * Get Parent Crown + * @returns {shape|PMUI.draw.Shape|*} + */ +Corona.prototype.getParent = function () { + return this.parent; +}; +/** + * Get Parent Type + * @returns {null|string|*} + */ +Corona.prototype.getParentType = function () { + return this.parentType; +}; +/** + * Get Rows + * @returns {number} + */ +Corona.prototype.getRows = function () { + return this.rows; +}; +/** + * Get Cols + * @returns {number} + */ +Corona.prototype.getCols = function () { + return this.cols; +}; +/** + * Get Items Crown + * @returns {PMUI.util.ArrayList|*} + */ +Corona.prototype.getItemsCrown = function () { + return this.itemsCrown; +}; +/** + * Set Parent Crown + * @param parent + * @returns {Corona} + */ +Corona.prototype.setParent = function (parent) { + if (typeof parent === "object" && !jQuery.isEmptyObject(parent)) { + this.parent = parent; + } + return this; +}; +/** + * Set Parent Type + * @param parentType + * @returns {Corona} + */ +Corona.prototype.setParentType = function (parentType) { + if (parentType && typeof parentType === "string") { + this.parentType = parentType; + } + return this; +}; +/** + * Set Number Rows + * @param rows + * @returns {Crown} + */ +Corona.prototype.setRows = function (rows) { + if (rows && rows > 0) { + this.rows = rows; + } + return this; +}; +/** + * Set Number Cols + * @param cols + * @returns {Crown} + */ +Corona.prototype.setCols = function (cols) { + if (cols && cols > 0) { + this.cols = cols; + } + return this; +}; +/** + * Resize crown + * @returns {Corona} + */ +Corona.prototype.adjustSize = function () { + var width, + height, + itemFirst, + margin = 4; + itemFirst = this.getItemsCrown().get(0); + width = (itemFirst.getWidth() + margin) * this.getCols(); + height = (itemFirst.getHeight() + margin) * this.getRows(); + if (this.html) { + this.html.style.width = width + "px"; + this.html.style.height = height + 'px'; + this.updatePosition(); + } + return this; +}; +/** + * Changes position + * @returns {Corona} + */ +Corona.prototype.updatePosition = function () { + jQuery(this.html).position({ + of: jQuery(this.parent.html), + my: "left top", + at: "right top", + collision: 'none' + }); + return this; +}; +/** + * Get config Items Crown + * @param especificType + * @returns {*} + */ +Corona.prototype.getConfigItems = function (especificType) { + var configDefault = PMDesigner.configCrown, + typeShape = this.getParent().getType(), + configCrown = configDefault[typeShape][especificType]; + return configCrown; +}; +/** + * Populate Crown from previous configuration + * @param config + * @returns {Corona} + */ +Corona.prototype.populateItemsCrown = function (config) { + var order = (config && config.order) || [], + itemsDefault = PMDesigner.modelCrown.getItemsDefault(), + itemCrownDefault, + itemCrown, + max, + i; + if (order && Array.isArray(order) && order.length > 0) { + max = order.length; + for (i = 0; i < max; i += 1) { + itemCrownDefault = itemsDefault.find("id", order[i]); + itemCrownDefault.parent = this; + itemCrownDefault.canvas = this.canvas; + itemCrown = new ItemCrown(itemCrownDefault); + this.itemsCrown.insert(itemCrown); + } + } + return this; +}; +Corona.prototype.isCreatedItems = function () { + var isCreated = false; + if (this.countChildrens() === this.getItemsCrown().getSize()) { + isCreated = true; + } + return isCreated +}; +/** + * Paint Crown + * @returns {Corona} + */ +Corona.prototype.paint = function () { + if (!this.html) { + this.createHTML(); + } + return this; +}; +/** + * Create HTML + * @returns {Corona} + */ +Corona.prototype.createHTML = function () { + var htmlParent = this.getCanvas().html, + htmlCrown, + htmlRow, + itemCrown, + itemsAux = this.getItemsCrown().asArray(), + cont = 0, + i; + this.html = null; + htmlCrown = this.createHtmlCrown(); + while (itemsAux.length > 0) { + if (this.getRows() > cont) { + htmlRow = this.createHtmlRow(cont); + for (i = 0; i < this.getCols(); i += 1) { + if (itemsAux.length > 0) { + itemCrown = itemsAux.shift(); + itemCrown = itemCrown.createHtmlItem(); + itemCrown = itemCrown.attachListeners(); + htmlRow.appendChild(itemCrown.html); + } else { + break; + } + } + htmlCrown.appendChild(htmlRow); + cont += 1; + } + } + htmlParent.appendChild(htmlCrown); + this.html = htmlCrown; + this.adjustSize(); + return this; +}; +/** + * Create Html Crown + * @returns {*} + */ +Corona.prototype.createHtmlCrown = function () { + var htmlCrown = null, + classCrown = "crown-container"; + PMUI.draw.Shape.prototype.createHTML.call(this); + htmlCrown = this.html; + if (htmlCrown) { + htmlCrown.className = classCrown; + } + return htmlCrown; +}; +/** + * Create Html Row + * @param index + * @returns {HTMLElement|*} + */ +Corona.prototype.createHtmlRow = function (index) { + var htmlRow = null, + classRow = "row"; + htmlRow = PMUI.createHTMLElement("div"); + htmlRow.className = classRow + " " + classRow + "-" + index; + return htmlRow; +}; +/** + * Show Crown + * @returns {Corona} + */ +Corona.prototype.show = function () { + if (this.isDirtyParentType()) { + this.updateCrown(); + } + if (!this.html) { + this.createHTML(); + } else { + jQuery(this.html).show(); + this.updatePosition(); + this.setZOrder(this.getParent().getZOrder() + 1 || 1); + } + return this; +}; +/** + * Hide Crown + * @returns {Corona} + */ +Corona.prototype.hide = function () { + if (this && this.html) { + jQuery(this.html).hide(); + } + return this; +}; +/** + * Destroy Crown Content + * @returns {Corona} + */ +Corona.prototype.destroy = function () { + if (this && this.html) { + jQuery(this.html).empty(); + jQuery(this.html).remove(); + this.html = null; + } + this.getItemsCrown().clear(); + return this; +}; +/** + * Update Crown when the config changes + * @returns {Corona} + */ +Corona.prototype.updateCrown = function () { + var config, + especificType = this.getParent().getEspecificType(); + this.destroy(); + this.setParentType(especificType); + config = this.getConfigItems(especificType); + this.populateItemsCrown(config); + this.setRows(config.rows); + this.setCols(config.cols); + return this; +}; +/** + * Validate if the shape type change + * @returns {boolean} + */ +Corona.prototype.isDirtyParentType = function () { + var isDirty = false; + if (this.getParent().getType() !== "PMActivity" && this.getParentType() !== this.getParent().getEspecificType()) { + isDirty = true; + } + return isDirty; +}; + +/** + * Item Crown Class + * @param options + * @constructor + */ +var ItemCrown = function (options) { + /** + * Call Shape Constructor + */ + PMUI.draw.Shape.call(this, options); + /** + * Define Id ItemCrown + * @type {null} + */ + this.id = null; + /** + * Parent Item Crown + * @type {null} + */ + this.parent = null; + /** + * Name Item Crown + * @type {string} + */ + this.name = null; + /** + * Class Name Item Crown + * @type {string} + */ + this.className = null; + /** + * Width of the Item Crown + * @type {number} + */ + this.width = 22; + /** + * Height of the Item Crown + * @type {number} + */ + this.height = 22; + /** + * Event OnClick + * @type {null} + */ + this.eventOnClick = null; + /** + * Event OnMouseDown + * @type {null} + */ + this.eventOnMouseDown = null; + /** + * Event OnMouseUp + * @type {null} + */ + this.eventOnMouseUp = null; + /** + * Event OnMouseMove + * @type {null} + */ + this.eventOnMouseMove = null; + /** + * Event OnMouseOut + * @type {null} + */ + this.eventOnMouseOut = null; + this.init(options); +}; +/** + * Define new Object Shape + * @type {PMUI.draw.Shape} + */ +ItemCrown.prototype = new PMUI.draw.Shape(); +/** + * Defines the object type + * @type {String} + */ +ItemCrown.prototype.type = 'ItemCrown'; +/** + * Inicialize Item Crown + * @param options + * @returns {ItemCrown} + */ +ItemCrown.prototype.init = function (options) { + if (typeof options === "object") { + this.setId(options.id); + this.setParent(options.parent); + this.setName(options.name); + this.setClassName(options.className); + this.setEventOnClick(options.eventOnClick); + this.setEventOnMouseDown(options.eventOnMouseDown); + this.setEventOnMouseUp(options.eventOnMouseUp); + this.setEventOnMouseMove(options.eventOnMouseMove); + this.setEventOnMouseOut(options.eventOnMouseOut); + } + return this; +}; +/** + * Get Id Item Crown + * @returns {null} + */ +ItemCrown.prototype.getId = function () { + return this.id; +}; +/** + * Get parent Item Crown + * @returns {null} + */ +ItemCrown.prototype.getParent = function () { + return this.parent; +}; +/** + * Get Name + * @returns {null|string|*} + */ +ItemCrown.prototype.getName = function () { + return this.name; +}; +/** + * Get Class Name Style + * @returns {null|*} + */ +ItemCrown.prototype.getClassName = function () { + return this.className; +}; +/** + * Get Width + * @returns {number|*} + */ +ItemCrown.prototype.getWidth = function () { + return this.width; +}; +/** + * Get Height + * @returns {number|*} + */ +ItemCrown.prototype.getHeight = function () { + return this.height; +}; +/** + * Get Function EventOnclick + * @returns {null|*} + */ +ItemCrown.prototype.getEventOnClick = function () { + return this.eventOnClick; +}; +/** + * Get Function EventOnMouseDown + * @returns {null|*} + */ +ItemCrown.prototype.getEventOnMouseDown = function () { + return this.eventOnMouseDown; +}; +/** + * Set Id ItemCrown + * @param id + * @returns {ItemCrown} + */ +ItemCrown.prototype.setId = function (id) { + if (id && typeof id === "string") { + this.id = id; + } + return this; +}; +/** + * Set Parent ItemCrown + * @param parent + * @returns {ItemCrown} + */ +ItemCrown.prototype.setParent = function (parent) { + if (typeof parent === "object" && !jQuery.isEmptyObject(parent)) { + this.parent = parent; + } + return this; +}; +/** + * Set Name + * @param name + * @returns {ItemCrown} + */ +ItemCrown.prototype.setName = function (name) { + if (name && typeof name === "string") { + this.name = name; + } + return this; +}; +/** + * Set ClassName Style + * @param className + * @returns {ItemCrown} + */ +ItemCrown.prototype.setClassName = function (className) { + if (className && typeof className === "string") { + this.className = className + } + return this; +}; +/** + * Set Width + * @param width + * @returns {ItemCrown} + */ +ItemCrown.prototype.setWidth = function (width) { + if (width) { + this.width = width; + } + return this; +}; +/** + * Set Height + * @param height + * @returns {ItemCrown} + */ +ItemCrown.prototype.setHeight = function (height) { + if (height) { + this.height = height; + } + return this; +}; +/** + * Set Function EventOnClick + * @param func + * @returns {ItemCrown} + */ +ItemCrown.prototype.setEventOnClick = function (func) { + if (func && typeof func === "function") { + this.eventOnClick = func; + } + return this; +}; +/** + * Set Function EventOnMouseDown + * @param func + * @returns {ItemCrown} + */ +ItemCrown.prototype.setEventOnMouseDown = function (func) { + if (func && typeof func === "function") { + this.eventOnMouseDown = func; + } + return this; +}; +/** + * Set Function EventOnMouseUp + * @param func + * @returns {ItemCrown} + */ +ItemCrown.prototype.setEventOnMouseUp = function (func) { + if (func && typeof func === "function") { + this.eventOnMouseUp = func; + } + return this; +}; +/** + * Set Function EventOnMouseMove + * @param func + * @returns {ItemCrown} + */ +ItemCrown.prototype.setEventOnMouseMove = function (func) { + if (func && typeof func === "function") { + this.eventOnMouseMove = func; + } + return this; +}; +/** + * Set Function EventOnMouseOut + * @param func + * @returns {ItemCrown} + */ +ItemCrown.prototype.setEventOnMouseOut = function (func) { + if (func && typeof func === "function") { + this.eventOnMouseOut = func; + } + return this; +}; +/** + * Create HTML Item Crown + * @returns {*} + */ +ItemCrown.prototype.createHtmlItem = function () { + var htmlItemCrown, + classItemCrown = "item-crown", + positionDefault = 'relative'; + PMUI.draw.Shape.prototype.createHTML.call(this); + htmlItemCrown = this.html; + htmlItemCrown.className = this.getClassName() + " " + classItemCrown; + htmlItemCrown.title = this.getName(); + htmlItemCrown.style.position = positionDefault; + htmlItemCrown.style.width = this.getWidth() + "px"; + htmlItemCrown.style.height = this.getHeight() + "px"; + this.html = htmlItemCrown; + return this; +}; +/** + * Listeners + * @returns {ItemCrown} + */ +ItemCrown.prototype.attachListeners = function () { + var htmlItemCrown; + htmlItemCrown = this.html; + if (htmlItemCrown) { + jQuery(htmlItemCrown).click(this.onClick()); + jQuery(htmlItemCrown).mousedown(this.onMouseDown()); + jQuery(htmlItemCrown).mouseup(this.onMouseUp()); + jQuery(htmlItemCrown).mousemove(this.onMouseMove()); + jQuery(htmlItemCrown).mouseout(this.onMouseOut()); + } + this.html = htmlItemCrown; + return this; +}; +/** + * OnClick Event + * @returns {Function} + */ +ItemCrown.prototype.onClick = function () { + var that = this; + return function (e) { + e.stopPropagation(); + e.preventDefault(); + if (that.eventOnClick) { + that.eventOnClick(that); + } + }; +}; +/** + * OnMouseDown Event + * @returns {Function} + */ +ItemCrown.prototype.onMouseDown = function () { + var that = this; + return function (e) { + e.stopPropagation(); + e.preventDefault(); + if (that.eventOnMouseDown) { + that.eventOnMouseDown(that); + } + }; +}; +/** + * OnMouseUp Event + * @returns {Function} + */ +ItemCrown.prototype.onMouseUp = function () { + var that = this; + return function (e) { + e.stopPropagation(); + e.preventDefault(); + if (that.eventOnMouseUp) { + that.eventOnMouseUp(that); + } + }; +}; +/** + * OnMouseMove Event + * @returns {Function} + */ +ItemCrown.prototype.onMouseMove = function () { + var that = this; + return function (e) { + e.stopPropagation(); + e.preventDefault(); + if (that.eventOnMouseMove) { + that.eventOnMouseMove(that); + } + }; +}; +/** + * OnMouseOut Event + * @returns {Function} + */ +ItemCrown.prototype.onMouseOut = function () { + var that = this; + return function (e) { + e.stopPropagation(); + e.preventDefault(); + if (that.eventOnMouseOut) { + that.eventOnMouseOut(that); + } + }; +}; + +/** + * Class ModelCrown + * @param options + * @constructor + */ +var ModelCrown = function (options) { + this.itemsDefault = PMUI.util.ArrayList(); + this.init(options); +}; +/** + * Initialize ModelCrown + * @param options + */ +ModelCrown.prototype.init = function (options) { + if (typeof options === "object" && Object.keys(options).length > 0) { + this.setItemsDefault(options.items); + } + return this; +}; +/** + * Get Items ModelCrown + * @returns {*|Array} + */ +ModelCrown.prototype.getItemsDefault = function () { + return this.itemsDefault; +}; +/** + * Set Items ModelCrown + * @param items {Array of the Objects} + * @returns {ModelCrown} + */ +ModelCrown.prototype.setItemsDefault = function (items) { + var itemCrown, + max, + i; + if (items && Array.isArray(items) && items.length > 0) { + max = items.length; + for (i = 0; i < max; i += 1) { + this.itemsDefault.insert(items[i]); + } + } + return this; +}; +/** + * Add New Item Crown + * Example: + * PMDesigner.modelCrown.addItemToCrown({ + * id: "example-id", + * name: "exmaple-name".translate(), + * className: "name-class-css", + * eventOnClick: function(item) { + * --Your code goes here + * }, + * eventOnMouseDown: function(item) { + * --Your code goes here + * } + * }); + * + * @param itemObject {Object} + * @returns {ModelCrown} + */ +ModelCrown.prototype.addItemToCrown = function (itemObject) { + if (typeof itemObject === "object" && Object.keys(itemObject).length > 0) { + this.itemsDefault.insert(itemObject); + } + return this; +}; +/** + * Remove ItemCrown + * Example: + * PMDesigner.modelCrown.removeItemFromCrown(idItem); + * + * @param idItem {string} + * @returns {ModelCrown} + */ +ModelCrown.prototype.removeItemFromCrown = function (idItem) { + var itemCrown; + if (idItem && typeof idItem === "string") { + itemCrown = this.itemsDefault.find("id", idItem); + if (itemCrown) { + this.itemsDefault.remove(itemCrown); + } + } + return this; +}; +var __env = __env || {};__env.USER_GUEST = {"uid":"00000000000000000000000000000002","firstname":"Guest","lastname":"Guest","username":"guest"}; __env.pmVariable = {"regEx":"/^[a-zA-Z\\_]{1}\\w+$/"}; + +var defaultCrown = { + items: [ + { + id: "task", + name: "Task".translate(), + className: "mafe-corona-task", + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'TASK'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-task'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "gateway", + name: 'Gateway'.translate(), + className: 'mafe-corona-gateway-exclusive', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'EXCLUSIVE'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-gateway-exclusive'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "intermediate", + name: 'Intermediate'.translate(), + className: 'mafe-corona-intermediate', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'INTERMEDIATE_EMAIL'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-intermediate-send-mesage'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "end", + name: 'End'.translate(), + className: 'mafe-corona-end', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'END'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-end'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "flow", + name: 'Flow'.translate(), + className: 'mafe-corona-flow', + eventOnClick: function (item) { + item.parent.hide(); + item.parent.parent.canvas.hideAllFocusedLabels(); + }, + eventOnMouseDown: function (item) { + item.canvas.canConnect = true; + item.canvas.connectStartShape = item.parent.parent; + } + }, + { + id: "properties", + name: 'Properties'.translate(), + className: 'mafe-corona-settings', + eventOnClick: function (item) { + item.parent.hide(); + PMDesigner.saveAndOpenSettings(item.parent.parent, PMDesigner.shapeProperties); + } + }, + { + id: "delete", + name: 'Delete'.translate(), + className: 'mafe-corona-delete', + eventOnClick: function (item) { + PMUI.getActiveCanvas().removeElements(); + item.parent.hide(); + } + } + ] +}; + +var configCrown = { + 'PMActivity': { + 'DEFAULT': { + order: ["task", "gateway", "intermediate", "end", "flow", "properties", "delete"], + rows: 3, + cols: 3 + } + }, + 'PMGateway': { + 'PARALLEL': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'EXCLUSIVE': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INCLUSIVE': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + } + }, + 'PMEvent': { + 'START_EMPTY': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'START_MESSAGECATCH': { + order: ["task", "gateway", "intermediate", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'START_TIMER': { + order: ["task", "gateway", "intermediate", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'START_CONDITIONAL': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'START_SIGNALCATCH': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_EMAIL': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_MESSAGETHROW': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_SIGNALTHROW': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_MESSAGECATCH': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_TIMER': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_CONDITIONAL': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_SIGNALCATCH': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'END_EMPTY': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_EMAIL': { + order: ["flow", "properties", "delete"], + rows: 2, + cols: 2 + }, + 'END_MESSAGETHROW': { + order: ["flow", "properties", "delete"], + rows: 2, + cols: 2 + }, + 'END_ERRORTHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_SIGNALTHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_TERMINATETHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + }, + 'PMPool': { + 'DEFAULT': { + order: ["delete"], + rows: 1, + cols: 1 + } + }, + 'PMParticipant': { + 'DEFAULT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + }, + 'PMArtifact': { + 'TEXT_ANNOTATION': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'GROUP': { + order: ["delete"], + rows: 1, + cols: 1 + } + }, + 'PMData': { + 'DATAOBJECT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATAINPUT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATAOUTPUT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATASTORE': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + } +}; +var PMDesigner = {}, + LANG, + WORKSPACE, + SKIN, + DEFAULT_WINDOW_WIDTH, + DEFAULT_WINDOW_HEIGHT, + ENABLED_FEATURES, + DataDictionary, + enviromentVariables, + resizingFrame, + ViewTaskInformation; + +PMDesigner.defaultRules = window.defaultRules ? window.defaultRules : {}; +PMDesigner.defaultCrown = window.defaultCrown ? defaultCrown : {}; +PMDesigner.configCrown = window.configCrown ? configCrown : {}; +PMDesigner.modelRules = new ModelRules(PMDesigner.defaultRules); +PMDesigner.modelCrown = new ModelCrown(PMDesigner.defaultCrown); +PMDesigner.remoteUrl = ""; +PMDesigner.moddle = new BpmnModdle(); +PMDesigner.bpmnFactory = new BpmnFactory(PMDesigner.moddle); +PMDesigner.keyCodeF5 = 116; +PMDesigner.shapeProperties = function (shape) { + var typeShape = shape.type; + switch (typeShape) { + case "PMActivity": + PMDesigner.activityProperties(shape); + break; + case "PMGateway": + PMDesigner.gatewayProperties(shape); + break; + case "PMEvent": + shape.eventProperties(); + break; + } +}; + +/** + * function to get the enviroment variables (WORKSPACE, LANG, SKIN) + */ +enviromentVariables = function (variable) { + var url1, variables, WORKSPACE, LANG, SKIN; + if (window.parent) { + url1 = window.parent.location.pathname; + variables = url1.split('/'); + WORKSPACE = variables[1]; + WORKSPACE = WORKSPACE.substring(3); + LANG = variables[2]; + SKIN = variables[3]; + + if (variable == 'WORKSPACE') { + return WORKSPACE; + } else if (variable == 'LANG') { + return LANG; + } else if (variable == 'SKIN') { + return SKIN; + } else { + return null; + } + } +}; + +LANG = (typeof SYS_LANG !== "undefined") ? SYS_LANG : enviromentVariables('LANG'); +WORKSPACE = (typeof SYS_SYS !== "undefined") ? SYS_SYS : enviromentVariables('WORKSPACE'); +SKIN = (typeof SYS_SKIN !== "undefined") ? SYS_SKIN : enviromentVariables('SKIN'); + +DEFAULT_WINDOW_WIDTH = 943; +DEFAULT_WINDOW_HEIGHT = 520; +ENABLED_FEATURES = []; + +if (LANG != 'en') { + if (typeof __TRANSLATIONMAFE != "undefined" && typeof __TRANSLATIONMAFE[LANG] != 'undefined') { + PMUI.loadLanguage(__TRANSLATIONMAFE.en, 'en'); + PMUI.loadLanguage(__TRANSLATIONMAFE[LANG], LANG); + + PMUI.setDefaultLanguage('en'); + PMUI.setCurrentLanguage(LANG); + } +} + +PMDesigner.resizeFrame = function () { + if (parent.document.documentElement === document.documentElement) { + jQuery(".content").css("height", parseInt(jQuery(window).height())); + } else { + jQuery(".content").css("height", document.body.clientHeight); + + } +}; +resizingFrame = PMDesigner.resizeFrame; +PMDesigner.applyCanvasOptions = function () { + list = new PMUI.control.DropDownListControl({ + options: [], + style: { + cssClasses: [ + "mafe-dropdown-zoom" + ] + }, + width: 150, + onChange: function (newValue, previous) { + var canvas = PMDesigner.project.diagrams.find('id', newValue); + PMUI.getActiveCanvas().getHTML().style.display = 'none'; + PMUI.setActiveCanvas(canvas); + canvas.getHTML().style.display = 'inline'; + } + }); + //enable to support multidiagram + //jQuery(jQuery(".navBar li")[6]).append(list.getHTML()); + list.defineEvents(); + PMDesigner.canvasList = list; +}; +//Zoom +PMDesigner.ApplyOptionsZoom = function () { + list = new PMUI.control.DropDownListControl({ + id: '_idListZoom', + options: [ + { + label: "50%", + value: 1 + }, + { + label: "75%", + value: 2 + }, + { + label: "100%", + value: 3, + selected: true + }, + { + label: "125%", + value: 4 + }, + { + label: "150%", + value: 5 + } + ], + style: { + cssClasses: [ + "mafe-dropdown-zoom" + ] + }, + onChange: function (newValue, previous) { + var i; + newValue = parseInt(newValue, 10); + PMUI.getActiveCanvas().applyZoom(newValue); + } + }); + + //jQuery(jQuery(".navBar li")[4]).append(list.getHTML()); + jQuery(jQuery(".mafe-zoom-options")).append(list.getHTML()); + + list.defineEvents(); +}; +/** + * hides all requiered TinyControls + */ +PMDesigner.hideAllTinyEditorControls = function () { + var control, + i, + max, + j, + mapMax, + editor, + controlMap = [ + 'tinyeditor_fontselect', + 'tinyeditor_fontsizeselect', + 'tinyeditor_bullist', + 'tinyeditor_numlist', + 'tinyeditor_forecolor', + 'tinyeditor_backcolor' + ]; + for (i = 0, max = tinymce.editors.length; i < max; i += 1) { + editor = tinymce.editors[i]; + jQuery.each(editor.controlManager.controls, function (index, val) { + if (val && jQuery.isFunction(val.hideMenu)) { + val.hideMenu(); + } + }); + } + +}; + + +jQuery(document).ready(function ($) { + var setSaveButtonDisabled, + s, + sidebarCanvas, + project, + d, + downloadLink, + handlerExportNormal, + handlerExportGranular, + handler, + validatosr, + help, + option, + menu, + elem, + validatorLabel = "Validator".translate(); + /*************************************************** + * Defines the Process + ***************************************************/ + if (typeof prj_uid === "undefined") { + prj_uid = ''; + } + if (typeof prj_readonly === "undefined") { + prj_readonly = ''; + } + if (typeof credentials === "undefined") { + credentials = ''; + } else { + credentials = RCBase64.decode(credentials); + credentials = (credentials == '') ? "" : JSON.parse(credentials); + } + + if (prj_readonly !== 'true') { + $("#idContent").find(".content_controls").show(); + $(".bpmn_shapes").show(); + $('.bpmn_shapes_legend').hide(); + $("#idNavBar").show().css('height', '33px'); + } + + PMDesigner.createHTML(); + setSaveButtonDisabled = function (that) { + if (that.isDirty()) { + if (document.getElementsByClassName("mafe-save-process").length > 0) { + document.getElementsByClassName("mafe-save-process")[0].removeAttribute("style"); + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].style.color = "#FFF"; + + var mafebuttonMenu = document.getElementsByClassName("mafe-button-menu")[0]; + mafebuttonMenu.style.backgroundColor = "#0C9778"; + mafebuttonMenu.firstChild.src = "/lib/img/caret-down-w.png"; + } + } else { + if (document.getElementsByClassName("mafe-save-process").length > 0) { + document.getElementsByClassName("mafe-save-process")[0].style.backgroundColor = "#e8e8e8"; + document.getElementsByClassName("mafe-save-process")[0].style.color = "#000"; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].style.color = "#000"; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].text = "Save".translate(); + + var mafebuttonMenu = document.getElementsByClassName("mafe-button-menu")[0]; + mafebuttonMenu.style.backgroundColor = "#e8e8e8"; + mafebuttonMenu.firstChild.src = "/lib/img/caret-down.png"; + } + } + }; + sidebarCanvas = []; + for (s = 0; s < PMDesigner.sidebar.length; s += 1) { + sidebarCanvas = sidebarCanvas.concat(PMDesigner.sidebar[s].getSelectors()); + jQuery(".bpmn_shapes").append(PMDesigner.sidebar[s].getHTML()); + } + //Adding Sidebar to DOM + firstAbsuluteX = jQuery("#div-layout-canvas").offset().left; + + project = new PMProject({ + id: prj_uid, + name: 'Untitled Process', + readOnly: prj_readonly === "true", + keys: { + access_token: credentials.access_token, + expires_in: credentials.expires_in, + token_type: credentials.token_type, + scope: credentials.scope, + refresh_token: credentials.refresh_token, + client_id: credentials.client_id, + client_secret: credentials.client_secret + }, + listeners: { + create: function (self, element) { + var sh, i, + contDivergent = 0, + contConvergent = 0; + //Updating the background color for connections + jQuery(".pmui-intersection > div > div").css("background-color", "black"); + + if (element.type == "Connection") { + ///////////****************Changing the gatDirection*******************////////////////// + if (element.relatedObject.srcPort.parent.gat_type === "PARALLEL" || + element.relatedObject.srcPort.parent.gat_type === "INCLUSIVE" || + element.relatedObject.destPort.parent.gat_type === "PARALLEL" || + element.relatedObject.destPort.parent.gat_type === "INCLUSIVE") { + if (element.relatedObject.srcPort.parent.gat_type !== undefined) { + sh = element.relatedObject.srcPort.parent; + } else { + sh = element.relatedObject.destPort.parent; + } + + if (sh.gat_direction === "DIVERGING") { + for (i = 0; i < sh.ports.asArray().length; i += 1) { + if (sh.ports.asArray()[i].connection.flo_element_origin_type === "bpmnActivity") { + contDivergent += 1; + } + if (contDivergent > 1) { + sh.gat_direction = "CONVERGING"; + i = sh.ports.asArray().length; + } + } + } + if (sh.gat_direction === "CONVERGING") { + for (i = 0; i < sh.ports.asArray().length; i += 1) { + if (sh.ports.asArray()[i].connection.flo_element_origin_type === "bpmnGateway") { + contConvergent += 1; + } + if (contConvergent > 1) { + sh.gat_direction = "DIVERGING"; + i = sh.ports.asArray().length; + } + } + } + + } + } + setSaveButtonDisabled(self); + }, + update: function (self) { + //Updating the background color for connections + jQuery(".pmui-intersection > div > div").css("background-color", "black"); + setSaveButtonDisabled(self); + }, + remove: function (self) { + setSaveButtonDisabled(self); + }, + success: function (self, xhr, response) { + var message; + self.dirty = false; + setSaveButtonDisabled(self); + self.dirtyElements[0] = { + laneset: {}, + lanes: {}, + activities: {}, + events: {}, + gateways: {}, + flows: {}, + artifacts: {}, + lines: {}, + data: {}, + participants: {}, + startMessageEvent: {}, + startTimerEvent: {} + }; + self.updateIdentifiers(response); + PMDesigner.connectValidator.bpmnValidator(); + //if (PMDesigner.currentMsgFlash) { + PMDesigner.msgFlash('The process was saved successfully.'.translate(), document.body, 'success', 3000, 5); + PMDesigner.RoutingRuleSetOrder(); + //} + + }, + failure: function (self, xhr, response) { + var message; + if (response.error.code === 401) { + /*message = new PMUI.ui.FlashMessage({ + message: "It was not possible to establish a connection with the server".translate(), + duration: 5000, + appendTo: document.body, + severity: 'info' + }); + message.show();*/ + //self.remoteProxy.setUrl("/"+WORKSPACE+"/oauth2/token"); + //self.setRefreshToken(); + //self.remoteProxy.setUrl("/api/1.0/"+WORKSPACE+"/project/"+prj_uid); + //self.save(); + } else { + PMDesigner.msgFlash('Error saving the process.'.translate(), document.body, 'error', 3000, 5); + self.updateIdentifiers(response); + } + } + } + }); + PMDesigner.project = project; + //create a new restApi + PMDesigner.restApi = RestApi.createRestApi({ + serverUrl: '/rest/v10', + keys: PMDesigner.project.keys + }); + systemRest = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'system/enabled-features', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var result = response.pop(); + ENABLED_FEATURES = result.response; + navbarExportUpdate(); + }, + functionFailure: function (xhr, response) { + ENABLED_FEATURES = []; + } + }).setBaseEndPoint('').executeRestClient(); + PMDesigner.connectValidator = new ConnectValidator(); + for (d = 0; d < PMDesigner.sidebar.length; d += 1) { + PMDesigner.sidebar[d].activate(); + } + + $('.bpmn_shapes_legend').hide(); + project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + prj_uid); + project.load(); + + /*=========================================== + = ProcessMaker module = + ===========================================*/ + + //Renders content controls + PMDesigner.contentControl.show(); + new PMAction({ + selector: ".mafe-menu-eventmessages-create", + label: { + selector: ".mafe-menu-eventmessages-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.eventMessages.create(); + } + }); + + /*----- End of ProcessMaker module ------*/ + + /*======================================== + = Designer buttons = + ========================================*/ + + //Renders navBar Panel + PMDesigner.navbarPanel.show(); + // create Zoom options + PMDesigner.ApplyOptionsZoom(); + //the action to generate a .bpmn file with the export option. + downloadLink = $('.mafe-button-export-bpmn-process'); + downloadLink.click(function (e) { + PMDesigner.moddle.toXML(PMDesigner.businessObject, function (err, xmlStrUpdated) { + + setEncoded(downloadLink, PMDesigner.project.projectName + '.bpmn', xmlStrUpdated); + + // xmlStrUpdated contains new id and the added process + }); + + }); + option = $("
" + "Save as".translate() + "
"); + /** + * Add data tables + */ + $('body').append('
') + $('.validator_header').append('

' + validatorLabel + '

'); + $('.validator_header').append(''); + $('.validator_body').html('
'); + PMDesigner.validTable = $('#validator-table').DataTable({ + paging: false, + scrollY: 100, + searching: false, + "info": false, + scrollCollapse: true, + "columns": [ + { + name: 'numrow', + "title": "#", + width: '5%', + render: function (data, type, row, conf) { + return conf.row + 1; + } + }, + { + name: 'id', + className: 'never' + }, + { + "title": "Type".translate(), + width: '10%', + name: 'severity', + render: function (data, type, row, conf) { + var clasMap = { + Error: 'mafe-icon-error', + Warning: 'mafe-icon-warning' + }; + if (type === 'display') { + return ' ' + data; + } + return data; + } + }, + {name: 'element', "title": "Element".translate(), width: '15%'}, + {name: 'element-type', "title": "Element Type".translate(), width: '15%'}, + {name: 'description', "title": "Description".translate(), width: '45%'} + ] + }); + jQuery('#validator-table tbody').on('click', 'tr', function () { + var id = PMDesigner.validTable.row(this).data()[1], + shape; + if ($(this).hasClass('selected')) { + $(this).removeClass('selected'); + PMUI.getActiveCanvas().hideAllCoronas().emptyCurrentSelection(); + } + else { + PMDesigner.validTable.$('tr.selected').removeClass('selected'); + $(this).addClass('selected'); + PMUI.getActiveCanvas().hideAllCoronas().emptyCurrentSelection(); + shape = PMUI.getActiveCanvas().items.find('id', id); + PMUI.getActiveCanvas().addToSelection(shape.relatedObject); + } + }); + PMDesigner.validTable.columns([1]).visible(false); + /********finish datatables********/ + new PMAction({ + selector: ".mafe-validator-close", + tooltip: "Close Validator".translate(), + execute: true, + handler: function () { + $('.bpmn_validator').css('visibility', 'hidden'); + $('.mafe-toolbar-validation').css('background-color', 'rgb(233, 233, 233)'); + PMDesigner.validator = false; + } + }); + + menu = $("
"); + menu.append(option); + option.on("mouseout", function (e) { + menu.hide(); + }); + option.on("click", function (e) { + var saveas; + menu.hide(); + PMDesigner.project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id); + PMDesigner.project.save(true); + saveas = new SaveAs(); + saveas.open(); + }); + $(".mafe-button-menu").on("click", function (e) { + e.stopPropagation(); + $(".mafe-save-process").append(menu); + menu.show(); + }); + + /*----- End of Designer buttons ------*/ + /*================================================= + = Full screen functionality = + =================================================*/ + if (parent.document.documentElement === document.documentElement) { + elem = document.documentElement; + } else { + elem = parent.document.getElementById("frameMain"); + } + PMDesigner.fullScreen = new FullScreen({ + element: elem, + onReadyScreen: function () { + setTimeout(function () { + PMDesigner.resizeFrame(); + }, 500); + }, + onCancelScreen: function () { + setTimeout(function () { + PMDesigner.resizeFrame(); + }, 500); + } + }); + /*----- End of Full screen functionality ------*/ + + /*============================================= + = Shapes and Controls Box = + =============================================*/ + PMDesigner.cookie = { + name: "PMDesigner", + object: {}, + get: function (cname) { + var name = cname + "=", i, c, + ca = document.cookie.split(';'); + for (i = 0; i < ca.length; i += 1) { + c = ca[i].trim(); + if (c.indexOf(name) == 0) + return c.substring(name.length, c.length); + } + return ""; + }, + remove: function (cname) { + jQuery.each(PMDesigner.cookie.object, function (index, val) { + if (index === cname) { + delete PMDesigner.cookie.object[cname]; + PMDesigner.cookie.refresh(); + } + }); + }, + refresh: function () { + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + }; + PMDesigner.localStorage = { + prefix: "PM_" + WORKSPACE + "_" + prj_uid, + object: {}, + remove: function (cname) { + var obj; + obj = localStorage.getItem(PMDesigner.localStorage.prefix); + obj = (obj === null) ? {} : JSON.parse(obj); + if (obj[cname]) { + delete obj[cname]; + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(obj)); + } + } + }; + if (Modernizr.localstorage) { + var localDesigner = localStorage.getItem(PMDesigner.localStorage.prefix); + localDesigner = (localDesigner === null) ? {} : JSON.parse(localDesigner); + PMDesigner.panelsPosition = localDesigner; + } else { + if (PMDesigner.cookie.get(PMDesigner.cookie.name) !== "") { + var positions, pLeft, pTop, html; + positions = JSON.parse(PMDesigner.cookie.get(PMDesigner.cookie.name)); + PMDesigner.cookie.object = positions; + PMDesigner.panelsPosition = positions; + } + } + if (typeof PMDesigner.panelsPosition === "object") { + var pst = PMDesigner.panelsPosition; + if (pst.navbar) { + pLeft = pst.navbar.x; + pTop = pst.navbar.y; + html = document.getElementsByClassName("navBar")[0]; + } + if (pst.bpmn) { + pLeft = 0; + pTop = 0; + html = document.getElementsByClassName("bpmn_shapes")[0]; + html.style.left = pLeft + "px"; + html.style.top = pTop + "px"; + } + if (pst.controls) { + pLeft = pst.controls.x; + pTop = pst.controls.y; + html = document.getElementsByClassName("content_controls")[0]; + html.style.left = pLeft + "px"; + html.style.top = pTop + "px"; + if (pTop > 503) { + $("#idContent").find(".content_controls").css({'top': '', 'left': ''}); + } + } + } + jQuery(".bpmn_shapes").draggable({ + handle: "div", + start: function () { + }, + drag: function () { + }, + stop: function (event) { + var pLeft, pTop, currentObj; + pLeft = parseInt(event.target.style.left); + pTop = parseInt(event.target.style.top); + bpmn = { + bpmn: { + x: pLeft, + y: pTop + } + }; + if (Modernizr.localstorage) { + currentObj = localStorage.getItem(PMDesigner.localStorage.prefix); + currentObj = (currentObj === null) ? {} : JSON.parse(currentObj); + jQuery.extend(true, currentObj, bpmn); + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(currentObj)); + } else { + jQuery.extend(true, PMDesigner.cookie.object, bpmn); + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + } + }); + jQuery(".content_controls").draggable({ + handle: "div", + start: function () { + }, + drag: function () { + jQuery("html").css("overflow", "hidden"); + }, + stop: function (event) { + jQuery("html").css("overflow", "auto"); + if (jQuery(this).position().top > $(window).height()) { + var x = $(window).height() - 30; + jQuery(this).css({'top': x + 'px'}); + } + var pLeft, pTop, currentObj; + pLeft = parseInt(event.target.style.left); + pTop = parseInt(event.target.style.top); + if (pTop < 90) + pTop = 90; + event.target.style.setProperty("top", pTop.toString() + "px"); + controls = { + controls: { + x: pLeft, + y: pTop + } + }; + if (Modernizr.localstorage) { + currentObj = localStorage.getItem(PMDesigner.localStorage.prefix); + currentObj = (currentObj === null) ? {} : JSON.parse(currentObj); + jQuery.extend(true, currentObj, controls); + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(currentObj)); + } else { + jQuery.extend(true, PMDesigner.cookie.object, controls); + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + } + }); + /*----- End of Shapes and Controls Box ------*/ + + //Resize window + PMDesigner.resizeFrame(); + + /*============================================== + = Autosave functionality = + ==============================================*/ + PMDesigner.project.setSaveInterval(40000); + setInterval(function () { + if (PMDesigner.project.isDirty() && PMDesigner.project.readOnly === false) { + PMDesigner.project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + prj_uid); + PMDesigner.msgFlash('Saving Process'.translate(), document.body, 'success', 5000, 5); + PMDesigner.project.save(true); + } + }, PMDesigner.project.saveInterval); + /*----- End of Autosave functionality ------*/ + + //Reviewing functionalities + if (!PMDesigner.supportBrowser("fullscreen")) { + var li = document.getElementsByClassName("mafe-button-fullscreen"); + if (li) { + li[0].parentElement.style.display = "none"; + } + } + jQuery('.mafe-zoom-options').attr('title', 'Zoom'.translate()).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery('.mafe-toolbar-lasso').mouseover(function (e) { + $('.mafe-toolbar-lasso').css('cursor', 'pointer'); + }); + jQuery('.mafe-toolbar-validation').mouseover(function (e) { + $('.mafe-toolbar-validation').css('cursor', 'pointer'); + }); + jQuery('.mafe-toolbar-lasso').click(function (e) { + if (!PMUI.getActiveCanvas().lassoEnabled) { + $('.mafe-toolbar-lasso').css('background-color', 'rgb(207, 207, 207)'); + PMUI.getActiveCanvas().lassoEnabled = true; + } else { + $('.mafe-toolbar-lasso').css('background-color', 'rgb(233, 233, 233)'); + PMUI.getActiveCanvas().lassoEnabled = false; + } + }); + + PMDesigner.helper = new IntroHelper({ + tooltipClass: 'general', + skipLabel: 'Quit'.translate(), + + nextLabel: 'Next →'.translate(), + prevLabel: '← Back'.translate(), + doneLabel: 'Done'.translate(), + steps: [ + { + intro: '
' + }, + { + element: '#idNavBar', + intro: 'The designer bar displays the process name and is used to control the process view (zoom, full screen view), the export, undo/redo and the save button.'.translate() + }, + + { + element: '.bpmn_shapes', + intro: 'Drag and drop the process elements that you want to include in the process design.'.translate() + + '
' + ' Task: Add to include an action in your process.'.translate() + + '
' + ' Gateway: Selects a path or divides the process into multiple paths and joins them together.'.translate() + + '
' + ' Start Event: The process always begins with a start event.'.translate() + + '
' + ' Intermediate Event: Used to define an event that happens in the middle of the process.'.translate() + + '
' + ' End Event: End the execution of the process.'.translate() + + '
' + ' Pool: Place each process in a separate pool.'.translate() + + '
' + ' Lane: Used to divide a process into different sections.'.translate() + }, + { + element: '#div-layout-canvas', + intro: "In the design area you can drop the process elements and order or arrange them to design your process.".translate() + }, + { + element: '.content_controls', + intro: '

' + + 'The process objects are used to add execution features to the current process design.'.translate() + + '
Variables: Define the process data.'.translate() + + '
Dynaforms: Create dynamic forms.'.translate() + + '
Triggers: Create scripts.'.translate() + + '
Output documents: Generate documents with process data.'.translate() + + '
DB connections: Connect to external databases.'.translate() + + '

', + position: 'left' + }, + { + intro: '
' + 'Select an element in the designer to display the quick toolbar with the list of the most used options available for that element.'.translate() + '
' + } + ], + onExit: function () { + var canvas = PMUI.getActiveCanvas(); + if (canvas && canvas.getGridLine() && canvas.getHTML()) { + canvas.getHTML().classList.add("pmui-pmcanvas"); + } + } + }); + + jQuery('.mafe-toolbar-validation').click(function (e) { + if (!PMDesigner.validator) { + $('.mafe-toolbar-validation').css('background-color', 'rgb(207, 207, 207)'); + PMDesigner.validator = true; + } else { + $('.bpmn_validator').css('visibility', 'hidden'); + $('.mafe-toolbar-validation').css('background-color', 'rgb(233, 233, 233)'); + PMDesigner.validator = false; + } + }); + if (inArray("jXsSi94bkRUcVZyRStNVExlTXhEclVadGRRcG9xbjNvTWVFQUF3cklKQVBiVT0=", ENABLED_FEATURES)) { + $("#idNavBar").find(".mafe-button-export-process").html( + $("#idNavBar").find(".mafe-button-export-process").text() + " ▼" + ); + } + + function inArray(needle, haystack) { + var i, + length = haystack.length; + for (i = 0; i < length; i += 1) { + if (haystack[i] == needle) return true; + } + return false; + } +}); + +window.onload = function () { + //Reset the scroll positions + window.scrollBy(-window.scrollX, -window.scrollY); + document.onkeydown = function (e) { + if (e.keyCode === 8 && e.target === document.body) { + e.stopPropagation(); + return false; + } + }; +}; +/*================================================== + = Components from the Panels = + ==================================================*/ + +PMDesigner.createHTML = function () { + var minShapes = document.createElement("span"), + minShapesLegend = document.createElement("span"), + refreshShapes = document.createElement("span"), + minControls = document.createElement("span"), + processObjects = document.createElement("span"), + refreshControls = document.createElement("span"), + refreshNavBar = document.createElement("span"); + minShapes.id = "minShapes"; + minShapesLegend.id = "minShapesLegend"; + refreshShapes.id = "resetShapes"; + minControls.id = "minControls"; + refreshControls.id = "resetControls"; + refreshNavBar.id = "resetNavBar"; + minShapes.className = "mafe-shapes-toggle"; + minShapesLegend.className = "mafe-shapes-toggle"; + refreshShapes.className = "mafe-shapes-refresh"; + minControls.className = "mafe-shapes-toggle"; + processObjects.className = "mafe-process-object"; + refreshControls.className = "mafe-shapes-refresh"; + refreshNavBar.className = "mafe-shapes-refresh"; + minShapes.title = "Minimize".translate(); + minShapesLegend.title = "Minimize".translate(); + refreshShapes.title = "reset".translate(); + minControls.title = "Minimize".translate(); + refreshControls.title = "Reset to original position".translate(); + refreshNavBar.title = "reset".translate(); + + jQuery(minShapes).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(minShapesLegend).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshShapes).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(minControls).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshControls).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshNavBar).tooltip({tooltipClass: "mafe-action-tooltip"}); + + refreshControls.style.backgroundPosition = '0px 0px'; + processObjects.textContent = "Process Objects".translate(); + + minShapes.onclick = function () { + var i, + items = jQuery(".bpmn_shapes > ul"); + if (items.length > 0) { + for (i = 0; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + } + + } + } + }; + minShapesLegend.onclick = function () { + var i, + items = jQuery(".bpmn_shapes_legend").children(); + for (i = 1; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + } + } + }; + refreshShapes.onclick = function () { + jQuery(".bpmn_shapes").removeAttr('style'); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("bpmn"); + } else { + PMDesigner.cookie.remove("bpmn"); + } + }; + minControls.onclick = function () { + var i, + title = '', + items = jQuery(".content_controls > ul"); + + if (items.length > 0) { + for (i = 0; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + title = "Maximize"; + $('#minControls').removeClass('mafe-shapes-toggle'); + $('#minControls').addClass('mafe-shapes-plus'); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + title = "Minimize"; + $('#minControls').removeClass('mafe-shapes-plus'); + $('#minControls').addClass('mafe-shapes-toggle'); + + } + } + } + jQuery(minControls).tooltip({content: title.translate()}); + }; + refreshControls.onclick = function () { + jQuery(".content_controls").css({ + left: "auto", + right: "20px", + top: "90px" + }); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("controls"); + } else { + PMDesigner.cookie.remove("controls"); + } + }; + refreshNavBar.onclick = function () { + jQuery(".navBar").removeAttr('style'); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("navbar"); + } else { + PMDesigner.cookie.remove("navbar"); + } + }; + + + jQuery(".bpmn_shapes>div").append(minShapes); + jQuery(".bpmn_shapes>div").append(refreshShapes); + jQuery(".content_controls>div").append(processObjects); + jQuery(".content_controls>div").append(minControls); + jQuery(".content_controls>div").append(refreshControls); + jQuery(".navBar>div").append(refreshNavBar); + jQuery(".bpmn_shapes_legend>div").append(minShapesLegend); + jQuery(".bpmn_shapes, .content_controls").on("contextmenu", function (e) { + e.preventDefault(); + }); + + PMDesigner.applyCanvasOptions(); + +}; + +/*----- End of Components from the Panels ------*/ + +/*===================================================== + = Get information about browser = + =====================================================*/ +PMDesigner.getBrowser = function () { + var match, + ua = navigator.userAgent.toLowerCase(); + if (ua) { + match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[1] || "", + version: match[2] || "0" + }; + } +}; +/*----- End of Get information about browser ------*/ + +PMDesigner.supportBrowser = function (functionality) { + var browser, el, module; + functionality = functionality.toLowerCase(); + switch (functionality) { + case "fullscreen": + browser = PMDesigner.getBrowser(); + if ((browser.browser === "msie") && (parseInt(browser.version, 10) <= 10)) { + try { + module = new ActiveXObject("WScript.Shell"); + } catch (e) { + module = false; + } + } else { + el = document.documentElement; + module = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen; + if (!module) { + module = false; + } + } + break; + case "": + break; + } + return module; +}; + +/*============================================================ + = Leave the current page Functionality = + ============================================================*/ +window.onbeforeunload = function (e) { + var message; + if ((PMDesigner.project.isDirty() + && !PMDesigner.project.readOnly) + || PMDesigner.project.isSave) { + message = "There are unsaved changes, if you leave the editor some changes won't be saved.".translate(); + e = e || window.event; + if (e) { + e.returnValue = message; + } + return message; + } +}; +/*----- End of Leave the current page Functionality ------*/ + +/*===================================================================== + = Validating coordinates for create a new shape = + =====================================================================*/ +PMUI.validCoordinatedToCreate = function (canvas, event, shape) { + var position, p, width, height, createElem = true, panels = [], message; + //navBar panel + position = jQuery(".navBar").offset(); + width = jQuery(".navBar").width(); + height = jQuery(".navBar").height(); + element = { + x1: position.left, + y1: position.top, + x2: position.left + width, + y2: position.top + height + }; + panels.push(element); + //BPMN panel + position = jQuery(".bpmn_shapes").offset(); + width = jQuery(".bpmn_shapes").width(); + height = jQuery(".bpmn_shapes").height(); + element = { + x1: position.left, + y1: position.top, + x2: position.left + width, + y2: position.top + height + }; + if (panels.length > 0) { + for (p = 0; p < panels.length; p += 1) { + if (((event.pageX >= panels[p].x1) && (event.pageX <= panels[p].x2)) + && ((event.pageY >= panels[p].y1) && (event.pageY <= panels[p].y2))) { + PMDesigner.msgFlash('Is not possible create the element in that area'.translate(), document.body, 'info', 3000, 5); + return false; + } + } + } + + return true; +}; +/*----- End of Validating coordinates for create a new shape ------*/ + +PMUI.pageCoordinatesToShapeCoordinates = function (shape, e, xCoord, yCoord, customShape) { + var coordinates, + x = (!xCoord) ? e.pageX : xCoord, + y = (!yCoord) ? e.pageY : yCoord, + orgX = (!xCoord) ? e.pageX : xCoord, + orgY = (!yCoord) ? e.pageY : yCoord, + canvas = shape.getCanvas(); + x += canvas.getLeftScroll() - shape.getAbsoluteX() - canvas.getX(); + y += canvas.getTopScroll() - shape.getAbsoluteY() - canvas.getY(); + coordinates = new PMUI.util.Point(x, y); + return coordinates; +}; + +PMDesigner.msgFlash = function (text, container, severity, duration, zorder) { + var msg; + if (!PMDesigner.currentMsgFlash) { + msg = new PMUI.ui.FlashMessage({ + id: '__msgFlashMessage', + severity: 'success' + }); + } else { + msg = PMDesigner.currentMsgFlash; + } + if (msg.html) + jQuery(msg.html).remove(); + msg.setMessage(text || ""); + msg.setAppendTo(container || document.body); + msg.setSeverity(severity || "success"); + msg.setDuration(duration || 3000); + msg.setZOrder(zorder || 100); + msg.show(); + PMDesigner.currentMsgFlash = msg; +}; + +PMDesigner.msgWinError = function (text) { + var msgError; + if (!PMDesigner.currentWinError) { + msgError = new PMUI.ui.MessageWindow({ + id: 'showMessageWindowFailure', + width: 490, + windowMessageType: 'error', + title: 'Error'.translate(), + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + msgError.close(); + }, + buttonType: "success" + } + ] + }); + } else { + msgError = PMDesigner.currentWinError; + } + msgError.setMessage(text || 'Error'.translate()); + msgError.showFooter(); + msgError.open(); + PMDesigner.currentWinError = msgError; +}; + +PMDesigner.msgWinWarning = function (text) { + var msgWarning; + if (!PMDesigner.currentWinWarning) { + msgWarning = new PMUI.ui.MessageWindow({ + id: 'showMessageWindowWarning', + windowMessageType: 'warning', + width: 490, + title: 'Warning'.translate(), + footerItems: [{ + text: 'Ok'.translate(), + buttonType: "success", handler: function () { + msgWarning.close(); + } + }] + }); + } else { + msgWarning = PMDesigner.currentWinWarning; + } + msgWarning.setMessage(text || 'Warning'.translate()); + msgWarning.showFooter(); + msgWarning.open(); + PMDesigner.currentWinWarning = msgWarning; +}; + +PMDesigner.modeReadOnly = function () { + var restClient; + if (prj_readonly === 'true') { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'cases/' + app_uid + '/tasks', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var viewTaskInformation = new ViewTaskInformation(); + viewTaskInformation.setData(response[0].response); + viewTaskInformation.setShapes(); + viewTaskInformation.showViewLegendsInformation(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + } +}; + +PMDesigner.reloadDataTable = function () { + $('.bpmn_validator').css('visibility', 'visible'); +}; + +/** + * Escape XML characters method. + * There are only five: + * " " + * ' ' + * < < + * > > + * & & + * + * @param {string} label + * @returns {string} + */ +PMDesigner.escapeXMLCharacters = function (label) { + return label + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(/'/g, "'") + .replace(//g, ">"); +}; + +DataDictionary = function () { +}; +DataDictionary.prototype.getColor = function (value) { + switch (value) { + case 'TASK_IN_PROGRESS': + return 'red'; + case 'TASK_COMPLETED': + return 'green'; + case 'TASK_PENDING_NOT_EXECUTED': + return 'silver'; + case 'TASK_PARALLEL': + return 'orange'; + default: + return 'white'; + } +}; +DataDictionary.prototype.getStatus = function (value) { + switch (value) { + case 'TASK_IN_PROGRESS': + return 'Task in Progress'.translate(); + case 'TASK_COMPLETED': + return 'Completed Task'.translate(); + case 'TASK_PENDING_NOT_EXECUTED': + return 'Pending Task / Not Executed'.translate(); + case 'TASK_PARALLEL': + return 'Parallel Task'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasAssignType = function (value) { + switch (value) { + case 'BALANCED': + return 'Balanced'.translate(); + case 'MANUAL': + return 'Manual'.translate(); + case 'REPORT_TO': + return 'Report toO'.translate(); + case 'EVALUATE': + return 'Evaluate'.translate(); + case 'SELF_SERVICE': + return 'self Service'.translate(); + case 'SELF_SERVICE_EVALUATE': + return 'Self Service Evaluate'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasType = function (value) { + switch (value) { + case 'NORMAL': + return 'Normal'.translate(); + case 'SUBPROCESS': + return 'Sub Process'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasDerivation = function (value) { + switch (value) { + case 'NORMAL': + return 'Normal'.translate(); + default: + return value; + } +}; + +ViewTaskInformation = function (settings) { + ViewTaskInformation.prototype.init.call(this, settings); +}; +ViewTaskInformation.prototype.init = function () { + var that = this, + panelButton = new PMUI.core.Panel({ + layout: 'hbox', + items: [ + that.getButton('Information', function () { + that.showInformation(); + }), + that.getButton('Delegations', function () { + that.showDelegations(); + }), + that.getButton('Route', function () { + that.showRoute(); + }) + ] + }); + that.windowAbstract.showFooter(); + that.windowAbstract.addItem(panelButton); + that.windowAbstract.addItem(that.panelvertical); +}; +ViewTaskInformation.prototype.dataDictionary = new DataDictionary(); +ViewTaskInformation.prototype.data = null; +ViewTaskInformation.prototype.shapeData = null; +ViewTaskInformation.prototype.panelvertical = new PMUI.core.Panel({layout: 'vbox', width: 400}); +ViewTaskInformation.prototype.windowAbstract = new PMUI.ui.Window({id: 'windowAbstract', width: 500, height: 350}); +ViewTaskInformation.prototype.setData = function (data) { + this.data = data; +}; +ViewTaskInformation.prototype.setCursor = function (shape) { + shape.getHTML().onmouseover = function () { + this.style.cursor = 'pointer'; + }; + shape.getHTML().onmouseout = function () { + this.style.cursor = ''; + }; +}; +ViewTaskInformation.prototype.setShapes = function () { + var that = this, + shape, + diagrams, + i, + j, + dt = that.data; + for (i = 0; i < dt.length; i += 1) { + diagrams = PMDesigner.project.diagrams.asArray(); + for (j = 0; j < diagrams.length; j += 1) { + shape = diagrams[j].getCustomShapes().find('id', dt[i].tas_uid); + if (typeof shape != "undefined" && shape != null) { + shape.changeColor(that.dataDictionary.getColor(dt[i].status)); + shape.data = dt[i]; + shape.hasClick = function (event) { + that.setShapeData(this.data); + that.showInformation(); + }; + that.setCursor(shape); + } + } + } +}; +ViewTaskInformation.prototype.setShapeData = function (data) { + this.shapeData = data; +}; +ViewTaskInformation.prototype.addRowNewLine = function (label, value) { + var panelhorizontal = new PMUI.core.Panel({ + layout: 'hbox' + }); + panelhorizontal.addItem(new PMUI.ui.TextLabel({text: ''})); + this.panelvertical.addItem(panelhorizontal); + return panelhorizontal; +}; +ViewTaskInformation.prototype.addRow = function (label, value) { + var field1, field2, field3, panelhorizontal; + + field1 = new PMUI.ui.TextLabel({text: label.translate(), proportion: 0.3}); + field2 = new PMUI.ui.TextLabel({text: ':', proportion: 0.1}); + field3 = new PMUI.ui.TextLabel({text: value ? value + '' : '', proportion: 0.6}); + + panelhorizontal = new PMUI.core.Panel({ + layout: 'hbox' + }); + + panelhorizontal.addItem(field1); + panelhorizontal.addItem(field2); + panelhorizontal.addItem(field3); + this.panelvertical.addItem(panelhorizontal); + return panelhorizontal; +}; +ViewTaskInformation.prototype.clearRows = function () { + this.panelvertical.clearItems(); +}; +ViewTaskInformation.prototype.showInformation = function () { + var that = this; + that.clearRows(); + that.addRow('Title'.translate(), that.shapeData.tas_title); + that.addRow('Description'.translate(), that.shapeData.tas_description); + that.addRow('Status'.translate(), that.dataDictionary.getStatus(that.shapeData.status)); + that.addRow('Type'.translate(), that.dataDictionary.getTasType(that.shapeData.tas_type)); + that.addRow('Assign type'.translate(), that.dataDictionary.getTasAssignType(that.shapeData.tas_assign_type)); + that.addRow('Routing'.translate(), that.dataDictionary.getTasDerivation(that.shapeData.tas_derivation)); + that.addRow('Start'.translate(), that.shapeData.tas_start); + that.addRowNewLine(); + that.addRow('Last User Name'.translate(), that.shapeData.usr_username); + that.addRow('Last User'.translate(), that.shapeData.usr_firstname + ' ' + that.shapeData.usr_lastname); + + that.windowAbstract.setTitle('Information'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.showDelegations = function () { + var that = this, i, dt; + that.clearRows(); + dt = that.shapeData.delegations; + for (i = 0; i < dt.length; i += 1) { + that.addRow('User', dt[i].usr_username); + that.addRow('User Name', dt[i].usr_firstname + ' ' + dt[i].usr_lastname); + that.addRow('Duration', dt[i].del_duration); + that.addRow('Finish Date', dt[i].del_finish_date); + that.addRow('Index', dt[i].del_index); + that.addRow('Init Date', dt[i].del_init_date); + that.addRow('Task Due Date', dt[i].del_task_due_date); + that.addRowNewLine(); + } + + that.windowAbstract.setTitle('Delegations'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.showRoute = function () { + var that = this, i, dt; + that.clearRows(); + that.addRow('Type', that.shapeData.route.type); + that.addRowNewLine(); + dt = that.shapeData.route.to; + for (i = 0; i < dt.length; i += 1) { + that.addRow('Condition', dt[i].rou_condition); + that.addRow('Number', dt[i].rou_number); + that.addRowNewLine(); + } + + that.windowAbstract.setTitle('Route'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.getButton = function (text, fn) { + return new PMUI.ui.Button({ + text: text.translate(), + width: 180, + height: 50, + style: { + cssProperties: { + marginRight: 10, + marginBottom: 10, + backgroundColor: '#474747', + borderRadius: 5, + padding: 5 + }, + cssClasses: ['mafeButton'] + }, + handler: fn + }); +}; +ViewTaskInformation.prototype.showViewLegendsInformation = function () { + var i, dt, legend, legendIcon, legendText; + $('.bpmn_shapes_legend').show(); + + i; + dt = [ + ['red', 'Task in Progress'.translate()], + ['green', 'Completed Task'.translate()], + ['silver', 'Pending Task / Not Executed'.translate()], + ['orange', 'Parallel Task'.translate()] + ]; + for (i = 0; i < dt.length; i += 1) { + legend = $("
"); + legendIcon = $("
").addClass("mafe-activity-task-" + dt[i][0]).addClass("icon-legend"); + legendText = $("
" + dt[i][1] + "
").addClass("text-legend"); + legend.append(legendIcon).append(legendText); + jQuery(".bpmn_shapes_legend").append(legend); + } + + jQuery(".bpmn_shapes_legend").draggable({ + handle: "div", + start: function () { + }, + drag: function (event, e, u) { + }, + stop: function (event) { + + } + }); +}; + +(function () { + /** + * @class PMUI.menu.ContextMenu + * Handles the context menu of designer + * contains all the menus for elements + * + * @extend PMUI.util.Factory + * @constructor + * This method creates a new instance of this object + * @param {Object} [settings] Constructor settings + */ + "use strict"; + var ContextMenu = function (settings) { + this.factory = null; + ContextMenu.prototype.init.call(this, settings); + }; + + ContextMenu.prototype.type = 'ContextMenu'; + + ContextMenu.prototype.family = 'ContextMenu'; + + /** + * Initializes the object. + * @param {Object} settings A JSON object with the config options. + * @private + */ + ContextMenu.prototype.init = function (settings) { + jQuery.extend(true, defaults, settings); + this.factory = new PMUI.util.Factory(defaults.factory); + }; + + /** + * Register a new context menu object into a product. + * + * Usage example: + * @example + * //Remember, this is an abstract class so it shouldn't be instantiate, + * //anyway we are instantiating it just for this example + * var additionalMenu = { + * id: "additionalMenu", + * text: "New Menu", + * onClick: function () { + * PMDesigner.msgWinWarning('This is a new Menu'); + * } + * }; + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * PMDesigner.contextMenuFactory.registerMenu("CANVAS", additionalMenu); + * + * @param {String} productName Name of the shape or product in factory. + * @param {Object} menu Object with menu values and actions. + * @private + */ + ContextMenu.prototype.registerMenu = function (productName, menu) { + if (typeof this.factory.products[productName] === 'undefined') { + console.log('Context Menu Warning: Cannot add Menu into: ' + productName + '. Please, review name.'); + } else { + if (this.factory.products[productName].items instanceof Array) { + this.factory.products[productName].items.push(menu); + } + } + }; + + /** + * Removes context menu object from product. + * + * Usage example: + * @example + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * // this example removes Canvas gridLines option + * PMDesigner.contextMenuFactory.removeMenu("CANVAS", "id", "menuGridLines"); + * + * @param {String} product Name of the shape or product in factory. + * @param {String} id Key to look through product. + * @param {String} value Name of the elementValue. + * @private + */ + ContextMenu.prototype.removeMenu = function (product, id, value) { + if (typeof this.factory.products[product] !== 'undefined') { + this.factory.products[product].items = _.reject(this.factory.products[product].items, function (menuValue) { + return menuValue[id] === value; + }); + } else { + console.log('Context Menu Warning: Cannot find ' + product + ' Menu. Please, review name.'); + } + }; + + /** + * Returns specific product. + * @param {String} type Name of product. + * @private + */ + ContextMenu.prototype.getProduct = function (type) { + return this.factory.products[type]; + }; + + var menuMessages = { + 'START': { + 'TIMER': 'Please configure cron to create cases.'.translate(), + 'CONDITIONAL': 'Please configure cron to create cases in base to a condition.'.translate(), + 'SIGNALCATCH': 'Please configure cron to create cases in base to a signal.'.translate() + }, + 'INTERMEDIATE': { + 'CATCH': { + 'TIMER': 'Please configure cron to wait for time event.'.translate(), + 'CONDITIONAL': 'Please configure cron to wait for time condition.'.translate(), + 'SIGNALCATCH': 'Please configure script to wait for a signal.'.translate() + }, + 'THROW': { + 'SIGNALTHROW': 'Please configure a script to send a signal.'.translate() + } + }, + 'END': { + 'ERRORTHROW': 'Please configure script to end with error status.'.translate(), + 'SIGNALTHROW': 'Please configure script to send a signal.'.translate(), + 'TERMINATETHROW': 'Please configure script to terminate case.'.translate() + } + }, + menu = {}, + rootMenu, + elementActivite, + typeMenu = { + text: "Gateway Type".translate(), + icon: "mafe-menu-properties-action", + id: "gatewaytype", + items: [ + { + id: "gatewayexclusive", + text: "Exclusive (XOR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('EXCLUSIVE'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayparallel", + text: "Parallel (AND) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('PARALLEL'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayinclusive", + text: "Inclusive (OR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('INCLUSIVE'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + endMarker = { + text: "End Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "endempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endmessagethrow", + text: "Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "enderrorthrow", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORTHROW', 'Error'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endsignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endterminatethrow", + text: "Terminate".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TERMINATETHROW', 'Terminate'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + intermediateCatchMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "intermediatemessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatetimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediateconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + boundaryCatchMarker = { + text: "Boundary Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "eventType", + items: [ + { + id: "messageCatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + } + }, + { + id: "boundaryTimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + } + }, + { + id: "BoudaryConditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + } + }, + { + id: "BoudarySignal", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + } + }, + { + id: "BoudaryError", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORCATCH', 'Error'); + } + } + ] + }, + intermediateThrowMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "intermediateemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatemessagethrow", + text: "Send Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Send Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + startCatchMarker = { + text: "Start Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "startempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startmessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "starttimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startsignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + } + ] + }, + canvas = { + id: "menuCanvas", + width: 150, + items: [ + { + id: "menuEditProcess", + text: "Edit Process".translate(), + onClick: function (menuOption) { + PMDesigner.propertiesProcess(); + } + }, + { + id: "menuGridLines", + text: "Enable Grid Lines".translate(), + onClick: function () { + var canvas = PMUI.getActiveCanvas(); + if (canvas.toogleGridLine()) { + this.setText("Disable Grid Lines".translate()); + } else { + this.setText("Enable Grid Lines".translate()); + } + } + } + ], + onShow: function (menu) { + var canvas = PMUI.getActiveCanvas(); + if (canvas.currentConnection) { + canvas.currentConnection.hidePortsAndHandlers(); + } + if (canvas.isGridLine) { + menu.items.find('id', 'menuGridLines').setText("Disable Grid Lines".translate()); + } + + } + }, + task = { + id: "menuTask", + items: [ + { + id: "taskType", + text: "Task Type".translate(), + items: [ + { + id: "empty", + text: "Empty Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "sendtask", + text: "Send Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "receivetask", + text: "Receive Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "usertask", + text: "User Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "servicetask", + text: "Service Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "scripttask", + text: "Script Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "manualtask", + text: "Manual Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "businessrule", + text: "Business Rule Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + } + ] + }, + { + id: "loopType", + text: "Marker Type".translate(), + items: [ + { + id: "empty", + text: "None".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "loop", + text: "Loop".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "parallel", + text: "Parallel".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "sequential", + text: "Sequential".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + } + ] + }, + { + id: "menuTaskSteps", + text: "Steps".translate(), + icon: "mafe-menu-task-steps", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + } + } + }, + { + id: "menuTaskAssignedRules", + text: "Assignment Rules".translate(), + icon: "mafe-menu-users-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuTaskProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + + if (targetElement.act_task_type == "SCRIPTTASK") { + menu.getItems()[1].setVisible(false); + menu.getItems()[2].setVisible(false); + menu.getItems()[3].setVisible(false); + } else { + menu.getItems()[1].setVisible(true); + menu.getItems()[2].setVisible(true); + menu.getItems()[3].setVisible(true); + } + + if (targetElement.act_task_type == "MANUALTASK" || targetElement.act_task_type == "USERTASK" || targetElement.act_task_type == "EMPTY") { + menu.getItems()[1].getItems()[2].setVisible(true); + } else { + menu.getItems()[1].getItems()[2].setVisible(false); + } + } + }, + subProcess = { + id: "menuSubProcess", + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas + .hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete Routing Rule".translate(), + icon: "mafe-menu-delete-rules-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuSubProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + } + }, + start = { + id: 'menuStart', + items: [ + startCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuStartWebEntry", + text: "Web Entry".translate(), + icon: "mafe-menu-start-message-view", + //visible: false, + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"), webEntry; + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + var webEntry; + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + } + } + }, + { + id: "menuStartProperties", + text: "Properties".translate(), + icon: "mafe-menu-start-message-view", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + shape, + propertyMap = ['MESSAGECATCH', 'TIMER']; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (targetElement.evn_marker == 'TIMER') { + } + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (targetElement.evn_marker === 'MESSAGECATCH') { + var dt = menu.getItems(); + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(true); + } + } + } + //disabled weebentry for others pmEvent no support + if (targetElement.getPorts().asArray().length) { + shape = targetElement.getPorts().getFirst().getConnection().getDestPort().parent; + if (shape && (shape instanceof PMActivity) && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else if (shape && (shape instanceof PMEvent) && shape.evn_marker === "EMAIL" + && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + + //Enable && Disabled - Properties + if (targetElement.evn_type === "START" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuStartProperties').enable(); + } else { + menu.items.find('id', 'menuStartProperties').disable(); + } + }, + onHide: function (menu) { + var dt = menu.getItems(), i; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(false); + } + } + } + }, + end = { + id: 'menuEnd', + items: [ + endMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuEndProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var propertyMap = ['MESSAGETHROW', 'EMAIL'], + targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + + + //Enable && Disabled - Properties + if (targetElement.evn_type === "END" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuEndProperties').enable(); + } else { + menu.items.find('id', 'menuEndProperties').disable(); + } + } + }, + selection = { + id: 'menuSelection', + items: [ + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action" + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action" + } + ] + }, + evaluation = { + id: 'menuEvaluation', + items: [ + + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + } + ] + }, + parallel = { + id: 'menuParallel', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + listeners: {}, + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + } + }, + exclusive = { + id: 'menuExclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + + } + }, + inclusive = { + id: 'menuInclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: 'Properties'.translate(), + icon: 'mafe-menu-properties-action', + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + } + }, + complex = { + id: 'menuComplex', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.complexRoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + group = { + id: 'menuLine', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataObject = { + id: 'menuDataObject', + items: [ + { + id: "dataType", + text: "Data Type".translate(), + items: [ + { + id: "dataobject", + text: "Data Empty".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOBJECT'); + } + }, + { + id: "datainput", + text: "Data Input".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAINPUT'); + } + }, + { + id: "dataoutput", + text: "Data Output".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOUTPUT'); + } + } + ] + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataStore = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + textAnnotation = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + intermediate = { + id: 'intermediate', + items: [ + intermediateCatchMarker, + intermediateThrowMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "intermediateProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + propertyEnabled = ['MESSAGECATCH', 'MESSAGETHROW', 'EMAIL', 'TIMER']; + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (targetElement.evn_behavior === 'CATCH') { + targetElement.menu.getItems()[0].setVisible(true); + targetElement.menu.getItems()[1].setVisible(false); + } else { + targetElement.menu.getItems()[0].setVisible(false); + targetElement.menu.getItems()[1].setVisible(true); + } + + //Enable && Disabled - Properties + if (propertyEnabled.indexOf(targetElement.evn_marker) >= 0) { + + menu.items.find('id', 'intermediateProperties').enable(); + } else { + menu.items.find('id', 'intermediateProperties').disable(); + } + } + }, + boundary = { + id: 'menuDataObject', + items: [ + boundaryCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + } + }, + participant = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }; + var defaults = { + factory: { + products: { + 'CANVAS': canvas, + 'TASK': task, + 'SUB_PROCESS': subProcess, + 'START': start, + 'END': end, + 'SELECTION': selection, + 'EVALUATION': evaluation, + 'PARALLEL': parallel, + 'EXCLUSIVE': exclusive, + 'EVENTBASED': exclusive, + 'EXCLUSIVEEVENTBASED': exclusive, + 'PARALLELEVENTBASED': exclusive, + 'INCLUSIVE': inclusive, + 'COMPLEX': complex, + 'VERTICAL_LINE': group, + 'HORIZONTAL_LINE': group, + 'GROUP': group, + 'LANE': participant, + 'DATAOBJECT': dataObject, + 'DATASTORE': dataStore, + 'TEXT_ANNOTATION': textAnnotation, + 'V_LABEL': textAnnotation, + 'H_LABEL': textAnnotation, + 'INTERMEDIATE': intermediate, + 'BOUNDARY': boundary, + 'PARTICIPANT': participant, + 'POOL': participant + }, + + defaultProduct: 'START' + } + }; + + PMDesigner.contextMenuFactory = new ContextMenu(defaults.factory); + PMDesigner.getMenuFactory = function (type) { + if (prj_readonly === 'true') { + return {}; + } + return PMDesigner.contextMenuFactory.getProduct(type); + }; + /** + * Change task type marker + * @param menuOption + */ + function handlerMarkerType(menuOption) { + var result = true, + tempType = menuOption.getMenuTargetElement().getTaskType(); + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().switchTaskType(menuOption.id.toUpperCase()); + + //validate if act loop type is parallel + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + handlerMarkerLoopType(menuOption, tempType) + } + + //to enable save button + PMDesigner.project.updateElement([]); + + } + + /** + * Change marker loop type + * @param menuOption + * @param type + * @returns {boolean} + */ + function handlerMarkerLoopType(menuOption, type) { + var message_window, + loopType = menuOption.id.toUpperCase(), + taskType = menuOption.getMenuTargetElement().act_task_type; + if (typeof type !== 'undefined' && type !== null) { + taskType = type; + } + + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + + message_window = new PMUI.ui.MessageWindow({ + id: "handlerMarkerType", + width: 490, + title: 'Parallel Marker Type'.translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: "The configuring of multiple instances will be lost".translate(), + footerItems: [ + { + text: 'Cancel'.translate(), + handler: function () { + menuOption.getMenuTargetElement().switchLoopType('PARALLEL'); + menuOption.getMenuTargetElement().switchTaskType(taskType); + message_window.close(); + return false; + }, + buttonType: "error" + }, + { + text: 'Continue'.translate(), + handler: function () { + try { + if (loopType == "loop" || loopType == "sequential") { + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + } else { + menuOption.getMenuTargetElement().switchLoopType('EMPTY'); + } + PMDesigner.project.updateElement([]); + } catch (e) { + console.error("loop marker error", e.message); + } + message_window.close(); + return true; + }, + buttonType: "success" + } + + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + PMDesigner.project.updateElement([]); + return true; + } + } + +}()); + +(function () { + PMDesigner.shapeFactory = function (type, options) { + var customshape = null, + menuShape, + defaultOptions = null, + canvasName, + name, + id, + classEvent = "start", + pmCanvas = this.canvas, + corona = PMDesigner.defaultCrown, + wildcard; + + canvasName = new IncrementNameCanvas(pmCanvas); + name = canvasName.get(type); + + if (typeof options === 'undefined') { + options = {}; + if (type === 'START_MESSAGE') { + type = 'START'; + classEvent = "message"; + options.evn_marker = 'MESSAGECATCH'; + } + if (type === 'START_TIMER') { + type = 'START'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } + + if (type === 'END_MESSAGE') { + type = 'END'; + classEvent = "message"; + options.evn_marker = 'MESSAGETHROW'; + } + if (type === 'END_EMAIL') { + type = 'END'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_SENDMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "sendmessage"; + options.evn_marker = 'MESSAGETHROW'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_RECEIVEMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "receivemessage"; + options.evn_marker = 'MESSAGECATCH'; + options.evn_behavior = 'CATCH'; + } + if (type === 'INTERMEDIATE_EMAIL') { + type = 'INTERMEDIATE'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_TIMER') { + type = 'INTERMEDIATE'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } + if (type === 'BOUNDARY_EVENT') { + type = 'BOUNDARY'; + classEvent = "receivemessage"; + options.evn_marker = 'EMPTY'; + options.evn_behavior = 'CATCH'; + } + + switch (type) { + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': + options.gat_type = type; + break; + } + } + if (type === 'DATAOBJECT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataobject'; + } + if (type === 'DATAINPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'datainput'; + } + if (type === 'DATAOUTPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataoutput'; + } + + wildcard = [ + { + name: 'wildcard'.translate(), + className: 'mafe-wildcard', + onClick: null, + column: 2 + } + ]; + + switch (type) { + case 'TASK': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'TASK', + act_name: name, + act_task_type: 'EMPTY', + act_loop_type: 'EMPTY', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ + { + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-task' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'USERTASK', + x: 10, + y: 10, + position: 0, + markerZoomClasses: [] + }, + { + markerType: 'EMPTY', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [] + } + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ], + markerZoomClassesWarning: [ + "mafe-style-warning-marker-7", + "mafe-style-warning-marker-10", + "mafe-style-warning-marker-14", + "mafe-style-warning-marker-17", + "mafe-style-warning-marker-21" + ] + } + } + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + defaultOptions.markers[1] + .markerZoomClasses = PMDesigner.updateLoopLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'SUB_PROCESS': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'SUB_PROCESS', + act_loop_type: 'EMPTY', + act_name: name, + act_task_type: 'COLLAPSED', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ + { + message: name, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-subprocess' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'COLLAPSED', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [ + "mafe-collapsed-marker-10", + "mafe-collapsed-marker-15", + "mafe-collapsed-marker-21", + "mafe-collapsed-marker-26", + "mafe-collapsed-marker-31" + ] + } + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'START': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'START', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'catch', + evn_message: 'LEAD', + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-start'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-start-empty-16', + 'mafe-event-start-empty-24', + 'mafe-event-start-empty-33', + 'mafe-event-start-empty-41', + 'mafe-event-start-empty-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + case 'INTERMEDIATE': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'INTERMEDIATE', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-intermediate'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + case 'BOUNDARY': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'BOUNDARY', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + style: { + cssClasses: ['mafe-event-boundary'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + drag: 'nodrag' + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + + case 'END': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'END', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'throw', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-end'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-end-empty-16', + 'mafe-event-end-empty-24', + 'mafe-event-end-empty-33', + 'mafe-event-end-empty-41', + 'mafe-event-end-empty-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + canvas: pmCanvas, + width: 41, + height: 41, + gat_type: 'EXCLUSIVE', + gat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-gateway-exclusive-20', + 'mafe-gateway-exclusive-30', + 'mafe-gateway-exclusive-41', + 'mafe-gateway-exclusive-51', + 'mafe-gateway-exclusive-61' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateGatewayLayerClasses(defaultOptions); + customshape = new PMGateway(defaultOptions); + break; + case 'GROUP': + defaultOptions = { + art_name: name, + art_type: 'GROUP', + canvas: pmCanvas, + width: 200, + height: 100, + style: { + cssClasses: ['mafe-artifact-group'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "background-layer", + priority: 1, + visible: true, + style: { + cssClasses: [ + 'mafe-artifact-group' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'annotationResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + } + }, + labels: [ + { + message: "", + width: 0, + height: 0, + position: { + location: 'top', + diffX: 2, + diffY: 0 + }, + attachEvents: false, + updateParent: true, + style: { + cssClasses: [ + 'mafe-label-annotation' + ] + } + } + ], + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMArtifact(defaultOptions); + break; + case 'TEXT_ANNOTATION': + defaultOptions = { + art_name: name, + art_type: 'TEXT_ANNOTATION', + canvas: pmCanvas, + width: 100, + height: 30, + style: { + cssClasses: ['mafe-artifact-annotation'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "background-layer", + priority: 1, + visible: true, + style: { + cssClasses: [ + 'mafe-artifact-annotation' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'annotationResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + } + }, + labels: [ + { + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false, + updateParent: true + } + ], + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMArtifact(defaultOptions); + break; + + case 'DATAOBJECT': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + canvas: pmCanvas, + width: 33, + height: 41, + dat_type: 'DATAOBJECT', + dat_object_type: "dataobject", + dat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-dataobject-50', + 'mafe-dataobject-75', + 'mafe-dataobject-100', + 'mafe-dataobject-125', + 'mafe-dataobject-150' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + markers: [ + { + markerType: 'USERTASK', + x: 10, + y: 10, + position: 0 + } + ], + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateDataMarkerLayerClasses(defaultOptions); + customshape = new PMData(defaultOptions); + break; + + case 'DATASTORE': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + canvas: pmCanvas, + width: 41, + height: 41, + dat_type: 'DATASTORE', + dat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-datastore-20', + 'mafe-datastore-30', + 'mafe-datastore-41', + 'mafe-datastore-51', + 'mafe-datastore-61' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMData(defaultOptions); + break; + case 'PARTICIPANT': + defaultOptions = { + width: 500, + height: 130, + "canvas": this, + "connectAtMiddlePoints": false, + topLeft: true, + connectionType: 'dotted', + resizeBehavior: "participantResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + "style": { + cssClasses: ["mafe-pool"] + + }, + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + }, + attachEvents: false + } + ], + par_name: name, + corona: corona, + focusLabel: true + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMParticipant(defaultOptions); + break; + case 'POOL': + if (options.lns_name) { + name = options.lns_name; + } else if (options.par_name) { + name = options.par_name; + } + defaultOptions = { + width: 700, + height: 200, + "canvas": pmCanvas, + "connectAtMiddlePoints": false, + topLeft: false, + connectionType: 'dotted', + resizeBehavior: "poolResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmcontainer", + selectors: [ + "#TASK", + "#SUB_PROCESS", + "#START", + "#START_MESSAGE", + "#START_TIMER", + "#END", + "#END_MESSAGE", + "#END_EMAIL", + "#INTERMEDIATE_SENDMESSAGE", + "#INTERMEDIATE_RECEIVEMESSAGE", + "#INTERMEDIATE_EMAIL", + "#INTERMEDIATE_TIMER", + "#EXCLUSIVE", + "#PARALLEL", + "#INCLUSIVE", + "#DATAOBJECT", + "#DATASTORE", + "#TEXT_ANNOTATION", + "#LANE", + "#GROUP", + ".mafe-event-start", + ".mafe-event-intermediate", + ".mafe-event-end", + ".pmui-pmactivity", + ".pmui-pmgateway", + ".pmui-pmdata", + ".mafe-artifact-annotation", + ".mafe-artifact-group", + ".port" + ] + }, + container: "pool", + "style": { + cssClasses: ["mafe-pool"] + + }, + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + }, + attachEvents: false + } + ], + lns_name: name, + focusLabel: true, + corona: corona + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMPool(defaultOptions); + break; + case 'LANE': + defaultOptions = { + width: 500, + height: 200, + "canvas": pmCanvas, + "connectAtMiddlePoints": false, + topLeft: true, + connectionType: 'dotted', + resizeBehavior: "laneResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmcontainer", + selectors: [ + "#TASK", + "#SUB_PROCESS", + "#START", + "#START_MESSAGE", + "#START_TIMER", + "#END", + "#END_MESSAGE", + "#END_EMAIL", + "#INTERMEDIATE_SENDMESSAGE", + "#INTERMEDIATE_RECEIVEMESSAGE", + "#INTERMEDIATE_EMAIL", + "#INTERMEDIATE_TIMER", + "#EXCLUSIVE", + "#PARALLEL", + "#INCLUSIVE", + "#DATAOBJECT", + "#DATASTORE", + "#GROUP", + "#TEXT_ANNOTATION", + ".mafe-event-start", + ".mafe-event-intermediate", + ".mafe-event-end", + ".pmui-pmactivity", + ".pmui-pmgateway", + ".pmui-pmdata", + ".mafe-artifact-annotation", + ".mafe-artifact-group" + ] + }, + container: "lane", + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + } + + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + } + } + ], + lan_name: name, + focusLabel: true + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMLane(defaultOptions); + break; + + } + if (customshape && !pmCanvas.readOnly) { + customshape.attachListeners(); + customshape.extendedType = type; + menuShape = PMDesigner.getMenuFactory(type); + customshape.getHTML(); + customshape.setContextMenu(menuShape); + } + return customshape; + }; + PMDesigner.updateLayerClasses = function (options) { + return [ + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-16', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-24', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-33', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-41', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-49' + ]; + }; + PMDesigner.updateGatewayLayerClasses = function (options) { + return [ + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-20', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-30', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-41', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-51', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-61' + ]; + }; + PMDesigner.updateMarkerLayerClasses = function (options) { + if (options.act_task_type !== 'EMPTY') { + return [ + "mafe-" + options.act_task_type.toLowerCase() + "-marker-10", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-15", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-21", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-26", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-31" + ]; + } + }; + PMDesigner.updateLoopLayerClasses = function (options) { + if (options.act_loop_type !== 'EMPTY') { + return [ + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-10", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-15", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-21", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-26", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-31" + ]; + } + }; + PMDesigner.updateDataMarkerLayerClasses = function (options) { + var type = options.dat_object_type.toLowerCase(); + if (type !== 'dataobject') { + return [ + "mafe-" + type + "-marker-10", + "mafe-" + type + "-marker-15", + "mafe-" + type + "-marker-21", + "mafe-" + type + "-marker-26", + "mafe-" + type + "-marker-31" + ]; + } + }; + /** + * Save a process and open the settings + * @param shape + * @param callback + */ + PMDesigner.saveAndOpenSettings= function (shape, callback) { + var splitedID; + + if(shape) { + splitedID = shape.getID().split("-"); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + if(callback) { + callback(shape); + } + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + callback(shape); + } + } + + + }; +}()); +PMDesigner.sidebar = []; + +PMDesigner.sidebar.push( + new ToolbarPanel({ + buttons: [ + { + selector: 'TASK', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-task' + ], + tooltip: "Task".translate() + }, + { + selector: 'SUB_PROCESS', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-subprocess' + ], + tooltip: "Sub Process".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'EXCLUSIVE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-exclusive' + ], + tooltip: "Exclusive Gateway".translate() + }, + { + selector: 'PARALLEL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-parallel' + ], + tooltip: "Parallel gateway".translate() + }, + { + selector: 'INCLUSIVE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-inclusive' + ], + tooltip: "Inclusive Gateway".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'START', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-start' + ], + tooltip: "Start Event".translate() + }, + { + selector: 'START_TIMER', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-event-start-timer' + ], + tooltip: "Start Timer Event".translate() + }, + { + selector: 'INTERMEDIATE_EMAIL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-intermediate-send-mesage' + ], + tooltip: "Intermediate Email Event".translate() + }, + { + selector: 'INTERMEDIATE_TIMER', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-event-intermediate-timer' + ], + tooltip: "Intermediate Timer Event".translate() + }, + { + selector: 'END', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-end' + ], + tooltip: "End Event".translate() + }, + { + selector: 'END_EMAIL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-end-message' + ], + tooltip: "End Email Event ".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'DATAOBJECT', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-data-object' + ], + tooltip: "Data Object".translate() + }, + { + selector: 'DATASTORE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-data-store' + ], + tooltip: "Data Store".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'PARTICIPANT', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-blackbox' + ], + tooltip: " Black Box Pool".translate() + }, + { + selector: 'POOL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-pool' + ], + tooltip: "Pool".translate() + }, + { + selector: 'LANE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-lane' + ], + tooltip: "Lane".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'GROUP', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-group' + ], + tooltip: "Group".translate() + }, + { + selector: 'TEXT_ANNOTATION', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-annotation' + ], + tooltip: "Text Annotation".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'LASSO', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-lasso' + ], + tooltip: "Lasso".translate() + } + + ] + }) +); +ListDynaform = function () { + this.superTitle = 'Dynaforms'.translate(); + this.tableContainerHeight = 374; + this.buttonCreate = null; + this.onCreate = new Function(); + this.onShowId = new Function(); + this.onEdit = new Function(); + this.onDel = new Function(); + this.loaded = false; + this.clickedClose = true; + Mafe.Grid.call(this); + ListDynaform.prototype.init.call(this); +}; +ListDynaform.prototype = new Mafe.Grid(); +ListDynaform.prototype.init = function () { + var that = this; + that.buttonCreate = new PMUI.ui.Button({ + id: 'dynaformButtonNew', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: {cssClasses: ['mafe-button-create']}, + handler: function (event) { + that.onCreate(event); + } + }); + that.buttonCreate.defineEvents(); + that.setID('idListDynaform'); + that.setColumns([{ + id: 'copyuid', + title: 'Show ID'.translate(), + dataType: 'button', + buttonLabel: 'Show ID'.translate(), + buttonStyle: {cssClasses: ['mafe-button-show']}, + onButtonClick: function (row, grid) { + that.onShowId(row, grid); + } + }, { + id: 'dynaformGridPanelTitle', + title: 'Title'.translate(), + dataType: 'string', + width: '460px', + alignmentCell: 'left', + sortable: true, + columnData: 'dyn_title' + }, { + id: 'dynaformGridPanelEdit', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-edit']}, + buttonLabel: function (row, data) { + return 'Edit'.translate(); + }, + onButtonClick: function (row, grid) { + that.onEdit(row, grid); + } + }, { + id: 'dynaformGridPanelDelete', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-delete']}, + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + onButtonClick: function (row, grid) { + that.onDel(row, grid); + } + } + ]); +}; +ListDynaform.prototype.createHTML = function () { + Mafe.Grid.prototype.createHTML.call(this); + this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); + return this.html; +}; +ListDynaform.prototype.load = function () { + var that = this; + that.clearItems(); + (new PMRestClient({ + endpoint: 'dynaforms', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.setDataItems(response); + that.sort('dyn_title', 'asc'); + that.loaded = true; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + that.loaded = false; + }, + messageError: 'There are problems getting the list of dynaforms, please try again.'.translate() + })).executeRestClient(); +}; +ListDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +BlankDynaform = function () { + this.superTitle = 'Create Blank Dynaform'.translate(); + this.onSave = new Function(); + this.onSaveOpen = new Function(); + this.onCancel = new Function(); + this.buttons = null; + Mafe.Form.call(this); + BlankDynaform.prototype.init.call(this); +}; +BlankDynaform.prototype = new Mafe.Form(); +BlankDynaform.prototype.init = function () { + var that = this; + that.setID('formDynaformInformation'); + that.setTitle('Dynaform Information'.translate()); + that.setItems([{ + id: 'formDynaformInformationTitle', + pmType: 'text', + label: 'Title'.translate(), + value: '', + maxLength: 255, + placeholder: 'The Dynaform title'.translate(), + name: 'dyn_title', + required: true, + controlsWidth: 303 + }, { + id: 'formDynaformInformationDescription', + pmType: 'textarea', + rows: 200, + name: 'dyn_description', + width: 200, + label: 'Description'.translate(), + style: {cssClasses: ['mafe-textarea-resize']} + } + ]); + that.buttons = [ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSaveOpen', + text: 'Save & Open'.translate(), + buttonType: 'success', + handler: function () { + that.onSaveOpen(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSave', + text: 'Save'.translate(), + buttonType: 'success', + handler: function () { + that.onSave(); + } + }) + ]; +}; +BlankDynaform.prototype.getButtons = function () { + return this.buttons; +}; +BlankDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +Dynaform = function (settings) { + this.listDynaform = null; + this.blankDynaform = null; + Mafe.Window.call(this, settings); + Dynaform.prototype.init.call(this, settings); +}; +Dynaform.prototype = new Mafe.Window(); +Dynaform.prototype.init = function (settings) { + var that = this; + that.listDynaform = new ListDynaform(); + that.setOnBeforeCloseHandler(function () { + this.clickedClose = true; + if (!that.blankDynaform.isVisible()) { + that.close(); + } else { + that.blankDynaform.onCancel(); + } + }); + that.listDynaform.load(); + that.listDynaform.onShowId = function (row, grid) { + showUID(row.getData().dyn_uid); + }; + that.listDynaform.onCreate = function () { + that.resetView(); + that.setTitle(that.blankDynaform.getSuperTitle()); + that.blankDynaform.setVisible(true); + that.setButtons(that.blankDynaform.getButtons()); + }; + that.listDynaform.onEdit = function (row, grid) { + that.edit(row, grid); + }; + that.listDynaform.onDel = function (row, grid) { + that.del(row, grid); + }; + + that.blankDynaform = new BlankDynaform(); + that.blankDynaform.onSave = function () { + that.saveBlank(false); + }; + that.blankDynaform.onSaveOpen = function () { + that.saveBlank(true); + }; + that.blankDynaform.onCancel = function () { + $("input,select,textarea").blur(); + var title = ""; + that.blankDynaform.loseChanges(title); + }; + that.blankDynaform.onYesConfirmCancellation = function () { + if (that.clickedClose) { + that.close(); + } + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + }; + + that.addItem(that.listDynaform); + that.addItem(that.blankDynaform); + + that.open(); + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + + // hard coding dyn_title textfield because enter keypress reload the current page + if (that.blankDynaform.getItems()[0] + && that.blankDynaform.getItems()[0].controls[0] + && that.blankDynaform.getItems()[0].controls[0].html) { + $(that.blankDynaform.getItems()[0].controls[0].html).keypress(function (e) { + if (e.which == 13) { + e.preventDefault(); + } + }); + } +}; +Dynaform.prototype.saveBlank = function (open) { + var that = this, + data, + restClient, + flagAux; + + if (!that.blankDynaform.isValid()) { + flagAux = that.blankDynaform.visible; + } else { + flagAux = that.blankDynaform.isValid(); + } + + if (flagAux) { + if (getData2PMUI(that.blankDynaform.html).dyn_title == "") { + return false; + } + } + + data = getData2PMUI(that.blankDynaform.html); + data['dyn_version'] = 2; + data['dyn_type'] = 'xmlform'; + restClient = new PMRestClient({ + endpoint: 'dynaform', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + if (open) { + that.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(response); + } else { + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + that.listDynaform.load(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems creating the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform saved successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); +}; +Dynaform.prototype.edit = function (row, grid) { + this.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(row.getData()); +}; +Dynaform.prototype.del = function (row, grid) { + var that = this, + confirmDeletion = new Mafe.ConfirmDeletion(); + confirmDeletion.setMessage('Do you want to delete this DynaForm?'.translate()); + confirmDeletion.setTitle("Dynaform".translate()); + confirmDeletion.onDelete = function () { + var restClient = new PMRestClient({ + endpoint: 'dynaform/' + row.getData().dyn_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.listDynaform.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems deleting the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform deleted successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); + }; +}; + +(function () { + PMDesigner.dynaform = function () { + var dynaform = new Dynaform(); + }; + PMDesigner.dynaform.create = function () { + var dynaform = new Dynaform(); + dynaform.resetView(); + dynaform.setTitle(dynaform.blankDynaform.getSuperTitle()); + dynaform.blankDynaform.setVisible(true); + dynaform.setButtons(dynaform.blankDynaform.getButtons()); + }; +}()); + +/** + * Updates the granular export feature after enabled features are loaded. + */ +var navbarExportUpdate = function () { + //Code export - export granular (handler) + var handlerExportNormal = function () { + var ws = enviromentVariables('WORKSPACE'); + if (!HTTP_SERVER_HOSTNAME) { + HTTP_SERVER_HOSTNAME = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); + } + location.href = HTTP_SERVER_HOSTNAME + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + "/export?access_token=" + PMDesigner.project.keys.access_token; + }; + + var handlerExportGranular = function () { + var optionExportNormal = $("
" + "Normal".translate() + "
"), + optionExportGranular = $("
" + "Custom".translate() + "
"), + menuExport = $("").hide(), + $item = $("#idNavBar").find(".mafe-button-export-process").closest("li"); + + menuExport.append(optionExportNormal).append(optionExportGranular); + if (!$item.find(".mafe-button-menu-container").length) { + $item.append(menuExport); + } + $(".ui-tooltip").hide(); + $(menuExport).slideToggle("slow"); + $item.on("mouseleave", function (e) { + if ($(this).find(".mafe-button-menu-container").eq(0).is(":visible")) { + var that = this; + $(that).find(".mafe-button-menu-container").remove(); + } + }); + + $(".sub-nav").on("click", ".normalExport", function (event) { + var ws = enviromentVariables('WORKSPACE'), + locationOrigin; + if (!window.location.origin) { + locationOrigin = window.location.protocol + "//" + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { + locationOrigin = HTTP_SERVER_HOSTNAME; + } else { + locationOrigin = window.location.origin; + } + location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + "/export?access_token=" + PMDesigner.project.keys.access_token; + }); + + $(".sub-nav").on("click", ".granularExport", function (event) { + PMDesigner.granularProcessExport(); + }); + }; + if (inArray("jXsSi94bkRUcVZyRStNVExlTXhEclVadGRRcG9xbjNvTWVFQUF3cklKQVBiVT0=", ENABLED_FEATURES)) { + handler = handlerExportGranular; + } else { + handler = handlerExportNormal; + } + +}; + +function inArray(needle, haystack) { + var i, + length = haystack.length; + for (i = 0; i < length; i += 1) { + if (haystack[i] == needle) return true; + } + return false; +} + +var defaultNavbarPanelMenus = { + array: [], + init: function () { + var closeVar = { + id: 'closeButton', + name: 'Close', + htmlProperty: { + id: 'closeButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-close', + child: [ + { + element: 'span', + class: 'mafe-button-close' + } + ] + } + + ] + }, + actions: { + selector: ".mafe-button-close", + tooltip: "Close".translate(), + execute: true, + handler: function () { + var message_window, + browser = PMDesigner.getBrowser(), + url = parent.location.href; + + if (PMDesigner.project.isDirty() && !PMDesigner.project.isSave) { + var message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: "cancelSaveSubprocPropertiesWin", + title: PMDesigner.project.projectName, + message: 'Save your changes and exit ?'.translate(), + footerItems: [ + { + pmType: 'label', + text: ' ' + }, { + text: "No".translate(), + handler: function () { + PMDesigner.project.isClose = true; + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + window.close(); + } else { + parent.location.href = url; + } + }, + buttonType: "error" + }, + + { + text: "Yes".translate(), + handler: function () { + PMDesigner.project.saveClose(true); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + window.close(); + } else { + parent.location.href = url; + } + } + } + } + }, + helpVar = { + id: 'helpButton', + name: 'Help', + htmlProperty: { + id: 'helpButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-help', + child: [ + { + element: 'span', + class: 'mafe-toolbar-help' + } + ] + } + ] + }, + actions: { + selector: ".mafe-toolbar-help", + tooltip: "Help".translate(), + execute: true, + handler: function () { + var canvas = PMUI.getActiveCanvas(); + PMDesigner.helper.startIntro(); + if (canvas && canvas.getHTML()) { + canvas.getHTML().classList.remove("pmui-pmcanvas"); + } + } + } + }, + saveVar = { + id: 'saveButton', + name: 'Save', + htmlProperty: { + id: 'saveButton', + element: 'li', + class: 'mafe-save-process', + child: [ + { + element: 'a', + class: 'mafe-button-save' + }, + { + element: 'span', + class: 'mafe-button-menu', + child: [ + { + element: 'img', + src: '/lib/img/caret-down.png' + } + ] + } + ] + }, + actions: { + selector: ".mafe-button-save", + tooltip: "Save process".translate(), + label: { + text: "Save".translate() + }, + execute: true, + handler: function () { + if (PMDesigner.project.isDirty() && PMDesigner.project.isSave === false) { + PMDesigner.project.isSave = true; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].text = "Saving"; + PMDesigner.project.save(true); + } + } + } + }, + exportButton = { + id: 'exportButton', + name: 'ExportButton', + htmlProperty: { + id: 'exportButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-export-process' + } + ] + }, + actions: { + selector: ".mafe-button-export-process", + tooltip: "Export process".translate(), + label: { + text: "Export Process".translate() + }, + execute: true, + handler: function () { + handler(); + } + } + }, + exportBpmnButton = { + id: 'exportBpmnButton', + name: 'ExportBpmn', + htmlProperty: { + id: 'exportBpmnButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-export-bpmn-process' + } + ] + }, + actions: { + selector: ".mafe-button-export-bpmn-process", + tooltip: "Export Diagram ".translate(), + label: { + text: "Export Diagram".translate() + }, + execute: false, + handler: function () { + } + } + }, + zoomVar = { + id: 'zoomOptions', + name: 'Zoom', + htmlProperty: { + id: 'zoomOptions', + element: 'li', + child: [ + { + element: 'span', + class: 'mafe-zoom-options' + } + ] + }, + actions: { + id: 'zoomOptions', + spanclass: 'mafe-zoom-options', + actions: 'zoom' + }, + aditionalAction: { + execute: PMDesigner.ApplyOptionsZoom() + } + }, + undo = { + id: 'undoButton', + name: 'Undo', + htmlProperty: { + id: 'undoButton', + element: 'li', + class: 'mafe-undo', + child: [ + { + element: 'b', + class: 'mafe-action-undo', + child: [ + { + element: 'span', + class: 'mafe-button-undo' + } + ] + } + ] + }, + actions: { + selector: ".mafe-action-undo", + tooltip: "Undo Action".translate(), + label: { + text: '' + }, + execute: true, + handler: function () { + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().commandStack.undo(); + } + } + }, + redo = { + id: 'redoButton', + name: 'Redo', + htmlProperty: { + id: 'redoButton', + element: 'li', + class: 'mafe-redo', + child: [ + { + element: 'b', + class: 'mafe-action-redo', + child: [ + { + element: 'span', + class: 'mafe-button-redo' + } + ] + } + ] + }, + actions: { + selector: ".mafe-action-redo", + tooltip: "Redo Action".translate(), + label: { + text: '' + }, + execute: true, + handler: function () { + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().commandStack.redo(); + } + } + }, + fullScreen = { + id: 'fullScreenButton', + name: 'FullScreen', + htmlProperty: { + id: 'fullScreenButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-fullscreen' + } + ] + }, + actions: { + selector: ".mafe-button-fullscreen", + tooltip: "Full Screen".translate(), + execute: true, + handler: function () { + PMDesigner.fullScreen.toggle(this); + } + } + }; + navbarExportUpdate(); + this.array = [ + closeVar, + helpVar, + saveVar, + exportButton, + exportBpmnButton, + zoomVar, + undo, + redo, + fullScreen + ]; + }, + /** + * Get Array of Items of the NavBarPanelMenu + * @returns {Array} + */ + getNavBarPanelMenu: function () { + return this.array; + }, + /** + * Adds one Item To NavBarPanelMenu + * @param item + */ + addItemToNavBarPanelMenu: function (item) { + this.array.push(item); + } +}; + +defaultNavbarPanelMenus.init(); + +/** + * @class PMUI.menu.navBarPanel + * Handles the navbar panel of designer, + * contains all menus for content elements. + * + * @param {array} items Default items + * @constructor + */ +var NavbarPanel = function (items) { + NavbarPanel.prototype.init.call(this, items); +}; + +/** + * Initializes the object. + * + * @param {array} items Array with default values. + */ +NavbarPanel.prototype.init = function (items) { + var item; + if (typeof items === 'undefined') { + items = defaultNavbarPanelMenus.getNavBarPanelMenu(); + } + this.items = new PMUI.util.ArrayList(); + for (item in items) { + if (!items.hasOwnProperty(item)) { + continue; + } + this.items.insert(items[item]); + } +}; + +/** + * This method renders HTML and actions into designer + * + */ +NavbarPanel.prototype.show = function () { + var item = null, + i, + max; + if (PMDesigner.navbarPanel.items instanceof Object) { + for (i = 0, max = PMDesigner.navbarPanel.items.getSize(); i < max; i += 1) { + item = PMDesigner.navbarPanel.items.get(i); + if (typeof item.htmlProperty !== "undefined") { + PMDesigner.navbarPanel.buildHtmlElement(item.htmlProperty); + } + if (typeof item.aditionalAction !== "undefined") { + item.aditionalAction; + } + if (typeof item.actions !== "undefined") { + new PMAction(item.actions); + } + } + } else { + throw new Error('cannot show the elements of the List'); + } + +}; + +/** + * This method creates a html element button into the navBar Panel + * @param {Object} element + * @param {HTMLElement} before + */ +NavbarPanel.prototype.buildHtmlElement = function (element, before) { + var ul = document.getElementById('idNavBarList'), + htmlElement; + if ((typeof ul !== undefined) && (ul !== null)) { + htmlElement = this.getNodeChild(element, ul); + if (typeof before !== "undefined") { + before = document.getElementById(before); + ul.insertBefore(htmlElement, before); + } else { + ul.appendChild(htmlElement); + } + } + +}; + +/** + * This method assembling dependent html elements to the button + * @param {Object} nodeChild + * @param {HTMLElement} nodePattern + * @returns {Element} + */ +NavbarPanel.prototype.getNodeChild = function (nodeChild, nodePattern) { + var node = document.createElement(nodeChild.element), + i; + if (typeof nodeChild.id !== 'undefined') { + node.setAttribute("id", nodeChild.id); + } + if (nodeChild.element === 'a') { + node.setAttribute("href", "return;"); + } + if (typeof(nodeChild.class) !== 'undefined') { + node.setAttribute("class", nodeChild.class); + } + if (typeof(nodeChild.child) !== 'undefined' && nodeChild.child instanceof Array) { + for (i = 0; i < nodeChild.child.length; i += 1) { + this.getNodeChild(nodeChild.child[i], node); + } + } + if (typeof(nodeChild.src) !== 'undefined') { + node.setAttribute("src", nodeChild.src); + } + if ((typeof nodePattern !== undefined) && (nodePattern !== null) && nodePattern.localName !== 'ul') { + nodePattern.appendChild(node); + } + return node; +}; + +/** + * This method removes an html element for the + * NavBar panel array List and delete the HTML from the designer. + * @param {String} idButton + */ +NavbarPanel.prototype.deleteHtmlElement = function (idButton) { + var btn = document.getElementById(idButton), + element = PMDesigner.contentControl.items.find("id", idButton), + remove = PMDesigner.contentControl.items.remove(element); + if (typeof btn !== 'undefined' && remove === true) { + btn.parentNode.removeChild(btn); + } else { + throw new Error('Cannot find the specified button: ' + idButton + '. Please, review this'); + } +}; + +/** + * NavbarPanel get an instance + * @type {NavbarPanel} + */ +PMDesigner.navbarPanel = new NavbarPanel(defaultNavbarPanelMenus.getNavBarPanelMenu()); + +function defaultContentControlMenus() { + var variableCreate = { + id: 'variableCreate', + name: 'Variable', + htmlProperty: { + id: 'variableCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-variable' + }, + { + element: 'a', + class: 'btn_create mafe-menu-variable-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-variable", + label: { + text: "Variables".translate() + }, + execute: true, + handler: function () { + PMDesigner.variables(); + } + }, + createAction: { + selector: ".mafe-menu-variable-create", + label: { + selector: ".mafe-menu-variable-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.variables.create(); + } + } + }, + messageType = { + id: 'messageTypeCreate', + name: 'MessageType', + htmlProperty: { + id: 'messageTypeCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-messagetype' + }, + { + element: 'a', + class: 'btn_create mafe-menu-messagetype-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-messagetype", + label: { + text: "Message Types".translate() + }, + execute: true, + handler: function () { + PMDesigner.messageType(); + } + }, + createAction: { + selector: ".mafe-menu-messagetype-create", + label: { + selector: ".mafe-menu-messagetype-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.messageType.create(); + } + } + }, + dynaformCreate = { + id: 'dynaformCreate', + name: 'Dynaform', + htmlProperty: { + id: 'dynaformCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-dynaform' + }, + { + element: 'a', + class: 'btn_create mafe-menu-dynaform-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-dynaform", + label: { + text: "Dynaforms".translate() + }, + execute: true, + handler: function () { + PMDesigner.dynaform(); + } + }, + createAction: { + selector: ".mafe-menu-dynaform-create", + label: { + selector: ".mafe-menu-dynaform-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.dynaform.create(); + } + } + }, + inputDocumentCreate = { + id: 'inputDocumentCreate', + name: 'InputDocument', + htmlProperty: { + id: 'inputDocumentCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-inputdocuments' + }, + { + element: 'a', + class: 'btn_create mafe-menu-inputdocuments-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-inputdocuments", + label: { + text: "Input Documents".translate() + }, + execute: true, + handler: function () { + var inputDocument = new InputDocument(); + inputDocument.build(); + } + }, + createAction: { + selector: ".mafe-menu-inputdocuments-create", + label: { + selector: ".mafe-menu-inputdocuments-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + var inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.method = "POST"; + } + } + }, + outputDocumentCreate = { + id: 'outputDocumentCreate', + name: 'OutputDocument', + htmlProperty: { + id: 'outputDocumentCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-outputdocuments' + }, + { + element: 'a', + class: 'btn_create mafe-menu-outputdocuments-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-outputdocuments", + label: { + text: "Output Documents".translate() + }, + execute: true, + handler: function () { + PMDesigner.output(); + } + }, + createAction: { + selector: ".mafe-menu-outputdocuments-create", + label: { + selector: ".mafe-menu-outputdocuments-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.output(); + PMDesigner.output.create(); + } + } + }, + triggerCreate = { + id: 'triggerCreate', + name: 'Trigger', + htmlProperty: { + id: 'triggerCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-triggers' + }, + { + element: 'a', + class: 'btn_create mafe-menu-triggers-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-triggers", + label: { + text: "Triggers".translate() + }, + execute: true, + handler: function () { + PMDesigner.trigger(); + } + }, + createAction: { + selector: ".mafe-menu-triggers-create", + label: { + selector: ".mafe-menu-triggers-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.trigger(); + PMDesigner.trigger.create(); + } + } + }, + reportTableCreate = { + id: 'reportTableCreate', + name: 'ReportTable', + htmlProperty: { + id: 'reportTableCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-reporttables' + }, + { + element: 'a', + class: 'btn_create mafe-menu-reporttables-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-reporttables", + label: { + text: "Report Tables".translate() + }, + execute: true, + handler: function () { + PMDesigner.reporttable(); + } + }, + createAction: { + selector: ".mafe-menu-reporttables-create", + label: { + selector: ".mafe-menu-reporttables-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.reporttable(); + PMDesigner.reporttable.create(); + } + } + }, + databaseCreate = { + id: 'databaseCreate', + name: 'Database', + htmlProperty: { + id: 'databaseCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-databaseconnections' + }, + { + element: 'a', + class: 'btn_create mafe-menu-databaseconnections-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-databaseconnections", + label: { + text: "Database Connections".translate() + }, + execute: true, + handler: function () { + PMDesigner.database(); + } + }, + createAction: { + selector: ".mafe-menu-databaseconnections-create", + label: { + selector: ".mafe-menu-databaseconnections-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.database.create(); + } + } + }, + templateCreate = { + id: 'templateCreate', + name: 'TemplateCreate', + htmlProperty: { + id: 'templateCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-templates' + }, + { + element: 'a', + class: 'btn_create mafe-menu-templates-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-templates", + label: { + text: "Templates".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager("templates", "CREATION_NORMAL"); + } + }, + createAction: { + selector: ".mafe-menu-templates-create", + label: { + selector: ".mafe-menu-templates-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager.createFirst("templates", "CREATION_MORE"); + } + } + }, + menuPublic = { + id: 'menuPublic', + name: 'MenuPublic', + htmlProperty: { + id: 'menuPublic', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-public' + }, + { + element: 'a', + class: 'btn_create mafe-menu-public-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-public", + label: { + text: "Public Files".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager("public", "CREATION_NORMAL"); + } + }, + createAction: { + selector: ".mafe-menu-public-create", + label: { + selector: ".mafe-menu-public-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager.createFirst("public", "CREATION_MORE"); + } + } + }, + menuPermission = { + id: 'menuPermission', + name: 'MenuPermission', + htmlProperty: { + id: 'menuPermission', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-permissions' + }, + { + element: 'a', + class: 'btn_create mafe-menu-permissions-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-permissions", + label: { + text: "Permissions".translate() + }, + execute: true, + handler: function () { + PMDesigner.processPermissions(); + } + }, + createAction: { + selector: ".mafe-menu-permissions-create", + label: { + selector: ".mafe-menu-permissions-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.processPermissions.create(); + } + } + }, + menuCaseTracker = { + id: 'menuCaseTracker', + name: 'CaseTracker', + htmlProperty: { + id: 'menuCaseTracker', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-casetracker' + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-casetracker", + label: { + text: "Case Tracker".translate() + }, + execute: true, + handler: function () { + PMDesigner.caseTracker(); + } + } + }, + menuSupervisor = { + id: 'menuSupervisor', + name: 'MenuSupervisor', + htmlProperty: { + id: 'menuSupervisor', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-supervisors' + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-supervisors", + label: { + text: "Supervisors".translate() + }, + execute: true, + handler: function () { + PMDesigner.assigmentSupervisors(); + } + } + }; + + return [ + variableCreate, + messageType, + dynaformCreate, + inputDocumentCreate, + outputDocumentCreate, + triggerCreate, + reportTableCreate, + databaseCreate, + templateCreate, + menuPublic, + menuPermission, + menuCaseTracker, + menuSupervisor + ]; +}; + +/** + * @class PMUI.menu.contentControl + * Handles the content control menu of designer, + * contains all menus for content elements. + * + * @param {array} items Default items + * @constructor + */ +var ContentControl = function (items) { + ContentControl.prototype.init.call(this, items); +}; + +/** + * Initializes the object. + * + * @param {array} items Array with default values. + */ +ContentControl.prototype.init = function (items) { + this.items = new PMUI.util.ArrayList(); + if (typeof items === 'undefined') { + items = defaultContentControlMenus(); + } + for (var item in items) { + if (!items.hasOwnProperty(item)) { + continue; + } + this.items.insert(items[item]); + } +}; + +/** + * This method renders HTML and actions into designer + * + */ +ContentControl.prototype.show = function () { + var item = null, + i, + max; + if (this.items instanceof Object) { + for (i = 0, max = this.items.getSize(); i < max; i += 1) { + item = this.items.get(i); + if (typeof item.htmlProperty !== "undefined") { + this.buildHtmlElement(item.htmlProperty); + } + if (typeof item.actions !== "undefined") { + new PMAction(item.actions); + } + if (typeof item.createAction !== "undefined") { + new PMAction(item.createAction); + } + } + } else { + throw new Error('Cannot show the elements of the List'); + } +}; + +/** + * This method creates a html element button into the content + * control panel. + * @param {Object} element + * @param {HTMLElement} before + */ +ContentControl.prototype.buildHtmlElement = function (element, before) { + var ul = document.getElementById('contentControlList'), + htmlElement; + if ((typeof ul !== undefined) && (ul !== null)) { + htmlElement = this.getNodeChild(element, ul); + if (typeof before !== "undefined") { + before = document.getElementById(before); + ul.insertBefore(htmlElement, before); + } else { + ul.appendChild(htmlElement); + } + } + +}; + +/** + * This method assembling dependent html elements to the button + * @param {Object} nodeChild + * @param {HTMLElement} nodePattern + * @returns {Element} + */ +ContentControl.prototype.getNodeChild = function (nodeChild, nodePattern) { + var node = document.createElement(nodeChild.element), + i; + if (typeof nodeChild.id !== 'undefined') { + node.setAttribute("id", nodeChild.id); + } + if (nodeChild.element === 'a') { + node.setAttribute("href", "#"); + } + if (typeof(nodeChild.class) !== 'undefined') { + node.setAttribute("class", nodeChild.class); + } + if (typeof(nodeChild.child) !== 'undefined' && nodeChild.child instanceof Array) { + for (i = 0; i < nodeChild.child.length; i += 1) { + this.getNodeChild(nodeChild.child[i], node); + } + } + if (typeof(nodeChild.src) !== 'undefined') { + node.setAttribute("src", nodeChild.src); + } + if ((typeof nodePattern !== undefined) && (nodePattern !== null) && nodePattern.localName !== 'ul') { + nodePattern.appendChild(node); + } + return node; +}; + +/** + * This method removes an html element for the + * Content Control panel array List and delete the HTML from the designer. + * @param {String} idButton + */ +ContentControl.prototype.deleteHtmlElement = function (idButton) { + var btn = document.getElementById(idButton), + element = this.items.find("id", idButton), + remove = this.items.remove(element); + if (typeof btn !== 'undefined' && remove === true) { + btn.parentNode.removeChild(btn); + } else { + throw new Error('Cannot find the specified button: ' + idButton + '. Please, review this'); + } +}; + +/** + * ContentControl get an instance + * @type {ContentControl} + */ +PMDesigner.contentControl = new ContentControl(defaultContentControlMenus()); + +/** + * Input Document module + * @param options + * @constructor + */ +var InputDocument = function (options) { + this.winMainInputDocument = null; + this.externalType = false; + this.inputDocumentOriginDataForUpdate = {}; + this.windowDialog = null; + this.assignAccordion = null; + this.clickedClose = true; + this.onUpdateInputDocumentHandler = null; + InputDocument.prototype.init.call(this, options); +}; +/** + * set close modulo InputDocument constructor + * @param handler, the callback function + */ +InputDocument.prototype.setOnUpdateInputDocumentHandler = function (handler) { + if (typeof handler === "function") { + this.onUpdateInputDocumentHandler = handler; + } + return this; +}; +/** + * constructor + * @param options + */ +InputDocument.prototype.init = function (options) { + var defaults = { + onUpdateInputDocumentHandler: null + }; + $.extend(true, defaults, options); + this.setOnUpdateInputDocumentHandler(defaults.onUpdateInputDocumentHandler); + return this; +}; + +/** + * Puts input document using rest proxy, to update data + * @param inputDocumentUid + * @param data + */ +InputDocument.prototype.inputDocumentPutRestProxy = function (inputDocumentUid, data) { + var that = this, + restProxy; + + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + var message; + if (!that.externalType) { + if (typeof flagInputDocument != 'undefined' && flagInputDocument) { + that.winMainInputDocument.close(); + return; + } + that.inputDocumentsGetRestProxy(); + that.openGridPanelInMainWindow(); + } else { + that.winMainInputDocument.close(); + message = new PMUI.ui.FlashMessage({ + message: 'Input Document edited correctly.'.translate(), + duration: 3000, + severity: 'success', + appendTo: that.windowDialog + }); + message.show(); + } + if (typeof that.onUpdateInputDocumentHandler === "function") { + that.onUpdateInputDocumentHandler(data, that); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document updated successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Deletes an input document + * @param inputDocumentUid + */ +InputDocument.prototype.inputDocumentDeleteRestProxy = function (inputDocumentUid) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.inputDocumentsGetRestProxy(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document deleted successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Creates an input document using rest proxy + * @param data + */ +InputDocument.prototype.inputDocumentPostRestProxy = function (data) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document", + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + that.inputDocumentsGetRestProxy(); + that.openGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document saved successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Gets all input documents to populate the grid + */ +InputDocument.prototype.inputDocumentsGetRestProxy = function () { + var that = this, + restProxy = new PMRestClient({ + endpoint: 'input-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.grdpnlInputDocument.setDataItems(response); + that.grdpnlInputDocument.sort('inp_doc_title', 'asc'); + if (PMVariables.prototype.isWindowActive()) { + PMVariables.prototype.setInputDocumentsFromIDModule(PMUI.getPMUIObject(inp_doc_uid), response); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +/** + * Gets an specific input document data to edit it + * @param inputDocumentUid + */ +InputDocument.prototype.inputDocumentFormGetProxy = function (inputDocumentUid) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var data = response; + that.method = "PUT"; + that.openFormForEditInMainWindow(data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; + +/** + * Open Edit form and sets to main windows + * @param inputDocumentData + */ +InputDocument.prototype.openFormForEditInMainWindow = function (inputDocumentData) { + var that = this; + + that.inputDocumentOriginDataForUpdate = inputDocumentData; + that.inputDocumentUid = inputDocumentData.inp_doc_uid; + that.frmInputDocument.getField('inp_doc_original').setValue(""); + that.winMainInputDocument.setTitle("Edit Input Document".translate()); + + that.frmInputDocument.getField('inp_doc_title').setValue(inputDocumentData.inp_doc_title); + that.frmInputDocument.getField('inp_doc_description').setValue(inputDocumentData.inp_doc_description); + that.frmInputDocument.getField('inp_doc_form_needed').setValue(inputDocumentData.inp_doc_form_needed); + that.frmInputDocument.getField('inp_doc_original').setValue(inputDocumentData.inp_doc_original); + + if (inputDocumentData.inp_doc_form_needed !== "VIRTUAL") { + that.frmInputDocument.getField('inp_doc_original').setVisible(true); + } else { + that.frmInputDocument.getField('inp_doc_original').setVisible(false); + } + that.frmInputDocument.getField('inp_doc_versioning').setValue(parseInt(inputDocumentData.inp_doc_versioning + "")); + that.frmInputDocument.getField('inp_doc_destination_path').setValue(inputDocumentData.inp_doc_destination_path); + that.frmInputDocument.getField('inp_doc_tags').setValue(inputDocumentData.inp_doc_tags); + that.frmInputDocument.getField('inp_doc_type_file').setValue(inputDocumentData.inp_doc_type_file); + that.frmInputDocument.getField('inp_doc_max_filesize').setValue(inputDocumentData.inp_doc_max_filesize); + that.frmInputDocument.getField('inp_doc_max_filesize_unit').setValue(inputDocumentData.inp_doc_max_filesize_unit); +}; +/** + * Open the grid panel and sets to mai windows + */ +InputDocument.prototype.openGridPanelInMainWindow = function () { + this.grdpnlInputDocument.setVisible(true); + this.frmInputDocument.setVisible(false); + this.winMainInputDocument.setTitle("Input Documents".translate()); + this.winMainInputDocument.hideFooter(); +}; +/** + * Set the option external type of input Document + */ +InputDocument.prototype.setExternalType = function (value) { + if (typeof value === "boolean") { + this.externalType = value; + } + return this; +}; +/** + * Set the option window Dialog, a window that open this class + */ +InputDocument.prototype.setWindowDialog = function (value) { + this.windowDialog = value; + return this; +}; + +InputDocument.prototype.setAssignAccordion = function (obj) { + this.assignAccordion = obj; +}; + +/** + * Open create form an sets to main windows + */ +InputDocument.prototype.openFormInMainWindow = function () { + this.grdpnlInputDocument.setVisible(false); + this.frmInputDocument.setVisible(true); + this.winMainInputDocument.setTitle("Create Input Document".translate()); + this.winMainInputDocument.showFooter(); +}; + +InputDocument.prototype.checkIfValuesAreEqual = function (initialData, finalData) { + var key1, key2; + if (!Object.keys(initialData).length && Object.keys(finalData).length) { + if (finalData['inp_doc_title'] != '' || finalData['inp_doc_form_needed'] != 'VIRTUAL' || finalData['inp_doc_description'] != '' || finalData['inp_doc_versioning'] != '0' || finalData['inp_doc_destination_path'] != '') { + return false; + } + } + + for (key1 in initialData) { + for (key2 in finalData) { + if (typeof(initialData[key1]) != "undefined" && + typeof(finalData[key2]) != "undefined" && + key1 == key2 && + initialData[key1] != finalData[key2] + ) { + //Return + return false; + } + } + } + return true; +}; + +/** + * Generate all ui components(window, form, grid, fields) + */ + +InputDocument.prototype.isDirtyFormInput = function () { + $("input,select,textarea").blur(); + var that = this, message_window; + if (this.frmInputDocument.isVisible()) { + if (!this.externalType) { + if (!(this.checkIfValuesAreEqual(this.inputDocumentOriginDataForUpdate, getData2PMUI(this.frmInputDocument.html)))) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: "Input Documents".translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + if (typeof flagInputDocument != 'undefined' && flagInputDocument) { + if (that.clickedClose) { + message_window.close(); + that.winMainInputDocument.close(); + return; + } else { + that.winMainInputDocument.close(); + flagInputDocument = false; + } + return; + } else { + if (that.clickedClose) { + message_window.close(); + that.winMainInputDocument.close(); + return; + } else { + inputDocumentOption = ""; + that.openGridPanelInMainWindow(); + } + } + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + this.inputDocumentOriginDataForUpdate = {}; + } else { + if (that.clickedClose) { + this.winMainInputDocument.close(); + } else { + inputDocumentOption = ""; + this.openGridPanelInMainWindow(); + } + } + } else { + that.winMainInputDocument.close(); + } + } else { + that.winMainInputDocument.close(); + } +}; + +InputDocument.prototype.build = function () { + var ID = this, + btnSave, + btnCancel, + winMainInputDocument, + frmInputDocument, + grdpnlInputDocument, + btnNew, + inp_doc_destination_path, + inp_doc_tags, + that = this; + + btnSave = new PMUI.ui.Button({ + id: "btnSave", + text: "Save".translate(), + handler: function () { + var flagAux, data; + + if (!ID.frmInputDocument.isValid()) { + flagAux = ID.frmInputDocument.visible; + } else { + flagAux = ID.frmInputDocument.isValid(); + } + + if (flagAux) { + if (getData2PMUI(ID.frmInputDocument.html).inp_doc_title == "") { + return false; + } + } + + if (ID.frmInputDocument.getField("inp_doc_max_filesize").getValue() != "") { + if (!/^\+?(0|[1-9]\d*)$/.test(ID.frmInputDocument.getField("inp_doc_max_filesize").getValue())) { + return false; + } + } + + //validation because getData method do not work in IE + if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { + data = getData2PMUI(that.frmInputDocument.html); + } else { + data = that.frmInputDocument.getData(); + } + + data["inp_doc_versioning"] = parseInt(data["inp_doc_versioning"]); + + switch (that.method) { + case "POST": + that.inputDocumentPostRestProxy(data); + break; + case "PUT": + that.inputDocumentPutRestProxy(that.inputDocumentUid, data); + break; + } + }, + buttonType: 'success' + }); + + btnCancel = new PMUI.ui.Button({ + id: "btnCancel", + text: "Cancel".translate(), + handler: function () { + that.clickedClose = false; + that.isDirtyFormInput(); + }, + buttonType: 'error' + }); + btnNew = new PMUI.ui.Button({ + id: "btnNew", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + that.openFormInMainWindow(); + that.method = "POST"; + that.frmInputDocument.reset(); + } + }); + + /* form panel*/ + this.frmInputDocument = new PMUI.form.Form({ + id: "frmInputDocument", + width: 900, + visibleHeader: false, + items: [ + { + pmType: "text", + label: "Title".translate(), + id: "inputDocTitle", + name: "inp_doc_title", + valueType: 'string', + maxLength: 200, + required: true, + controlsWidth: 300 + }, + { + pmType: "dropdown", + name: "inp_doc_form_needed", + id: "inputDocDocumentType", + label: "Document Type".translate(), + value: "VIRTUAL", + controlsWidth: 130, + options: [ + { + value: "VIRTUAL", + label: "Digital".translate() + }, + { + value: "REAL", + label: "Printed".translate() + }, + { + value: "VREAL", + label: "Digital/Printed".translate() + } + ], + onChange: function (newValue, prevValue) { + var fields = that.frmInputDocument.getFields(); + if (newValue != "VIRTUAL") { + fields[2].setVisible(true); + } else { + fields[2].setVisible(false); + } + } + }, + { + pmType: "dropdown", + id: "inputDocDocumentType", + name: "inp_doc_original", + label: "Format".translate(), + value: "ORIGINAL", + controlsWidth: 105, + visible: false, + options: [ + { + value: "ORIGINAL", + label: "Original".translate() + }, + { + value: "COPYLEGAL", + label: "Legal Copy".translate() + }, + { + value: "COPY", + label: "Copy".translate() + } + ] + }, + { + pmType: "textarea", + id: "inputDocDescription", + name: "inp_doc_description", + label: "Description".translate(), + controlsWidth: 380, + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + pmType: "dropdown", + id: "inputDocEnableVersioning", + name: "inp_doc_versioning", + label: "Enable Versioning".translate(), + value: 0, + controlsWidth: 75, + options: [ + { + value: 0, + label: "NO".translate(), + selected: true + }, + { + value: 1, + label: "YES".translate() + } + ] + } + ], + buttonPanelPosition: 'top' + }); + inp_doc_destination_path = new CriteriaField({ + id: "inputDocDestinationPath", + name: "inp_doc_destination_path", + valueType: "string", + label: "Destination Path".translate(), + maxLength: 200, + controlsWidth: 380 + }); + + inp_doc_tags = new CriteriaField({ + id: "inputDocTags", + name: "inp_doc_tags", + valueType: "string", + label: "Tags".translate(), + maxLength: 200, + value: "INPUT", + controlsWidth: 380 + }); + + inp_doc_allowed = new PMUI.field.TextField({ + label: "Allowed file extensions (Use .* to allow any extension)".translate(), + id: "inputDocAllowedFileExtensions", + name: "inp_doc_type_file", + valueType: 'string', + maxLength: 200, + required: true, + value: ".*", + controlsWidth: 380 + + }); + + inp_doc_maximum = new PMUI.field.TextField({ + label: "Maximum file size (Use zero if unlimited)".translate(), + id: "inputDocMaximumFileSize", + name: "inp_doc_max_filesize", + valueType: 'string', + maxLength: 200, + required: true, + value: "0", + controlsWidth: 380, + validators: [ + { + pmType: "regexp", + criteria: /^\d*$/, + errorMessage: "Please enter a positive integer value".translate() + } + ] + + }); + + inp_doc_maximum_unit = new PMUI.field.DropDownListField({ + id: "inputDocUnit", + name: "inp_doc_max_filesize_unit", + label: "Unit".translate(), + value: "ORIGINAL", + controlsWidth: 105, + visible: true, + options: [ + { + value: "KB", + label: "KB".translate() + }, + { + value: "MB", + label: "MB".translate() + } + ] + }); + + that.frmInputDocument.addItem(inp_doc_destination_path); + that.frmInputDocument.addItem(inp_doc_tags); + that.frmInputDocument.addItem(inp_doc_allowed); + that.frmInputDocument.addItem(inp_doc_maximum); + that.frmInputDocument.addItem(inp_doc_maximum_unit); + + /*grid panel*/ + + this.grdpnlInputDocument = new PMUI.grid.GridPanel({ + id: "grdpnlInputDocument", + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'grdpnlInputDocumentButtonShow', + dataType: "button", + title: "", + buttonLabel: "Show ID".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + showUID(data.inp_doc_uid); + } + }, + { + columnData: "inp_doc_title", + title: "Title".translate(), + width: "607px", + alignment: "left", + sortable: true, + alignmentCell: 'left' + }, + { + id: 'grdpnlInputDocumentButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.inputDocumentOriginDataForUpdate = {}; + that.openFormInMainWindow(); + that.inputDocumentFormGetProxy(data.inp_doc_uid); + + } + }, + { + id: 'grdpnlInputDocumentButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + confirmWindow; + confirmWindow = new PMUI.ui.MessageWindow({ + id: "inputMessageWindowWarning", + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Input Documents".translate(), + message: "Do you want to delete this Input Document?".translate(), + footerItems: [ + { + id: 'confirmWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, + { + id: 'confirmWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + that.inputDocumentDeleteRestProxy(data.inp_doc_uid); + confirmWindow.close(); + confirmWindow.close(); + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = "17px"; + confirmWindow.showFooter(); + } + } + ], + dataItems: null + }); + /* main windows */ + this.winMainInputDocument = new PMUI.ui.Window({ + id: "winMainInputDocument", + title: "Input Documents".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: 'bottom', + footerAlign: 'right', + visibleFooter: true, + footerItems: [ + btnCancel, + btnSave + ], + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFormInput(); + } + }); + // add form and grid to windows + this.winMainInputDocument.addItem(this.grdpnlInputDocument); + this.winMainInputDocument.addItem(this.frmInputDocument); + this.winMainInputDocument.open(); + //custom css + this.frmInputDocument.getField("inp_doc_type_file").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_type_file").html.style.float = "left"; + this.frmInputDocument.getField("inp_doc_max_filesize").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_max_filesize").html.style.float = "left"; + this.frmInputDocument.getField("inp_doc_max_filesize_unit").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_max_filesize_unit").html.style.float = "left"; + this.grdpnlInputDocument.setVisible(true); + this.frmInputDocument.setVisible(false); + this.winMainInputDocument.hideFooter(); + /* insert create button to grid*/ + this.grdpnlInputDocument.dom.toolbar.appendChild(btnNew.getHTML()); + btnNew.defineEvents(); + this.inputDocumentsGetRestProxy(); +}; + +(function () { + + var loadValuesStartTimer, openForm, updateStatus; + + PMDesigner.startTimer = function (element) { + + var startTimer = element, + restClient, + loadServerData, + listUsers, + itemsDaly, + itemsWeekly, + loadOptionsRadio, + itemsMonthly, + itemsOneTime, + itemsEvery, + showProperties, + updateCaseScheduler, + buttonCancel, + loadUsers, + loadDataForm, + formCreateCaseScheduler, + schedulerListWindow, + buttonSave, + dataForm; + + loadValuesStartTimer = function ($flag) { + listUsers = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startTimer.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: 'case-scheduler/' + startTimer.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + dataForm = response[1].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: [null, 'There are problems loading the Start Timer, please try again.'.translate()] + }); + restClient.executeRestClient(); + if ($flag) { + return listUsers.length; + } + return true; + }; + + updateCaseScheduler = function (data) { + var restProxy = new PMRestClient({ + endpoint: 'case-scheduler/' + startTimer.evn_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Start Timer updated successfully'.translate(), + messageError: 'There are problems updating the Start Timer, please try again.'.translate(), + flashContainer: document.body + }); + restProxy.executeRestClient(); + }; + + updateStatus = function () { + var status = (typeof dataForm.sch_state !== 'undefined') ? ((dataForm.sch_state === 'ACTIVE') ? 'INACTIVE' : 'ACTIVE') : 'INACTIVE'; + dataForm.sch_state = status; + updateCaseScheduler(dataForm); + }; + + //Items for the form Create and edit Case Scheduler + itemsDaly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + } + ]; + + itemsWeekly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + id: 'daysoftheweek', + pmType: 'checkbox', + label: 'Select the day(s) of the week below'.translate(), + value: '', + name: 'daysoftheweek', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + id: 'monday', + label: 'Monday'.translate(), + value: '1' + }, + { + id: 'tuesday', + label: 'Tuesday'.translate(), + value: '2' + }, + { + id: 'wednesday', + label: 'Wednesday'.translate(), + value: '3' + }, + { + id: 'thursday', + label: 'Thursday'.translate(), + value: '4' + }, + { + id: 'friday', + label: 'Friday'.translate(), + value: '5' + }, + { + id: 'saturday', + label: 'Saturday'.translate(), + value: '6' + }, + { + id: 'sunday', + label: 'Sunday'.translate(), + value: '7' + } + ] + } + ]; + + loadOptionsRadio = function (newVal) { + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(true); + if (newVal === 'dayofmonth') { + paneldaysofMonth.getItems()[0].setVisible(true); + paneldaysofMonth.getItems()[1].setVisible(false); + } else if (newVal === 'day') { + paneldaysofMonth.getItems()[0].setVisible(false); + paneldaysofMonth.getItems()[1].setVisible(true); + } + }; + + itemsMonthly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + datetime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + datetime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + controlsWidth: 580, + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + pmType: 'panel', + id: 'panelDays', + layout: 'hbox', + items: [ + { + id: 'options', + pmType: 'radio', + label: '', + value: '', + name: 'options', + required: false, + controlPositioning: 'vertical', + maxDirectionOptions: 4, + options: [ + { + id: 'dayMonth', + label: 'Day of month'.translate(), + value: 'dayofmonth' + }, + { + id: 'day', + label: 'The day'.translate(), + value: 'day' + } + ], + onChange: function (newVal, oldVal) { + loadOptionsRadio(newVal); + }, + labelWidth: '46%' + }, + { + pmType: 'panel', + id: 'paneldaysofMonth', + layout: 'vbox', + items: [ + { + id: 'dayoftheMonth', + pmType: 'text', + label: '', + value: '', + placeholder: 'Day of the month (example: 1)'.translate(), + required: false, + name: 'dayMonth', + valueType: 'string' + }, + { + pmType: 'panel', + id: 'panelmonth', + layout: 'hbox', + items: [ + { + id: 'first', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'first', + valueType: 'string', + options: [ + { + label: 'First'.translate(), + value: '1' + }, + { + label: 'Second'.translate(), + value: '2' + }, + { + label: 'Third'.translate(), + value: '3' + }, + { + label: 'Fourth'.translate(), + value: '4' + }, + { + label: 'Last'.translate(), + value: '5' + } + ], + controlsWidth: 100 + }, + { + id: 'day', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'day', + valueType: 'string', + options: [ + { + label: 'Monday'.translate(), + value: '1' + }, + { + label: 'Tuesday'.translate(), + value: '2' + }, + { + label: 'Wednesday'.translate(), + value: '3' + }, + { + label: 'Thursday'.translate(), + value: '4' + }, + { + label: 'Friday'.translate(), + value: '5' + }, + { + label: 'Saturday'.translate(), + value: '6' + }, + { + label: 'Sunday'.translate(), + value: '7' + } + ], + controlsWidth: 100 + } + ] + } + ] + } + ] + }, + { + id: 'months', + pmType: 'checkbox', + label: 'Of the month(s)'.translate(), + value: '', + name: 'months', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'jan', + label: 'Jan'.translate(), + value: '1' + }, + { + id: 'feb', + label: 'Feb'.translate(), + value: '2' + }, + { + id: 'mar', + label: 'Mar'.translate(), + value: '3' + }, + { + id: 'apr', + label: 'Apr'.translate(), + value: '4' + }, + { + id: 'may', + label: 'May'.translate(), + value: '5' + }, + { + id: 'jun', + label: 'Jun'.translate(), + value: '6' + }, + { + id: 'jul', + label: 'Jul'.translate(), + value: '7' + }, + { + id: 'aug', + label: 'Aug'.translate(), + value: '8' + }, + { + id: 'sep', + label: 'Sep'.translate(), + value: '9' + }, + { + id: 'oct', + label: 'Oct'.translate(), + value: '10' + }, + { + id: 'nov', + label: 'Nov'.translate(), + value: '11' + }, + { + id: 'dec', + label: 'Dec'.translate(), + value: '12' + } + ] + } + ]; + + itemsOneTime = [{ + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + itemsEvery = [{ + id: 'execttime', + pmType: 'text', + label: 'Execute every Hour(s)'.translate(), + value: '', + required: true, + name: 'execttime', + valueType: 'string', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + showProperties = function (newValue) { + switch (newValue) { + case 'daily': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsDaly); + break; + case 'weekly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsWeekly); + break; + case 'monthly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsMonthly); + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(false); + formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[1].hideColon(); + break; + case 'oneTime': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsOneTime); + break; + case 'every': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsEvery); + validateKeysField(formCreateCaseScheduler.getField('execttime').getControls()[0].getHTML(), ['isnumber', 'iscolon']); + break; + } + }; + + //Form to Edit and create the Case Scheduler + formCreateCaseScheduler = new PMUI.form.Form({ + id: 'formCreateCaseScheduler', + border: false, + visibleHeader: false, + width: '925px', + name: 'formcreate', + title: '', + items: [ + { + id: 'panelProperties', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + height: '350px', + legend: 'Properties'.translate(), + items: [ + { + id: 'state', + pmType: 'dropdown', + label: 'Status'.translate(), + name: 'state', + required: true, + value: '', + controlsWidth: 150, + options: [ + { + value: 'ACTIVE', + label: 'Active'.translate() + }, + { + value: 'INACTIVE', + label: 'Inactive'.translate() + } + ] + }, + { + id: 'username', + pmType: 'dropdown', + label: 'User'.translate(), + name: 'username', + required: true, + controlsWidth: 300, + value: '', + options: [], + onChange: function (newValue, prevValue) { + } + }, + { + id: 'name', + pmType: 'text', + label: 'Name'.translate(), + value: startTimer.evn_name, + required: true, + name: 'name', + visible: false, + valueType: 'string' + }, + { + id: 'performTask', + pmType: 'dropdown', + label: 'Perform this task'.translate(), + name: 'performTask', + required: true, + value: '', + controlsWidth: 300, + options: [ + { + label: '- Select -'.translate(), + value: '', + disabled: true, + selected: true + }, + { + value: 'daily', + label: 'Daily'.translate() + }, + { + value: 'weekly', + label: 'Weekly'.translate() + }, + { + value: 'monthly', + label: 'Monthly'.translate() + }, + { + value: 'oneTime', + label: 'One Time Only'.translate() + }, + { + value: 'every', + label: 'Every'.translate() + } + ], + onChange: function (newValue, prevValue) { + showProperties(newValue); + } + } + ] + }, + { + id: 'panelSelectDate', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + visible: false, + height: '350px', + legend: 'Select the date and time for case(s) to be initiated.'.translate(), + items: [] + } + ] + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelSchedulerButton', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function (event) { + if (formCreateCaseScheduler.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: 'cancelMessageStartTimer', + title: 'Start Timer Event'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + schedulerListWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + } + } + }); + + //Window Buttons + buttonSave = new PMUI.ui.Button({ + id: 'saveSchedulerButton', + text: 'Save'.translate(), + height: 31, + buttonType: 'success', + handler: function (event) { + if (formCreateCaseScheduler.isValid()) { + var dataFormCreate = formCreateCaseScheduler.getData(); + + var dataToSend = { + sch_del_user_name: dataFormCreate.username, + sch_name: startTimer.evn_name, + tas_uid: startTimer.ports.get(0).connection.flo_element_dest, + sch_start_time: '', + sch_start_date: '', + sch_week_days: '', + sch_start_day: '', + sch_start_day_opt_1: '', + sch_start_day_opt_2: '', + sch_months: '', + sch_end_date: '', + sch_repeat_every: '', + sch_state: (dataFormCreate.state !== '') ? dataFormCreate.state : 'ACTIVE', + sch_option: '' + }; + + var perform = dataFormCreate.performTask; + switch (perform) { + case 'daily': + dataToSend.sch_option = '1'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + break; + case 'weekly': + var formdays = eval(dataFormCreate.daysoftheweek); + var days = ''; + for (i = 0; i < formdays.length; i += 1) { + if (i !== (formdays.length - 1)) { + days += formdays[i] + '|'; + } else { + days += formdays[i]; + } + } + + dataToSend.sch_option = '2'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + dataToSend.sch_week_days = days; + break; + case 'monthly': + dataToSend.sch_option = '3'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + if (dataFormCreate.options === 'dayofmonth') { + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '1'; //Day of month + dataToSend.sch_start_day_opt_1 = dataFormCreate.dayMonth;//1 to 31 - day of the month + } else if (dataFormCreate.options === 'day') { + var opt2 = dataFormCreate.first + '|' + dataFormCreate.day; + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '2'; //Day of month + dataToSend.sch_start_day_opt_2 = opt2;//1 to 31 - day of the month + + } + dataToSend.sch_months = months; + break; + case 'oneTime': + dataToSend.sch_option = '4'; + dataToSend.sch_start_time = dataFormCreate.execttime; + break; + case 'every': + dataToSend.sch_option = '5'; + dataToSend.sch_repeat_every = timeToDecimal(dataFormCreate.execttime).toFixed(2); + break; + } + updateCaseScheduler(dataToSend); + } + } + }); + + //load users + loadUsers = function () { + var field = formCreateCaseScheduler.getField('username'); + field.clearOptions(); + for (var i = 0; i < listUsers.length; i += 1) { + field.addOption({ + value: listUsers[i].aas_username, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + var loadTime, + option, + daysVal, + monthsVal, + monthsop, + days, + i, + startTime, + finallyST, + dataEdit; + + loadTime = function (dataEdit, dataForm) { + var starDate, + startTime, + finallyST, + endDate; + starDate = dataForm.sch_start_date ? dataForm.sch_start_date.split(' ') : ['']; + endDate = dataForm.sch_end_date ? dataForm.sch_end_date.split(' ') : ['']; + + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(starDate[0]); + dataEdit[5].setValue(endDate[0]); + dataEdit[6].setValue(finallyST); + }; + + dataEdit = formCreateCaseScheduler.getFields(); + + dataEdit[0].setValue(dataForm.sch_state); + dataEdit[1].setValue(dataForm.sch_del_user_name); + option = 'daily'; + switch (dataForm.sch_option) { + case '1': + option = 'daily'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + break; + case '2': + option = 'weekly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + + daysVal = "[\""; + days = dataForm.sch_week_days.split('|'); + for (i = 0; i < days.length; i += 1) { + if (i !== (days.length - 1)) { + daysVal += days[i] + "\",\""; + } else { + daysVal += days[i] + "\"]"; + } + } + dataEdit[7].setValue(daysVal); + break; + case '3': + option = 'monthly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + days = []; + if (dataForm.sch_start_day !== '') { + days = dataForm.sch_start_day.split('|'); + } + + if (days[0] === '1') { + dataEdit[7].setValue('dayofmonth'); + loadOptionsRadio('dayofmonth'); + dataEdit[8].setValue(days[1]); + } else if (days[0] === '2') { + dataEdit[7].setValue('day'); + loadOptionsRadio('day'); + dataEdit[9].setValue(days[1]); + dataEdit[10].setValue(days[2]); + } + monthsVal = "[\""; + monthsop = dataForm.sch_months.split('|'); + for (i = 0; i < monthsop.length; i += 1) { + if (i !== (monthsop.length - 1)) { + monthsVal += monthsop[i] + "\",\""; + } else { + monthsVal += monthsop[i] + "\"]"; + } + } + dataEdit[11].setValue(monthsVal); + break; + case '4': + option = 'oneTime'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(finallyST); + break; + case '5': + option = 'every'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + dataEdit[4].setValue(decimalToTime(parseFloat(dataForm.sch_repeat_every))); + break; + } + }; + + //Main window Case Scheduler + schedulerListWindow = new PMUI.ui.Window({ + id: 'schedulerListWindow', + title: 'Start Timer Event'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: 'top', + buttons: [ + buttonSave, + {pmType: 'label', text: 'or'}, + buttonCancel + ] + }); + + openForm = function () { + schedulerListWindow.addItem(formCreateCaseScheduler); + schedulerListWindow.open(); + loadUsers(); + loadDataForm(); + applyStyleWindowForm(schedulerListWindow); + schedulerListWindow.showFooter(); + schedulerListWindow.defineEvents(); + }; + }; + + PMDesigner.startTimer.openForm = function (element) { + openForm(); + }; + + PMDesigner.startTimer.validate = function (element) { + if (element.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 3000, 5); + return false; + } + PMDesigner.startTimer(element); + if (loadValuesStartTimer(true) === 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 3000, 5); + return false; + } + return true; + }; + +}()); +( + function () { + var dataBaseConnectionOption, + winFrmDataBaseConnectionShow, + frmDataBaseConnection, + closeClicked = true; + + PMDesigner.database = function (event) { + var winGrdpnlDataBaseConnection, + panelTest, + grdpnlDataBaseConnection, + flagError, + titleOld, + btnNew, + btnTestConnection, + btnCreate, + btnCancel, + testShow, + isDirtyFrmDataBaseConnection, + showForm, + listDBConnection, + refreshGridPanelInMainWindow, + dataBaseConnectionsGetRestProxy, + dataBaseConnectionPostTestRestProxy, + dataBaseConnectionGetRestProxy, + dataBaseConnectionPutRestProxy, + dataBaseConnectionDeleteRestProxy, + dataBaseConnectionPostRestProxy, + cboEngineSetOptionsRestProxy, + showEncoderOptions, + hideEncoderOptions, + cboConnectionTypeOracleSetOptions, + cboEncodeSetOptionsRestProxy, + winFrmDataBaseConnectionShow, + cboEngine, + txtUID, + cboEncode, + txtTns, + txtServer, + txtDataBaseName, + disableAllItems, + txtUsername, + txtPassword, + txtPort, + btnBack, + txtDescription, + cboConnectionTypeOracle, + dataBaseConnectionData; + + disableAllItems = function () { + winGrdpnlDataBaseConnection.getItems()[0].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(false); + + txtUID.setVisible(false); + btnTestConnection.setVisible(false); + btnBack.setVisible(false); + btnCreate.setVisible(false); + btnCancel.setVisible(false); + }; + + testShow = function (testData) { + var msg = "", titleSummary, style, i, flag; + flagError = 0; + disableAllItems(); + titleOld = winGrdpnlDataBaseConnection.getTitle(); + winGrdpnlDataBaseConnection.setTitle("Testing Server Connection".translate()); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(true); + + for (i = 0; i <= testData.length - 1; i += 1) { + flag = (typeof(testData[i].error) != "undefined") ? 1 : 0; + if (flag != 1) { + msg = msg + "" + testData[i].test + "
"; + } else { + msg = msg + "" + testData[i].error + "
"; + } + + if (typeof(testData[i].error) != "undefined" && flagError == 0) { + flagError = 1; + } + } + if (flag == 0) { + btnCreate.setVisible(true); + btnBack.setVisible(true); + } else { + btnBack.setVisible(true); + } + + titleSummary = "
Testing Database Server configuration
"; + + style = $('#panelTest').attr("style"); + titleSummary = titleSummary + "
" + msg + "
"; + $('#panelTest').empty(); + style = style + ' background: #FFFFFF; font: normal 0.8em arial;'; + $('#panelTest').attr("style", style); + $('#panelTest').append(titleSummary); + }; + + isDirtyFrmDataBaseConnection = function () { + var message_window; + $("input,select,textarea").blur(); + if (frmDataBaseConnection.isVisible()) { + if (frmDataBaseConnection.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Database Connections".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + dataBaseConnectionOption = ""; + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } + refreshGridPanelInMainWindow(false); + }, + buttonType: "success" + } + ], + title: 'Confirm'.translate() + }); + message_window.open(); + message_window.showFooter(); + } else { + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } else { + dataBaseConnectionOption = ""; + refreshGridPanelInMainWindow(false); + } + } + } else { + winGrdpnlDataBaseConnection.close(); + } + }; + showForm = function () { + disableAllItems(); + winGrdpnlDataBaseConnection.setTitle(titleOld); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); + } + + refreshGridPanelInMainWindow = function (load) { + disableAllItems(); + winGrdpnlDataBaseConnection.hideFooter(); + dataBaseConnectionOption = ""; + winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); + winGrdpnlDataBaseConnection.setTitle("Database Connections".translate()); + load = load != null ? load : true; + if (load) { + dataBaseConnectionsGetRestProxy(grdpnlDataBaseConnection); + } + }; + + dataBaseConnectionsGetRestProxy = function (grdpnl) { + var restProxy = new PMRestClient({ + endpoint: "database-connections", + typeRequest: "get", + functionSuccess: function (xhr, response) { + listDBConnection = response; + grdpnl.setDataItems(listDBConnection); + grdpnl.sort('dbs_database_name', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostTestRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/test", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + testShow(response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionGetRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response; + dataBaseConnectionOption = "PUT"; + winFrmDataBaseConnectionShow("PUT", data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPutRestProxy = function (dataBaseConnectionUid, data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Database connection edited successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + + restProxy.executeRestClient(); + }; + + dataBaseConnectionDeleteRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "remove", + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Database connection deleted successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + refreshGridPanelInMainWindow(); + }, + messageError: 'An unexpected error while deleting the DB Connection, please try again later.'.translate(), + messageSuccess: 'Database connection saved successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + + restProxy.executeRestClient(); + }; + + cboEngineSetOptionsRestProxy = function (cboEngine, cboEncode) { + cboEngine.clearOptions(); + var restProxy = new PMRestClient({ + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, + i, + arrayOptions = []; + for (i = 0; i <= data.length - 1; i += 1) { + arrayOptions.push( + { + value: data[i].id, + label: data[i].name + } + ); + } + cboEngine.setOptions(arrayOptions); + cboEngine.setValue(arrayOptions[0].value); + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.setBaseEndPoint("system/db-engines"); + restProxy.executeRestClient(); + }; + + hideEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(true); + }; + + showEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(false); + }; + cboConnectionTypeOracleSetOptions = function (cboConnectionTypeOracle) { + var arrayEnconde = [], + i, + arrayOptions = []; + cboConnectionTypeOracle.clearOptions(); + + arrayEnconde = [ + {"value": "NORMAL", "text": "Normal"}, + {"value": "TNS", "text": "TNS"} + ]; + + for (i = 0; i <= arrayEnconde.length - 1; i += 1) { + arrayOptions.push( + { + value: arrayEnconde[i].value, + label: arrayEnconde[i].text + } + ); + } + + cboConnectionTypeOracle.setOptions(arrayOptions); + }; + cboEncodeSetOptionsRestProxy = function (selectedCboEngineValue, cboEncode) { + var arrayEnconde = [], + arrayNewEnconde, + i, + portsDefault, + arrayOptions, + encode = selectedCboEngineValue; + cboEncode.clearOptions(); + + arrayEnconde["mysql"] = [ + {"value": "big5", "text": "big5 - Big5 Traditional Chinese"}, + {"value": "dec8", "text": "dec8 - DEC West European"}, + {"value": "cp850", "text": "cp850 - DOS West European"}, + {"value": "hp8", "text": "hp8 - HP West European"}, + {"value": "koi8r", "text": "koi8r - KOI8-R Relcom Russian"}, + {"value": "latin1", "text": "latin1 - cp1252 West European"}, + {"value": "latin2", "text": "latin2 - ISO 8859-2 Central European"}, + {"value": "swe7", "text": "swe7 - 7bit Swedish"}, + {"value": "ascii", "text": "ascii - US ASCII"}, + {"value": "ujis", "text": "ujis - EUC-JP Japanese"}, + {"value": "sjis", "text": "sjis - Shift-JIS Japanese"}, + {"value": "hebrew", "text": "hebrew - ISO 8859-8 Hebrew"}, + {"value": "tis620", "text": "tis620 - TIS620 Thai"}, + {"value": "euckr", "text": "euckr - EUC-KR Korean"}, + {"value": "koi8u", "text": "koi8u - KOI8-U Ukrainian"}, + {"value": "gb2312", "text": "gb2312 - GB2312 Simplified Chinese"}, + {"value": "greek", "text": "greek - ISO 8859-7 Greek"}, + {"value": "cp1250", "text": "cp1250 - Windows Central European"}, + {"value": "gbk", "text": "gbk - GBK Simplified Chinese"}, + {"value": "latin5", "text": "latin5 - ISO 8859-9 Turkish"}, + {"value": "armscii8", "text": "armscii8 - ARMSCII-8 Armenian"}, + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"}, + {"value": "ucs2", "text": "ucs2 - UCS-2 Unicode"}, + {"value": "cp866", "text": "cp866 - DOS Russian"}, + {"value": "keybcs2", "text": "keybcs2 - DOS Kamenicky Czech-Slovak"}, + {"value": "macce", "text": "macce - Mac Central European"}, + {"value": "macroman", "text": "macroman - Mac West European"}, + {"value": "cp852", "text": "cp852 - DOS Central European"}, + {"value": "latin7", "text": "atin7 - ISO 8859-13 Baltic"}, + {"value": "cp1251", "text": "cp1251 - Windows Cyrillic"}, + {"value": "cp1256", "text": "cp1256 - Windows Arabic"}, + {"value": "cp1257", "text": "cp1257 - Windows Baltic"}, + {"value": "binary", "text": "binary - Binary pseudo charset"}, + {"value": "geostd8", "text": "geostd8 - GEOSTD8 Georgian"}, + {"value": "cp932", "text": "cp932] - SJIS for Windows Japanese"}, + {"value": "eucjpms", "text": "eucjpms - UJIS for Windows Japanese"} + ]; + + arrayEnconde["pgsql"] = [ + {"value": "BIG5", "text": "BIG5"}, + {"value": "EUC_CN", "text": "EUC_CN"}, + {"value": "EUC_JP", "text": "EUC_JP"}, + {"value": "EUC_KR", "text": "EUC_KR"}, + {"value": "EUC_TW", "text": "EUC_TW"}, + {"value": "GB18030", "text": "GB18030"}, + {"value": "GBK", "text": "GBK"}, + {"value": "ISO_8859_5", "text": "ISO_8859_5"}, + {"value": "ISO_8859_6", "text": "ISO_8859_6"}, + {"value": "ISO_8859_7", "text": "ISO_8859_7"}, + {"value": "ISO_8859_8", "text": "ISO_8859_8"}, + {"value": "JOHAB", "text": "JOHAB"}, + {"value": "KOI8", "text": "KOI8"}, + {"value": "selected", "text": "LATIN1"}, + {"value": "LATIN2", "text": "LATIN2"}, + {"value": "LATIN3", "text": "LATIN3"}, + {"value": "LATIN4", "text": "LATIN4"}, + {"value": "LATIN5", "text": "LATIN5"}, + {"value": "LATIN6", "text": "LATIN6"}, + {"value": "LATIN7", "text": "LATIN7"}, + {"value": "LATIN8", "text": "LATIN8"}, + {"value": "LATIN9", "text": "LATIN9"}, + {"value": "LATIN10", "text": "LATIN10"}, + {"value": "SJIS", "text": "SJIS"}, + {"value": "SQL_ASCII", "text": "SQL_ASCII"}, + {"value": "UHC", "text": "UHC"}, + {"value": "UTF8", "text": "UTF8"}, + {"value": "WIN866", "text": "WIN866"}, + {"value": "WIN874", "text": "WIN874"}, + {"value": "WIN1250", "text": "WIN1250"}, + {"value": "WIN1251", "text": "WIN1251"}, + {"value": "WIN1252", "text": "WIN1252"}, + {"value": "WIN1256", "text": "WIN1256"}, + {"value": "WIN1258", "text": "WIN1258"} + ]; + + arrayEnconde["mssql"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; + + arrayEnconde["oracle"] = [ + {"value": "UTF8", "text": "UTF8 - Unicode 3.0 UTF-8 Universal character set, CESU-8 compliant"}, + {"value": "UTFE", "text": "UTFE - EBCDIC form of Unicode 3.0 UTF-8 Universal character set"}, + {"value": "AL16UTF16", "text": "AL16UTF16 - Unicode 3.1 UTF-16 Universal character set"}, + {"value": "AL32UTF8", "text": "AL32UTF8 - Unicode 3.1 UTF-8 Universal character set"} + ]; + + arrayEnconde["sqlsrv"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; + + arrayNewEnconde = (typeof(arrayEnconde[encode]) != "undefined") ? arrayEnconde[encode] : []; + arrayOptions = []; + + for (i = 0; i <= arrayNewEnconde.length - 1; i += 1) { + arrayOptions.push( + { + value: arrayNewEnconde[i].value, + label: arrayNewEnconde[i].text + } + ); + } + + cboEncode.setOptions(arrayOptions); + cboEncode.setValue('utf8'); + + portsDefault = ["3306", "5432", "1433", "1521"]; + switch (encode) { + case "mysql": + txtPort.setValue(portsDefault[0]); + showEncoderOptions(); + break; + case "pgsql": + txtPort.setValue(portsDefault[1]); + showEncoderOptions(); + break; + case "mssql": + txtPort.setValue(portsDefault[2]); + showEncoderOptions(); + break; + case "oracle": + txtPort.setValue(portsDefault[3]); + hideEncoderOptions(); + break; + } + }; + + winFrmDataBaseConnectionShow = function (option, data) { + disableAllItems(); + dataBaseConnectionData = data; + frmDataBaseConnection.reset(); + cboEngineSetOptionsRestProxy(cboEngine, cboEncode); + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); + winGrdpnlDataBaseConnection.showFooter(); + + switch (option) { + case "POST": + winGrdpnlDataBaseConnection.setTitle("Create Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + txtServer.setVisible(true); + txtServer.setRequired(true); + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + txtPort.setVisible(true); + txtPort.setRequired(true); + txtPort.setValue("3306"); + break; + case "PUT": + winGrdpnlDataBaseConnection.setTitle("Edit Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtUID.setVisible(true); + txtUID.setValue(dataBaseConnectionData.dbs_uid); + cboEngine.setValue(dataBaseConnectionData.dbs_type); + cboEncodeSetOptionsRestProxy(dataBaseConnectionData.dbs_type, cboEncode); + cboEncode.setValue(dataBaseConnectionData.dbs_encode); + txtServer.setValue(dataBaseConnectionData.dbs_server); + txtDataBaseName.setValue(dataBaseConnectionData.dbs_database_name); + txtUsername.setValue(dataBaseConnectionData.dbs_username); + txtPassword.setValue(dataBaseConnectionData.dbs_password); + txtPort.setValue(dataBaseConnectionData.dbs_port); + txtDescription.setValue(dataBaseConnectionData.dbs_description); + + if (dataBaseConnectionData.dbs_type == "oracle") { + cboConnectionTypeOracle.setValue(dataBaseConnectionData.dbs_connection_type); + cboConnectionTypeOracle.setVisible(true); + + if (dataBaseConnectionData.dbs_connection_type == "TNS" && dataBaseConnectionData.dbs_tns != "") { + txtTns.setValue(dataBaseConnectionData.dbs_tns); + txtTns.setVisible(true); + txtTns.setRequired(true); + + txtServer.setValue(""); + txtServer.setVisible(false); + txtServer.setRequired(false); + + txtDataBaseName.setValue(""); + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); + + txtPort.setValue(""); + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + break; + } + frmDataBaseConnection.setFocus(); + }; + + txtUID = new PMUI.field.TextField({ + id: "txtUID", + name: "txtUID", + valueType: "string", + controlsWidth: 300, + label: "UID".translate(), + maxLength: 200, + readOnly: true, + visible: false + }); + + cboEngine = new PMUI.field.DropDownListField({ + id: "cboEngine", + name: "cboEngine", + label: "Engine".translate(), + options: null, + controlsWidth: 150, + onChange: function (newValue, prevValue) { + if (cboEngine.getValue() == "oracle") { + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); + } + }); + + cboEncode = new PMUI.field.DropDownListField({ + id: "cboEncode", + name: "cboEncode", + label: "Encode".translate(), + options: null, + controlsWidth: 300 + }); + + cboConnectionTypeOracle = new PMUI.field.DropDownListField({ + id: "cboConnectionTypeOracle", + name: "cboConnectionTypeOracle", + label: "Select Connection Type".translate(), + options: null, + controlsWidth: 300, + + onChange: function (newValue, prevValue) { + if (cboConnectionTypeOracle.getValue() != "NORMAL") { + txtTns.setVisible(true); + txtTns.setRequired(true); + + txtServer.setVisible(false); + txtServer.setRequired(false); + + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); + + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setValue("1521"); + txtPort.setVisible(true); + txtPort.setRequired(true); + } + } + }); + + txtTns = new PMUI.field.TextField({ + id: "txtTns", + name: "txtTns", + valueType: "txtTns", + controlsWidth: 300, + label: "TNS".translate(), + maxLength: 200, + visible: false, + required: true + }); + + txtServer = new PMUI.field.TextField({ + id: "txtServer", + name: "txtServer", + valueType: "string", + controlsWidth: 300, + label: "Server".translate(), + maxLength: 200, + required: true + }); + + txtDataBaseName = new PMUI.field.TextField({ + id: "txtDataBaseName", + name: "txtDataBaseName", + valueType: "string", + controlsWidth: 300, + label: "Database Name".translate(), + maxLength: 200, + required: true + }); + + txtUsername = new PMUI.field.TextField({ + id: "txtUsername", + name: "txtUsername", + valueType: "string", + controlsWidth: 300, + label: "Username".translate(), + maxLength: 200, + required: true + }); + + txtPassword = new PMUI.field.PasswordField({ + id: "txtPassword", + name: "txtPassword", + valueType: "string", + controlsWidth: 300, + label: "Password".translate(), + maxLength: 200 + }); + + txtPort = new PMUI.field.TextField({ + id: "txtPort", + name: "txtPort", + valueType: "string", + controlsWidth: 300, + label: "Port".translate(), + value: "3306", + controlsWidth: 300, + maxLength: 200, + required: true + }); + + txtDescription = new PMUI.field.TextAreaField({ + id: "txtDescription", + name: "txtDescription", + valueType: "string", + controlsWidth: 500, + label: "Description".translate(), + height: "200px", + style: {cssClasses: ['mafe-textarea-resize']} + }); + + btnTestConnection = new PMUI.ui.Button({ + id: "btnTestConnection", + text: "Test Connection".translate(), + buttonType: 'success', + handler: function () { + var data; + if (frmDataBaseConnection.isValid()) { + if (cboEngine.getValue() == "oracle") { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_connection_type: cboConnectionTypeOracle.getValue(), + dbs_tns: txtTns.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } else { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } + dataBaseConnectionPostTestRestProxy(data); + } + } + }); + + btnCreate = new PMUI.ui.Button({ + id: "btnCreate", + text: "Save".translate(), + buttonType: "success", + handler: function () { + var data; + if (cboEngine.getValue() == "oracle") { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_connection_type: cboConnectionTypeOracle.getValue(), + dbs_tns: txtTns.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } else { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: txtPassword.getValue(), + dbs_port: parseInt(txtPort.getValue()), + dbs_description: txtDescription.getValue() + }; + } + + switch (dataBaseConnectionOption) { + case "POST": + if (frmDataBaseConnection.isValid()) { + dataBaseConnectionPostRestProxy(data); + } else { + return; + } + break; + case "PUT": + if (frmDataBaseConnection.isValid()) { + dataBaseConnectionPutRestProxy(dataBaseConnectionData.dbs_uid, data); + } else { + return; + } + break; + } + } + }); + + btnCancel = new PMUI.ui.Button({ + id: "btnCancel", + text: "Cancel".translate(), + buttonType: 'error', + handler: function () { + closeClicked = false; + isDirtyFrmDataBaseConnection(); + } + }); + + btnBack = new PMUI.ui.Button({ + id: "btnBack", + text: "Back".translate(), + handler: function () { + showForm(); + } + }); + + frmDataBaseConnection = new PMUI.form.Form({ + id: "frmDataBaseConnection", + width: DEFAULT_WINDOW_WIDTH - 70, + items: [ + txtUID, + cboEngine, + cboEncode, + cboConnectionTypeOracle, + txtTns, + txtServer, + txtDataBaseName, + txtUsername, + txtPassword, + txtPort, + txtDescription + ] + }); + + txtPort.controls[0].onKeyUp = function () { + var txtPortfinalValue, + txtPortValue = getData2PMUI(frmDataBaseConnection.html).txtPort; + if (/\D/.test(txtPortValue)) { + if (isNaN(parseInt(txtPortValue))) { + txtPortfinalValue = ""; + } else { + txtPortfinalValue = parseInt(txtPortValue); + } + txtPort.setValue(txtPortfinalValue); + } + }; + + btnNew = new PMUI.ui.Button({ + id: "btnNew", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + dataBaseConnectionOption = "POST"; + winFrmDataBaseConnectionShow("POST", {}); + } + }); + + grdpnlDataBaseConnection = new PMUI.grid.GridPanel({ + id: "grdpnlDataBaseConnection", + filterable: true, + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'grdpnlDataBaseConnectionButtonShow', + dataType: "button", + title: "", + buttonLabel: "Show ID".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + width: "100px", + onButtonClick: function (row, grid) { + showUID(row.getData().dbs_uid); + } + }, + { + columnData: "dbs_type", + title: "Type".translate(), + width: "100px", + sortable: true, + alignmentCell: 'left' + }, + { + columnData: "dbs_server", + title: "Server".translate(), + width: "155px", + alignmentCell: 'left' + }, + { + columnData: "dbs_database_name", + title: "Database Name".translate(), + width: "160px", + sortable: true, + alignmentCell: 'left' + }, + { + columnData: "dbs_description", + title: "Description".translate(), + width: "200px", + alignmentCell: 'left' + }, + { + id: 'grdpnlDataBaseConnectionButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + dataBaseConnectionGetRestProxy(row.getData().dbs_uid); + } + }, + { + id: 'grdpnlDataBaseConnectionButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + var msgWarning = new PMUI.ui.MessageWindow({ + id: "msgWarning", + title: 'Database Connections'.translate(), + windowMessageType: 'warning', + width: 490, + message: "Do you want to delete this DB Connection?".translate(), + buttons: [ + { + text: "No".translate(), + handler: function () { + msgWarning.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + dataBaseConnectionDeleteRestProxy(data.dbs_uid); + msgWarning.close(); + }, + buttonType: "success" + } + ] + }); + msgWarning.open(); + msgWarning.showFooter(); + } + } + ], + dataItems: null + }); + + panelTest = new PMUI.core.Panel({ + id: 'panelTest', + height: DEFAULT_WINDOW_HEIGHT - 71, + display: 'inline-block' + }); + + winGrdpnlDataBaseConnection = new PMUI.ui.Window({ + id: "winGrdpnlDataBaseConnection", + title: "Database Connections".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + buttonPanelPosition: "bottom", + buttons: [btnCancel, btnBack, btnTestConnection, btnCreate], + onBeforeClose: function () { + closeClicked = true; + isDirtyFrmDataBaseConnection(); + } + }); + + winGrdpnlDataBaseConnection.addItem(grdpnlDataBaseConnection); + winGrdpnlDataBaseConnection.addItem(frmDataBaseConnection); + winGrdpnlDataBaseConnection.addItem(panelTest); + + refreshGridPanelInMainWindow(); + if (typeof listDBConnection !== "undefined") { + winGrdpnlDataBaseConnection.open(); + frmDataBaseConnection.panel.html.style.padding = "10px"; + $('#grdpnlDataBaseConnection .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + winGrdpnlDataBaseConnection.defineEvents(); + applyStyleWindowForm(winGrdpnlDataBaseConnection); + winGrdpnlDataBaseConnection.footer.html.style.textAlign = 'right'; + $(btnNew.getHTML()).css({float: "right"}) + grdpnlDataBaseConnection.dom.toolbar.appendChild(btnNew.getHTML()); + btnNew.defineEvents(); + + disableAllItems(); + winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); + } + }; + + PMDesigner.database.create = function () { + PMDesigner.database(); + dataBaseConnectionOption = "POST"; + winFrmDataBaseConnectionShow("POST", {}); + }; + }() +); + +(function () { + var openTinyInMainWindow, + dataOutPutDocument, + openFormInMainWindow, + messageRequired; + + PMDesigner.output = function (event) { + var winMainOutputDocument, formOutput, rowData, updateOutPut, restClient, isDirtyFormOutput, clickedClose = true, that = this, + setDataRow, + clearDataRow, + getGridOutput, + disableAllItems, + deleteDataRow, + updateOutput, + refreshGridPanelInMainWindow, + openGridPanelInMainWindow, + openFormForEditInMainWindow, + editorTiny, + outputFormDocPdfSecurityOpen, + docMargin, + password, + outputFormDocPdfSecurityOwner, + outputFormDocPdfSecurityEnabled, + btnCloseWindowOutputDoc, + btnSaveWindowOutputDoc, + btnCancelTiny, + newButtonOutput, + gridOutput, + winMainOutputDocument, + btnSaveTiny, + listOutputDocs; + + + setDataRow = function (row) { + dataOutPutDocument = row.getData(); + rowData = row; + }; + + clearDataRow = function () { + dataOutPutDocument = ''; + rowData = ''; + }; + + isDirtyFormOutput = function () { + var message_window; + $("input,select,textarea").blur(); + if (formOutput.isVisible()) { + if (formOutput.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: "Output Documents".translate(), + windowMessageType: "warning", + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + clearDataRow(); + message_window.close(); + if (clickedClose) { + tinymce.EditorManager.execCommand('mceRemoveControl', true, 'tinyeditor'); + winMainOutputDocument.close(); + } else { + clearDataRow(); + openGridPanelInMainWindow(); + } + + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + clearDataRow(); + if (clickedClose) { + tinymce.EditorManager.execCommand('mceRemoveControl', true, 'tinyeditor'); + winMainOutputDocument.close() + } else { + openGridPanelInMainWindow(); + } + } + } else { + winMainOutputDocument.close(); + } + }; + getGridOutput = function () { + var restClientGet = new PMRestClient({ + endpoint: 'output-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listOutputDocs = response; + gridOutput.setDataItems(listOutputDocs); + gridOutput.sort('out_doc_title', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + restClientGet.executeRestClient(); + }; + + disableAllItems = function () { + winMainOutputDocument.hideFooter(); + formOutput.reset(); + + winMainOutputDocument.getItems()[0].setVisible(false); + winMainOutputDocument.getItems()[1].setVisible(false); + for (var i = 0; i <= winMainOutputDocument.getItems()[1].getItems().length - 1; i += 1) { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(false); + } + btnSaveWindowOutputDoc.setVisible(false); + btnCloseWindowOutputDoc.setVisible(false); + btnSaveTiny.setVisible(false); + btnCancelTiny.setVisible(false); + + winMainOutputDocument.footer.getItems()[2].setVisible(false); + }; + + refreshGridPanelInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + winMainOutputDocument.setTitle("Output Documents".translate()); + getGridOutput(); + }; + + openGridPanelInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + winMainOutputDocument.setTitle("Output Documents".translate()); + $(winMainOutputDocument.body).removeClass("pmui-background"); + }; + + openFormInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.showFooter(); + winMainOutputDocument.getItems()[1].setVisible(true); + for (var i = 0; i < winMainOutputDocument.getItems()[1].getItems().length; i += 1) { + if (winMainOutputDocument.getItems()[1].getItems()[i].type !== "PMTinyField") { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(true); + } + } + btnSaveWindowOutputDoc.setVisible(true); + btnCloseWindowOutputDoc.setVisible(true); + winMainOutputDocument.footer.getItems()[2].setVisible(true); + password.setVisible(false); + winMainOutputDocument.setTitle("Create Output Document".translate()); + winMainOutputDocument.setHeight(520); + formOutput.panel.style.addProperties({padding: '20px 10px'}); + formOutput.setFocus(); + + }; + + openFormForEditInMainWindow = function (outputDocumentData) { + disableAllItems(); + winMainOutputDocument.showFooter(); + btnSaveWindowOutputDoc.setVisible(true); + btnCloseWindowOutputDoc.setVisible(true); + winMainOutputDocument.footer.getItems()[1].setVisible(false); + formOutput.setWidth(700); + winMainOutputDocument.getItems()[1].setVisible(true); + winMainOutputDocument.setTitle("Edit Output Document".translate()); + $(winMainOutputDocument.body).addClass("pmui-background"); + for (var i = 0; i < winMainOutputDocument.getItems()[1].getItems().length; i += 1) { + if (winMainOutputDocument.getItems()[1].getItems()[i].type !== "PMTinyField") { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(true); + } + } + + password.setVisible(false); + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + var dataEdit = formOutput.getFields(); + dataEdit[0].setValue(dataOutPutDocument['out_doc_title']); + dataEdit[1].setValue(dataOutPutDocument['out_doc_filename']); + dataEdit[2].setValue(dataOutPutDocument['out_doc_description']); + dataEdit[3].setValue(dataOutPutDocument['out_doc_report_generator']); + dataEdit[4].setValue(dataOutPutDocument['out_doc_media']); + dataEdit[5].setValue(dataOutPutDocument['out_doc_landscape']); + dataEdit[6].setValue(dataOutPutDocument['out_doc_left_margin']); + dataEdit[7].setValue(dataOutPutDocument['out_doc_right_margin']); + dataEdit[8].setValue(dataOutPutDocument['out_doc_top_margin']); + dataEdit[9].setValue(dataOutPutDocument['out_doc_bottom_margin']); + dataEdit[10].setValue(dataOutPutDocument['out_doc_generate']); + + if (dataOutPutDocument["out_doc_generate"] != "DOC") { + dataEdit[11].setVisible(true); + } else { + dataEdit[11].setVisible(false); + } + + dataEdit[11].setValue(dataOutPutDocument['out_doc_pdf_security_enabled']); + if (dataOutPutDocument['out_doc_pdf_security_enabled'] != 0) { + password.setVisible(true); + } + dataEdit[12].setValue(dataOutPutDocument['out_doc_pdf_security_open_password']); + dataEdit[13].setValue(dataOutPutDocument['out_doc_pdf_security_owner_password']); + + dataOutPutDocument['out_doc_pdf_security_permissions'] = dataOutPutDocument['out_doc_pdf_security_permissions'].split("|"); + dataEdit[14].setValue(JSON.stringify(dataOutPutDocument['out_doc_pdf_security_permissions'])); + + dataEdit[15].setValue(dataOutPutDocument['out_doc_versioning']); + dataEdit[16].setValue(dataOutPutDocument['out_doc_destination_path']); + dataEdit[17].setValue(dataOutPutDocument['out_doc_tags']); + dataEdit[18].setValue(dataOutPutDocument["out_doc_open_type"]); + } + winMainOutputDocument.setHeight(520); + formOutput.panel.style.addProperties({padding: '20px 10px'}); + formOutput.setFocus(); + }; + + openTinyInMainWindow = function (outputDocumentData) { + //Fix for IE11 + var isIe11 = /Trident\/7\.0;.*rv\s*\:?\s*11/.test(navigator.userAgent); + + if (isIe11) { + tinyMCE.isGecko = false; + } + + //Set TinyMCE + disableAllItems(); + winMainOutputDocument.showFooter(); + tinyEditorField = 13; + winMainOutputDocument.getItems()[1].setVisible(true); + winMainOutputDocument.getItems()[1].getItems()[tinyEditorField].setVisible(true); + formOutput.setWidth(890); + btnSaveTiny.setVisible(true); + btnCancelTiny.setVisible(true); + if (!editorTiny.isInitialized) { + editorTiny.createHTML(); + editorTiny.setParameterTiny(); + editorTiny.isInitialized = true; + } else { + tinyMCE.execCommand('mceFocus', false, 'tinyeditor'); + } + var dataEdit = formOutput.getFields(); + winMainOutputDocument.setTitle("Edit Output Document".translate()); + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + dataOutPutDocument['out_doc_template'] = (dataOutPutDocument['out_doc_template'] != null) ? dataOutPutDocument['out_doc_template'] : ' '; + dataEdit[19].setValue(dataOutPutDocument['out_doc_template']); + dataEdit[19].setValueTiny(dataOutPutDocument['out_doc_template']); + dataEdit[19].setHeight(425); + + dataEdit[18].setVisible(false); + dataEdit[19].setVisible(true); + } + formOutput.panel.style.addProperties({padding: '0px 10px'}); + winMainOutputDocument.setHeight(520); + if (!editorTiny.isInitialized) + tinymce.execCommand('mceFocus', false, 'tinyeditor'); + }; + + deleteDataRow = function () { + confirmWindow = new PMUI.ui.MessageWindow({ + id: "outputMessageWindowWarning", + windowMessageType: 'warning', + bodyHeight: 'auto', + width: 490, + title: "Output Documents".translate(), + message: "Do you want to delete this Output Document?".translate(), + footerItems: [ + { + id: 'confirmWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + id: 'confirmWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + var restClient; + confirmWindow.close(); + restClient = new PMRestClient({ + endpoint: "output-document/" + dataOutPutDocument.out_doc_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems deleting the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document deleted successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + }, + buttonType: "success" + }, + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = "17px"; + confirmWindow.showFooter(); + }; + + updateOutput = function (data) { + dataOutPutDocument = ''; + var restClientUpdate = new PMRestClient({ + endpoint: "output-document/" + data.out_doc_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + dataOutPutDocument = data; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document edited successfully'.translate(), + flashContainer: gridOutput + }); + restClientUpdate.executeRestClient(); + }; + + editorTiny = new PMTinyField({ + id: 'outputEditorTiny', + theme: "advanced", + plugins: "advhr,advimage,advlink,advlist,autolink,autoresize,contextmenu,directionality,emotions,example,example_dependency,fullpage,fullscreen,iespell,inlinepopups,insertdatetime,layer,legacyoutput,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,style,tabfocus,table,template,visualblocks,visualchars,wordcount,xhtmlxtras,pmSimpleUploader,pmVariablePicker,style", + mode: "specific_textareas", + editorSelector: "tmceEditor", + widthTiny: DEFAULT_WINDOW_WIDTH - 58, + heightTiny: DEFAULT_WINDOW_HEIGHT - 100, + directionality: 'ltr', + verifyHtml: false, + themeAdvancedButtons1: "pmSimpleUploader,|,pmVariablePicker,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,cut,copy,paste,|,bullist,numlist,|,outdent,indent,blockquote", + themeAdvancedButtons2: "tablecontrols,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor,styleprops,|,hr,removeformat,visualaid,|,sub,sup,|,ltr,rtl,|,code", + popupCss: "/js/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialogTinyBpmn.css", + contentCss: "/css/fonts.css,/fonts/styles.php", + themeAdvancedFonts: tcPdfFonts, + skin: "o2k7", + skin_variant: "silver" + }); + + docMargin = new PMUI.form.FormPanel({ + fieldset: true, + layout: 'hbox', + legend: "Margin".translate(), + items: [ + { + pmType: 'panel', + proportion: 0.7 + }, + { + pmType: "panel", + layout: 'vbox', + items: [ + { + id: 'outputDocMarginLeft', + pmType: "text", + label: "Left".translate(), + required: true, + value: 20, + name: "out_doc_left_margin", + controlsWidth: 50, + labelWidth: '35%' + }, { + id: 'outputDocMarginRight', + pmType: "text", + label: "Right".translate(), + required: true, + value: 20, + name: "out_doc_right_margin", + controlsWidth: 50, + labelWidth: '35%' + } + ] + }, + { + pmType: "panel", + layout: 'vbox', + proportion: 1.5, + items: [ + { + id: 'outputDocMarginTop', + pmType: "text", + label: "Top".translate(), + required: true, + value: 20, + name: "out_doc_top_margin", + controlsWidth: 50, + labelWidth: '27%' + }, { + id: 'outputDocMarginBottom', + pmType: "text", + label: "Bottom".translate(), + required: true, + value: 20, + name: "out_doc_bottom_margin", + controlsWidth: 50, + labelWidth: '27%' + } + ] + } + ] + }); + + //Field "Open Password - Owner Password" + outputFormDocPdfSecurityOpen = new PMUI.field.PasswordField({ + id: "outputFormDocPdfSecurityOpen", + name: "out_doc_pdf_security_open_password", + value: "", + label: "Open Password ".translate(), + required: true, + controlsWidth: 300 + }); + + outputFormDocPdfSecurityOwner = new PMUI.field.PasswordField({ + id: "outputFormDocPdfSecurityOwner", + name: "out_doc_pdf_security_owner_password", + value: "", + label: "Owner Password ".translate(), + required: true, + controlsWidth: 300 + + }); + + password = new PMUI.form.FormPanel({ + width: 500, + height: 130, + fieldset: true, + visible: false, + legend: "", + items: [ + { + pmType: "panel", + layout: 'vbox', + items: [ + outputFormDocPdfSecurityOpen, + outputFormDocPdfSecurityOwner + ] + }, + { + pmType: "panel", + layout: 'vbox', + items: [ + { + id: 'outputFormDocPdfSecurityPermissions', + pmType: 'checkbox', + label: "Allowed Permissions".translate(), + value: '', + name: 'out_doc_pdf_security_permissions', + required: false, + controlPositioning: 'horizontal', + separator: "|", + maxDirectionOptions: 4, + options: [ + { + id: 'monday', + label: "print".translate(), + value: 'print' + }, + { + id: 'monday', + label: "modify".translate(), + value: 'modify' + }, + { + id: 'monday', + label: "copy".translate(), + value: 'copy' + }, + { + id: 'monday', + label: "forms".translate(), + value: 'forms' + } + + ] + } + ] + } + ], + layout: "vbox" + }); + + //Field "PDF security" + outputFormDocPdfSecurityEnabled = new PMUI.field.DropDownListField({ + id: "outputDocDPFSecurity", + name: "out_doc_pdf_security_enabled", + label: "PDF security".translate(), + labelWidth: "27%", + valueType: "number", + visible: false, + + options: [ + { + value: 0, + label: "Disabled".translate(), + selected: true + }, + { + value: 1, + label: "Enabled".translate() + + } + ], + + controlsWidth: 100, + + onChange: function (newValue, prevValue) { + var visible = true; + + if (newValue == 0) { + visible = false; + + outputFormDocPdfSecurityOpen.setValue(""); + outputFormDocPdfSecurityOwner.setValue(""); + } + + password.setVisible(visible); + } + }); + + //the form is 700px width, but with the tiny grows to 890 + formOutput = new PMUI.form.Form({ + id: 'outputForm', + name: 'outputForm', + fieldset: true, + title: "", + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 43, + items: [ + { + id: 'outputDocTitle', + pmType: "text", + name: 'out_doc_title', + label: "Title".translate(), + labelWidth: '27%', + controlsWidth: 300, + required: true + }, + new CriteriaField({ + id: 'outputDocFilenameGenerated', + pmType: "text", + name: 'out_doc_filename', + label: "Filename generated".translate(), + labelWidth: '27%', + controlsWidth: 300, + required: true + }), + { + id: 'outputDocDescription', + pmType: "textarea", + name: 'out_doc_description', + label: "Description".translate(), + labelWidth: '27%', + controlsWidth: 500, + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: 'outputDocReportGenerator', + pmType: "dropdown", + name: 'out_doc_report_generator', + label: "Report Generator".translate(), + labelWidth: '27%', + require: true, + controlsWidth: 165, + options: [ + { + label: "TCPDF".translate(), + value: "TCPDF" + }, + { + label: "HTML2PDF (Old Version)".translate(), + value: "HTML2PDF" + } + ], + value: "TCPDF" + }, + { + id: 'outputDocMedia', + pmType: "dropdown", + name: 'out_doc_media', + label: "Media".translate(), + labelWidth: '27%', + controlsWidth: 165, + options: [ + {label: "Letter".translate(), value: "Letter"}, + {label: "Legal".translate(), value: "Legal"}, + {label: "Executive".translate(), value: "Executive"}, + {label: "B5".translate(), value: "B5"}, + {label: "Folio".translate(), value: "Folio"}, + {label: "A0Oversize".translate(), value: "A0Oversize"}, + {label: "A0".translate(), value: "A0"}, + {label: "A1".translate(), value: "A1"}, + {label: "A2".translate(), value: "A2"}, + {label: "A3".translate(), value: "A3"}, + {label: "A4".translate(), value: "A4"}, + {label: "A5".translate(), value: "A5"}, + {label: "A6".translate(), value: "A6"}, + {label: "A7".translate(), value: "A7"}, + {label: "A8".translate(), value: "A8"}, + {label: "A9".translate(), value: "A9"}, + {label: "A10", value: "A10"}, + {label: "Screenshot640".translate(), value: "SH640"}, + {label: "Screenshot800".translate(), value: "SH800"}, + {label: "Screenshot1024".translate(), value: "SH1024"} + ] + }, + { + id: 'outputDocOrientation', + pmType: "dropdown", + name: 'out_doc_landscape', + labelWidth: '27%', + label: "Orientation".translate(), + controlsWidth: 165, + options: [ + { + label: "Portrait".translate(), + selected: true, + value: 0 + }, + { + label: "Landscape".translate(), + value: 1 + } + ], + valueType: 'number' + }, + docMargin, + { + id: 'outputDocToGenerate', + pmType: "dropdown", + name: 'out_doc_generate', + controlsWidth: 70, + labelWidth: '27%', + label: "Output Document to Generate".translate(), + options: [ + { + label: "Both".translate(), + value: "BOTH" + }, + { + label: "Doc".translate(), + value: "DOC" + }, + { + label: "Pdf".translate(), + value: "PDF" + } + ], + value: "BOTH", + onChange: function (newValue, prevValue) { + if (newValue == "DOC") { + formOutput.getFields()[11].setVisible(false); + outputFormDocPdfSecurityEnabled.setVisible(false); + outputFormDocPdfSecurityEnabled.setValue(0); + password.setVisible(false); + outputFormDocPdfSecurityOpen.setValue(""); + outputFormDocPdfSecurityOwner.setValue(""); + } else { + formOutput.getFields()[11].setVisible(true); + } + } + }, + outputFormDocPdfSecurityEnabled, + password, + { + id: 'outputDocEnableVersioning', + pmType: "dropdown", + name: "out_doc_versioning", + controlsWidth: 70, + labelWidth: '27%', + label: 'Enable versioning'.translate(), + options: [ + { + label: "Yes".translate(), + value: 1 + }, + { + label: "No".translate(), + selected: true, + value: 0 + } + ], + valueType: 'number' + }, + new CriteriaField({ + id: 'outputDocDestinationPath', + pmType: "text", + name: "out_doc_destination_path", + labelWidth: '27%', + label: "Destination Path".translate(), + controlsWidth: 340 + }), + new CriteriaField({ + id: 'outputDocTags', + pmType: "text", + name: "out_doc_tags", + labelWidth: '27%', + label: "Tags".translate(), + controlsWidth: 340 + }), + { + id: "outputDocGenerateFileLink", + name: "cboByGeneratedFile", + pmType: "dropdown", + controlsWidth: 155, + labelWidth: "27%", + label: "By clicking on the generated file link".translate(), + + options: [ + { + value: 0, + label: "Open the file".translate() + }, + { + label: "Download the file".translate(), + value: 1, + selected: true + } + ], + + valueType: "number" + } + ], + style: { + cssProperties: { + marginLeft: '20px' + } + } + }); + + formOutput.style.addProperties({marginLeft: '20px'}); + gridOutput = new PMUI.grid.GridPanel({ + id: 'gridOutput', + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'gridOutputButtonShow', + title: '', + dataType: 'button', + buttonLabel: 'Show ID'.translate(), + columnData: "out_doc_uid", + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + showUID(data.out_doc_uid); + } + }, + { + title: 'Title'.translate(), + dataType: 'string', + width: '392px', + alignment: "left", + columnData: "out_doc_title", + sortable: true, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: '100px', + alignmentCell: 'left', + columnData: "out_doc_type", + sortable: true + }, + { + id: 'gridOutputButtonEdit', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + buttonLabel: 'Edit'.translate(), + onButtonClick: function (row, grid) { + messageRequired.hide(); + setDataRow(row); + openFormForEditInMainWindow(); + } + }, + { + id: 'gridOutputButtonProperties', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + buttonLabel: 'Open Editor'.translate(), + onButtonClick: function (row, grid) { + setDataRow(row); + openTinyInMainWindow(row); + } + }, + { + id: 'gridOutputButtonDelete', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + setDataRow(row); + deleteDataRow(); + } + } + ] + }); + + btnSaveWindowOutputDoc = new PMUI.ui.Button({ + id: 'btnSaveWindowOutputDoc', + text: "Save".translate(), + handler: function () { + var dataAux = getData2PMUI(formOutput.html); + if (dataAux.out_doc_title != "" && dataAux.out_doc_filename != "") { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + itemOutPut = getData2PMUI(formOutput.html); + } else { + itemOutPut = formOutput.getData(); + } + + itemOutPut['out_doc_type'] = "HTML"; + + var items = jQuery.parseJSON(itemOutPut['out_doc_pdf_security_permissions']); + itemOutPut['out_doc_pdf_security_permissions'] = ''; + for (var i = 0; i < items.length; i += 1) { + itemOutPut['out_doc_pdf_security_permissions'] += (i == 0) ? items[i] : '|' + items[i]; + } + + itemOutPut["out_doc_landscape"] = parseInt(itemOutPut["out_doc_landscape"]); + itemOutPut["out_doc_pdf_security_enabled"] = parseInt(itemOutPut["out_doc_pdf_security_enabled"]); + itemOutPut["out_doc_versioning"] = parseInt(itemOutPut["out_doc_versioning"]); + itemOutPut["out_doc_open_type"] = parseInt(getData2PMUI(formOutput.html).cboByGeneratedFile); + + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + itemOutPut['out_doc_uid'] = dataOutPutDocument.out_doc_uid; + restClient = new PMRestClient({ + endpoint: "output-document/" + dataOutPutDocument.out_doc_uid, + typeRequest: 'update', + data: itemOutPut, + functionSuccess: function (xhr, response) { + dataOutPutDocument = itemOutPut; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document edited successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + } else { + if (1 === parseInt(dataAux.out_doc_pdf_security_enabled) && (dataAux.out_doc_pdf_security_open_password.trim() === "" || dataAux.out_doc_pdf_security_owner_password.trim() === "")) { + password.getItems()[0].getItems()[0].isValid(); + password.getItems()[0].getItems()[1].isValid(); + return false; + } + itemOutPut['out_doc_uid'] = ''; + restClient = new PMRestClient({ + endpoint: "output-document", + typeRequest: 'post', + data: itemOutPut, + functionSuccess: function (xhr, response) { + dataOutPutDocument = itemOutPut; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems saved the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document saved successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + } + clearDataRow(); + } else { + formOutput.getField("out_doc_title").isValid(); + formOutput.getField("out_doc_filename").isValid(); + } + }, + buttonType: 'success' + }); + + btnCloseWindowOutputDoc = new PMUI.ui.Button({ + id: 'btnCloseWindowOutputDoc', + text: "Cancel".translate(), + handler: function () { + clickedClose = false; + isDirtyFormOutput(); + }, + buttonType: 'error' + }); + + newButtonOutput = new PMUI.ui.Button({ + id: 'outputButtonNew', + text: 'Create'.translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + clearDataRow(); + openFormInMainWindow(); + } + }); + + btnCancelTiny = new PMUI.ui.Button({ + id: 'btnCloseTiny', + text: 'Cancel'.translate(), + handler: function () { + /*if (typeof dataOutPutDocument['externalType'] != 'undefined' && dataOutPutDocument['externalType']) { + winMainOutputDocument.close(); + return; + }*/ + PMDesigner.hideAllTinyEditorControls(); + clickedClose = false; + isDirtyFormOutput(); + }, + buttonType: 'error' + }); + + btnSaveTiny = new PMUI.ui.Button({ + id: 'btnSaveTiny', + text: 'Save'.translate(), + handler: function () { + PMDesigner.hideAllTinyEditorControls(); + dataOutPutDocument['out_doc_template'] = tinyMCE.activeEditor.getContent(); + updateOutput(dataOutPutDocument); + if (typeof dataOutPutDocument['externalType'] != 'undefined' && dataOutPutDocument['externalType']) { + winMainOutputDocument.close(); + return; + } + clearDataRow(); + refreshGridPanelInMainWindow(); + }, + buttonType: 'success' + }); + + winMainOutputDocument = new PMUI.ui.Window({ + id: "winMainOutputDocument", + title: "Output Documents".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: "bottom", + onBeforeClose: function () { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = true; + isDirtyFormOutput(); + }, + footerItems: [ + btnCancelTiny, + btnSaveTiny, + btnCloseWindowOutputDoc, + btnSaveWindowOutputDoc] + }); + + formOutput.addItem(editorTiny); + formOutput.footer.setVisible(false); + + winMainOutputDocument.addItem(gridOutput); + winMainOutputDocument.addItem(formOutput); + + refreshGridPanelInMainWindow(); + + validateKeysField(docMargin.getField('out_doc_left_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_right_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_top_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_bottom_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + + if (typeof listOutputDocs !== "undefined") { + winMainOutputDocument.open(); + $('#gridOutput .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + messageRequired = $(document.getElementById("requiredMessage")); + applyStyleWindowForm(winMainOutputDocument); + + editorTiny.isInitialized = false; + winMainOutputDocument.footer.html.style.textAlign = 'right'; + + gridOutput.dom.toolbar.appendChild(newButtonOutput.getHTML()); + newButtonOutput.defineEvents(); + winMainOutputDocument.defineEvents(); + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + } + }; + + PMDesigner.output.showTiny = function (uid) { + getItemdOutput = function () { + var restClientGet = new PMRestClient({ + endpoint: 'output-document/' + uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + dataOutPutDocument = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + restClientGet.executeRestClient(); + }; + getItemdOutput(); + dataOutPutDocument['externalType'] = true; + openTinyInMainWindow(dataOutPutDocument); + }; + + PMDesigner.output.create = function () { + openFormInMainWindow(); + }; +}()); + +( + function () { + var iframeRT, + reportWindow, + pathSrc; + + PMDesigner.reporttable = function (event) { + reportWindow = new PMUI.ui.Window({ + id: 'reportTableWindow', + title: "Report Tables".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT + }); + + pathSrc = window.parent.location; + + iframeRT = new PMIframe({ + id: 'reporTableIframe', + src: window.location.href.split("/")[0] + "//" + pathSrc.host + "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/pmTables?PRO_UID=" + PMDesigner.project.id + "&flagProcessmap=1", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 36, + scrolling: 'no', + frameborder: '0' + }); + + reportWindow.addItem(iframeRT); + reportWindow.open(); + reportWindow.setBodyPadding(0); + }; + + PMDesigner.reporttable.create = function () { + pathSrc = window.parent.location; + reportWindow.clearItems(); + iframeRT = new PMIframe({ + id: 'reporTableIframe', + src: window.location.href.split("/")[0] + "//" + pathSrc.host + "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/pmTables/edit?PRO_UID=" + PMDesigner.project.id + "&tableType=report&flagProcessmap=1", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 36, + scrolling: 'no', + frameborder: '0' + }); + reportWindow.addItem(iframeRT); + reportWindow.open(); + reportWindow.setBodyPadding(0); + } + + }() +); +(function () { + $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); + var btnCopyImport, openFormCustom, formEditTriggerCustom; + var triggerOriginDataForUpdate = {}; + PMDesigner.trigger = function (event) { + var listTriggers, + clickedClose = true, + message_ErrorWindow, + flagChanges, + isDirtyFormTrigger, + gridListTrigger, + getListTrigger, + addNumberTriggerWizard, + newTriggerOptions, + allTreesItems, + buttonNew, + buttonCopy, + buttonWizard, + openListTriggers, + openFormWizard, + openFormWizardEditMode, + openFormCopy, + openFormEditCode, + openNewTriggerOptions, + listProjects, + getListProjects, + triggerSelectedData, + formCopyTrigger, + codMirr, + formEditTriggerWizard, + sepInputs, + labelInputs, + paramPanel, + sepOutputs, + labelOutputs, + returnPanel, + parameterItems, + returnItems, + treeNewTrigger, + accordionNewTrigger, + updateCustom, + checkIfValuesAreEqual, + buttonSave, + copyButton, + applyButton, + btnEditSourceCode, + buttonCancel, + editCode, + formEditCode, + triggerWindow, + formcustom; + + message_ErrorWindow = new PMUI.ui.MessageWindow({ + id: "errorMessage", + width: 490, + windowMessageType: 'error', + title: "Triggers".translate(), + message: "This is an error message.".translate(), + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + message_ErrorWindow.close(); + }, + buttonType: "success" + } + ] + }); + + isDirtyFormTrigger = function () { + $("input,select,textarea").blur(); + $("div.pmui-window-body.pmui-background").css('overflow', ''); + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + var flag = false; + + var finalData = { + tri_uid: getData2PMUI(formEditTriggerCustom.html).uid, + tri_title: getData2PMUI(formEditTriggerCustom.html).title, + tri_description: getData2PMUI(formEditTriggerCustom.html).description, + tri_webbot: getData2PMUI(formEditTriggerCustom.html).code + }; + + if (formcustom.isVisible() == true) { + flag = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + } else if (formwizard.isVisible() == true) { + flag = formEditTriggerWizard.isDirty(); + } else if (formcopy.isVisible() == true) { + flag = formCopyTrigger.isDirty(); + if (!flag) { + $('.ctrlSpaceMessage').remove(); + } + } else if (formeditcode.isVisible() == true) { + flag = formeditcode.isDirty(); + var flagFormCustom = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + if (!flag && formeditcode.getItems()[0].controls[0].value != "" || flagFormCustom) { + flag = true; + } + } + + if (flag == true) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, { + text: "Yes".translate(), + handler: function () { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + $('.ctrlSpaceMessage').remove(); + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } + message_window.close(); + if (clickedClose) { + triggerWindow.close(); + } + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } else if (accordionnewtrigger.isVisible() == true) { + openListTriggers(); + } + if (clickedClose) { + triggerWindow.close(); + } + } + }; + //GRID List Case Scheduler + gridListTrigger = new PMUI.grid.GridPanel({ + id: "listTriggers", + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'listTriggersButtonShow', + title: '', + dataType: 'button', + searchable: false, + buttonLabel: 'Show ID'.translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + id: 'copyuid', + onButtonClick: function (row, grid) { + var dataRow = row.getData(); + messageWindow = new PMUI.ui.MessageWindow({ + id: 'dynaformMessageWindowUID', + windowMessageType: 'info', + width: 490, + title: "Triggers".translate(), + message: dataRow.tri_uid, + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + messageWindow.close(); + }, + buttonType: "success" + } + ] + }); + messageWindow.setTitle("ID".translate()); + messageWindow.open(); + messageWindow.showFooter(); + $(messageWindow.dom.icon).removeClass(); + } + }, + { + title: 'Title'.translate(), + id: "title", + dataType: 'string', + width: "407px", + visible: true, + columnData: "tri_title", + searcheable: true, + sortable: true, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + id: "type", + dataType: 'string', + width: "225px", + visible: true, + alignmentCell: 'left', + columnData: function (data) { + if (typeof(data.tri_param) == "object" && typeof(data.tri_param.params) == "object") { + var wizardData = data.tri_param.params; + + return wizardData.LIBRARY_NAME; + } else { + return "Custom"; + } + }, + searcheable: true, + sortable: true + }, + { + id: "editButton", + title: '', + dataType: 'button', + messageTooltip: "Edit".translate(), + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + triggerOriginDataForUpdate = {}; + var data = row.getData(); + triggerOriginDataForUpdate = data; + var fields; + if (data.tri_param == "") { + + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 160); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.tri_uid); + fields.getItems()[1].setValue(data.tri_title); + fields.getItems()[2].setValue(data.tri_description); + formEditTriggerCustom.getItems()[1].setValue(data.tri_webbot); + + codeMirrorControl.setValue(data.tri_webbot); + codeMirrorControl.refresh(); + } else { + openFormWizardEditMode(); + + var wizardData = data.tri_param.params; + + var lib = wizardData.LIBRARY_CLASS; + lib = lib.split('.'); + lib = lib[1]; + fields = formEditTriggerWizard.getFields(); + fields[0].setValue(data.tri_uid); + fields[1].setValue(lib); + fields[2].setValue(wizardData.PMFUNTION_NAME); + fields[3].setValue(wizardData.LIBRARY_NAME + " (" + wizardData.PMFUNTION_LABEL + ")"); + fields[4].setValue(data.tri_title); + fields[5].setValue(data.tri_description); + fields[6].setValue(data.tri_webbot); + + var inputItems = []; + var outputItems = []; + + restClient = new PMRestClient({ + endpoint: "trigger-wizard/" + lib + "/" + wizardData.PMFUNTION_NAME, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (response.fn_params.input != undefined) { + for (j = 0; j < response.fn_params.input.length; j++) { + var nameInput = response.fn_params.input[j].name; + + var inp = new CriteriaField({ + id: nameInput, + pmType: "text", + name: nameInput, + label: response.fn_params.input[j].label, + value: wizardData[nameInput].toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.input[j].description, + required: response.fn_params.input[j].name === "unpauseDate" ? true : response.fn_params.input[j].required + }); + + inputItems.push(inp); + } + } + if (response.fn_params.output != undefined) { + for (k = 0; k < response.fn_params.output.length; k++) { + var nameOutput = response.fn_params.output[k].name; + + var out = new CriteriaField({ + id: nameOutput, + pmType: "text", + name: nameOutput, + label: response.fn_params.output[k].label, + value: wizardData.TRI_ANSWER.toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.output[k].description, + required: response.fn_params.output[k].required + }); + + outputItems.push(out); + } + } + triggerWindow.setTitle("Edit".translate() + " " + wizardData.LIBRARY_NAME); + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + } + }, + { + id: "deleteButton", + title: '', + dataType: 'button', + messageTooltip: "Delete".translate(), + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var questionWindow, dataRow = row.getData(); + + questionWindow = new PMUI.ui.MessageWindow({ + id: "questionDeleteWindow", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: "Do you want to delete this Trigger?".translate(), + footerItems: [ + { + id: 'questionDeleteWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + questionWindow.close(); + }, + buttonType: "error" + }, { + id: 'questionDeleteWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + questionWindow.close(); + restClient = new PMRestClient({ + endpoint: "trigger/" + dataRow.tri_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger deleted successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }, + buttonType: "success" + }, + ] + }); + + questionWindow.open(); + questionWindow.dom.titleContainer.style.height = "17px"; + questionWindow.showFooter(); + } + } + ], + dataItems: listTriggers, + onRowClick: function (row, data) { + + } + }); + + getListTrigger = function () { + var restClient = new PMRestClient({ + endpoint: 'triggers', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listTriggers = response; + gridListTrigger.setDataItems(listTriggers); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + + addNumberTriggerWizard = function (value, position) { + coutTriggers = document.createElement("span"); + coutTriggers.textContent = value; + headerAccordion = triggerWindow.getItems()[5].getItems()[position].header.html; + headerAccordion.appendChild(coutTriggers); + coutTriggers.style.float = "right"; + coutTriggers.style.color = "white"; + coutTriggers.style.fontSize = "13px"; + coutTriggers.style.marginRight = "6px"; + coutTriggers.style.marginTop = "3px"; + }; + + newTriggerOptions = function () { + + var acItemCustom = accordionNewTrigger.getItems()[0]; + var acItemCopy = accordionNewTrigger.getItems()[1]; + acItemCustom.setIconClosed('pmcustomtrigger'); + acItemCustom.setIconExpanded('pmcustomtrigger'); + acItemCopy.setIconClosed('pmcopytrigger'); + acItemCopy.setIconExpanded('pmcopytrigger'); + + var itemCustom = jQuery("#custom > .pmui-accordion-item-header > span")[1]; + itemCustom.style.width = "0px"; + var itemCopy = jQuery("#copy > .pmui-accordion-item-header > span")[1]; + itemCopy.style.width = "0px"; + + var numOfItems = accordionNewTrigger.getItems(); + + var lengthLibFunctions = []; + if (numOfItems.length <= 2) { + restClient = new PMRestClient({ + endpoint: "trigger-wizards", + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (i = 0; i < response.length; i++) { + var functTree = response[i].lib_functions; + lengthLibFunctions[i] = functTree.length; + var newTreeItems = []; + for (h = 0; h < functTree.length; h++) { + newTreeItems.push({ + label: functTree[h].fn_label, + id: functTree[h].fn_name, + onClick: function () { + for (s = 0; s < response.length; s++) { + for (p = 0; p < response[s].lib_functions.length; p++) { + if (response[s].lib_functions[p].fn_name == this.id) { + var fn = response[s].lib_functions[p].fn_params; + var fnLabel = response[s].lib_functions[p].fn_label; + var fnName = response[s].lib_functions[p].fn_name; + var libName = response[s].lib_name; + var libTitle = response[s].lib_title; + p = response[s].lib_functions.length; + s = response.length - 1; + } + } + } + var inputItems = []; + if (fn.input != undefined) { + for (j = 0; j < fn.input.length; j++) { + var val = ""; + if (fn.input[j].type == "array") { + val = "array('')"; + } + var inp = new CriteriaField({ + id: fn.input[j].name, + pmType: "text", + name: fn.input[j].name, + label: fn.input[j].label, + controlsWidth: 400, + labelWidth: '27%', + value: val, + helper: fn.input[j].description, + required: fn.input[j].name === "unpauseDate" ? true : fn.input[j].required + }); + + inputItems.push(inp); + } + } + + var outputItems = []; + if (fn.output != undefined) { + for (k = 0; k < fn.output.length; k++) { + var out = new CriteriaField({ + id: fn.output[k].name, + pmType: "text", + name: fn.output[k].name, + label: fn.output[k].label, + controlsWidth: 400, + labelWidth: '27%', + helper: fn.output[k].description, + required: fn.output[k].required + }); + + outputItems.push(out); + } + } + formEditTriggerWizard.reset(); + formEditTriggerWizard.setTitle(fnLabel + ' (' + fnName + ')'); + formEditTriggerWizard.getItems()[0].getItems()[1].setValue(libName); + formEditTriggerWizard.getItems()[0].getItems()[2].setValue(fnName); + formEditTriggerWizard.getItems()[0].getItems()[3].setValue(libTitle + ' (' + fnLabel + ')'); + + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + openFormWizard(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + triggerWindow.setTitle("Create".translate() + " " + libTitle); + } + }); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + allTreesItems[i] = newTreeItems; + + var arrayTriggerWizards = [ + "pmFunctions", + "pmSugar", + "pmTalend", + "pmTrAlfresco", + "pmTrSharepoint", + "pmZimbra" + ]; + + if (arrayTriggerWizards.indexOf(response[i].lib_name) == -1) { + $("head").append(""); + } + + //Accordion + var newAccordionItem = []; + newAccordionItem = { + iconClass: response[i].lib_name, + id: response[i].lib_name, + title: response[i].lib_title, + height: 'auto' + }; + accordionNewTrigger.addItem(newAccordionItem); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + + openNewTriggerOptions(); + var accordion = triggerWindow.getItems()[5].getItems(); + accordion[0].setVisible(false); + accordion[1].setVisible(false); + for (i = 0; i < accordion.length; i++) { + accordion[i].header.html.style.backgroundColor = "#FFFFFF"; + if (i > 1) { + addNumberTriggerWizard(lengthLibFunctions[i - 2], (i)); + } + } + }; + + allTreesItems = []; + getListTrigger(); + + //Button NEW Trigger + buttonNew = new PMUI.ui.Button({ + id: 'newTriggerButton', + text: "Create".translate(), + height: "36px", + width: 100, + handler: function (event) { + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + codeMirrorControl.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button COPY Trigger + buttonCopy = new PMUI.ui.Button({ + id: 'copyTriggerButton', + text: "Copy".translate(), + height: "36px", + width: 100, + handler: function (event) { + getListProjects(); + openFormCopy(); + formCopyTrigger.getFields()[1].clearOptions(); + $("#Code .CodeMirror.cm-s-default.CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + cmControlCopyTrigger.setValue(""); + if (cmControlCopyTrigger !== undefined) { + cmControlCopyTrigger.setSize(650, 140); + } + cmControlCopyTrigger.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button WIZARD Trigger + buttonWizard = new PMUI.ui.Button({ + id: 'wizardTriggerButton', + text: "Wizard".translate(), + height: "36px", + width: 100, + handler: function (event) { + newTriggerOptions(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + openListTriggers = function () { + triggerWindow.getItems()[0].setVisible(true); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Triggers".translate()); + triggerWindow.hideFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + openFormCustom = function (typeTitle) { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(true); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + + triggerWindow.setTitle(typeTitle + " Custom Trigger".translate()); + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerCustom.setFocus(); + + $('.CodeMirror.cm-s-default')[0].style.border = "1px solid #c0c0c0"; + if (formEditTriggerCustom.getItems()[0].getItems()[1].visible == false) { + var fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[1].setVisible(true); + fields.getItems()[2].setVisible(true); + formEditTriggerCustom.footer.getItems()[1].setVisible(true); + } + formEditTriggerCustom.getFields()[4].dom.labelTextContainer.style.marginLeft = "10px"; + formEditTriggerCustom.setAlignmentButtons('left'); + + $("#code").after($ctrlSpaceMessage.css({ + "margin": "5px 0 0 0", + "text-align": "center", + "width": "655px", + "padding": "" + })); + }; + + openFormWizard = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + openFormWizardEditMode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(true); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + + openFormCopy = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(true); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Copy Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(true); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formCopyTrigger.setFocus(); + + $(".pmui-field").css("float", "left"); + $('#Code .pmui.pmui-pmcodemirrorcontrol').append($ctrlSpaceMessage.css({ + "margin-top": "10px", + "text-align": "", + "width": "655px", + "padding": "" + })); + }; + + openFormEditCode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(true); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Editor".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(true); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).after($ctrlSpaceMessage.css({ + "padding": "5px 0 0 10px", + "text-align": "" + })); + + }; + + openNewTriggerOptions = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(true); + triggerWindow.setTitle("Create Predefined Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + //obtaning the list of process to show it on the copy/import of a trigger dropdown + listProjects = []; + getListProjects = function () { + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listProjects = []; + formCopyTrigger.getFields()[0].clearOptions(); + listProjects[0] = { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }; + for (i = 0; i < response.length; i++) { + listProjects.push({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } + formCopyTrigger.getFields()[0].setOptions(listProjects); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of projects.".translate() + }); + restClient.setBaseEndPoint('projects'); + restClient.executeRestClient(); + }; + + //form Copy/Import Trigger + triggerSelectedData; + formCopyTrigger = new PMUI.form.Form({ + id: "formCopyTriggers", + border: true, + width: '890px', + height: 'auto', + title: "", + visibleHeader: false, + items: [ + { + pmType: 'dropdown', + id: "processField", + label: 'Process'.translate(), + name: 'prj_uid', + required: true, + controlsWidth: 300, + value: "", + options: listProjects, + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidProj = newValue, myForm = this.form; + + //obtaning the Trigger list of the process SELECTED + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + triggerSelectedData = response; + var listTriggersCopy = []; + listTriggersCopy[0] = { + label: "- Select a trigger -".translate(), + value: "", + disabled: true, + selected: true + }; + + for (i = 0; i < response.length; i++) { + listTriggersCopy.push({ + label: response[i].tri_title, + value: response[i].tri_uid + }); + } + formFields[1].setOptions(listTriggersCopy); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of triggers.".translate() + }); + restClient.setBaseEndPoint("project/" + uidProj + "/triggers"); + restClient.executeRestClient(); + } + }, + { + pmType: 'dropdown', + id: "triggerField", + label: 'Trigger'.translate(), + name: 'tri_uid', + required: true, + controlsWidth: 300, + value: "", + options: [], + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidTri = newValue; + + for (i = 0; i < triggerSelectedData.length; i++) { + if (triggerSelectedData[i].tri_uid == uidTri) { + formFields[2].setValue(triggerSelectedData[i].tri_title); + formFields[3].setValue(triggerSelectedData[i].tri_description); + formFields[4].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + } + } + } + }, + { + pmType: "text", + id: "triTitle", + label: "Title of the new trigger".translate(), + placeholder: "Insert the title of the new trigger".translate(), + name: "tri_title", + required: true, + valueType: 'string', + controlsWidth: 300, + style: { + cssProperties: { + 'float': 'left' + } + } + }, + { + pmType: "textarea", + id: "triDescription", + rows: 80, + name: 'tri_description', + label: "Description of the new trigger".translate(), + valueType: 'string', + controlsWidth: 652, + style: { + cssClasses: ['mafe-textarea-resize'], + cssProperties: {'float': 'left'} + } + } + ] + }); + codMirr = new PMCodeMirrorField(); + codMirr.setLabel("Code".translate()); + codMirr.setID("Code"); + codMirr.setName('tri_webbot'); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + formCopyTrigger.addItem(codMirr); + + //Form to Edit the trigger with the WIZARD (we used a Form because we need buttons to save the changes) + formEditTriggerWizard = new PMUI.form.Form({ + id: "formEditTriggerWizard", + border: true, + visibleHeader: false, + name: "formwizard", + width: 926, + title: "New Trigger".translate(), + items: [ + { + id: "panelDetailsWizard", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: 'auto', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + visible: false, + valueType: 'string' + }, + { + id: "libName", + pmType: "text", + label: "", + value: "", + name: "libName", + visible: false, + valueType: 'string' + }, + { + id: "fnName", + pmType: "text", + label: "", + value: "", + name: "fnName", + visible: false, + valueType: 'string' + }, + { + id: "type", + pmType: "text", + label: "Type".translate(), + value: "WIZARD", + controlsWidth: 450, + labelWidth: '27%', + readOnly: true, + name: "type", + valueType: 'string' + }, + { + id: "titleDetailsWiz", + pmType: "text", + label: "Title".translate(), + value: "", + controlsWidth: 450, + labelWidth: '27%', + name: "titleDetails", + valueType: 'string', + required: true + }, + { + id: "descriptionDetailsWiz", + pmType: "textarea", + label: "Description".translate(), + value: "", + rows: 90, + width: '300px', + controlsWidth: 450, + labelWidth: '27%', + name: "descriptionDetails", + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "webbot", + pmType: "text", + label: "Webbot".translate(), + value: "", + name: "webbot", + controlsWidth: 300, + labelWidth: '27%', + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + //adding a separator Inputs line + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepInputs); + + //adding a label Inputs + labelInputs = new PMLabelField({ + text: "PARAMETERS".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + formEditTriggerWizard.addItem(labelInputs); + + //adding the Inputs Items (PARAMETERS) Panel + paramPanel = new PMUI.form.FormPanel({ + id: "panelParametersWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "__PARAMETERS__".translate(), + items: [] + }); + formEditTriggerWizard.addItem(paramPanel); + + //adding a separator Outputs line + sepOutputs = new PMSeparatorLineField({ + controlHeight: 1, + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepOutputs); + + //adding a label Outputs + labelOutputs = new PMLabelField({ + text: "RETURN VALUE".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + + formEditTriggerWizard.addItem(labelOutputs); + + //adding the Output Items (Returns) Panel + returnPanel = new PMUI.form.FormPanel({ + id: "panelReturnValWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "RETURN VALUE".translate(), + items: [] + }); + formEditTriggerWizard.addItem(returnPanel); + + + //treePanel New Trigger PMF + treeNewTrigger = new PMUI.panel.TreePanel({ + id: "treeNewTrigger", + width: 'auto', + height: 'auto', + style: { + cssClasses: ['pmtrigger'], + cssProperties: { + 'margin-top': '5px', + 'margin-bottom': '4px' + } + }, + items: [] + }); + + //Acordion Panel New Triggers Options + accordionNewTrigger = new PMUI.panel.AccordionPanel({ + id: "accordionNewTrigger", + width: 885, + height: 'auto', + borderWidth: "0px", + hiddenTitle: true, + style: { + cssProperties: { + 'margin-left': '30px' + } + }, + items: [ + { + iconClass: "", + id: 'custom', + title: "Custom Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + }, + { + iconClass: "", + id: 'copy', + title: "Copy Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + } + ], + listeners: { + select: function (obj, event) { + + if (obj.id == "custom") { + openFormCustom("Create".translate()); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 150); //CodeMirror Size + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + + } else if (obj.id == "copy") { + + getListProjects(); + openFormCopy(); + $($('#Code .CodeMirror.cm-s-default.CodeMirror-wrap')[1]).css({'border': '1px solid #c0c0c0'}); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + if (cmControlCopyTrigger != undefined) { + cmControlCopyTrigger.setSize(650, 140); //CodeMirror in formCopyTrigger Size + } + } else { + if (treeNewTrigger.getItems() == "" || treeNewTrigger.id != obj.id) { + var acItems = accordionNewTrigger.getItems(); + var accordionActualItem = accordionNewTrigger.getItem(obj.id); + + for (i = 0; i < acItems.length; i++) { + if (acItems[i].id == accordionActualItem.id) { + var positionActualAcItem = i - 2; + } + } + + treeNewTrigger.setItems(allTreesItems[positionActualAcItem]); + treeNewTrigger.setID(obj.id); + + accordionActualItem.setBody(treeNewTrigger); + treeNewTrigger.defineEvents(); + applyStyleTreePanel(treeNewTrigger, false); + } + } + } + } + }); + + updateCustom = function (dataToSend, triggerUid) { + var restClient = new PMRestClient({ + endpoint: "trigger/" + triggerUid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message; + var arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }; + + checkIfValuesAreEqual = function (initialData, finalData) { + if (typeof(initialData['tri_uid']) == "undefined" && finalData['tri_uid'] == '') { + if (finalData['tri_description'] != '' || finalData['tri_title'] != '' || finalData['tri_webbot'] != '') { + return false; + } + } + for (var key1 in initialData) { + for (var key2 in finalData) { + if (typeof(initialData[key1]) != "undefined" && + typeof(finalData[key2]) != "undefined" && + key1 == key2 && + initialData[key1] != finalData[key2] + ) { + return false; + } + } + } + return true; + } + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + buttonSave = new PMUI.ui.Button({ + id: 'saveTriggerButton', + text: "Save".translate(), + handler: function (event) { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1], + formwizard = triggerWindow.getItems()[2], + formTriggerData, + restClient, + dataToSend, + formTriggerData, + inputFields, + message_window, + outputV, + outputFields, + inputV, + dataToSend, + flagEdit; + if (formcustom.isVisible() == true) { + valuesCustom=formcustom.getItems()[0]; + if (!formEditTriggerCustom.isValid( )) { + flagEdit = formEditTriggerCustom.visible; + } else { + flagEdit = formEditTriggerCustom.isValid(); + } + if (flagEdit) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerCustom.html); + } else { + formTriggerData = formEditTriggerCustom.getData(); + } + if (formTriggerData.title.trim() === "") { + return false; + } + dataToSend = { + tri_title: formTriggerData.title, + tri_description: formTriggerData.description, + tri_webbot: formTriggerData.code, + tri_param: "" + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + formEditTriggerCustom.getItems()[0].getItems()[0].setValue(response.tri_uid); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message, + arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + if (formTriggerData.wizzard != "") { + if (formEditTriggerCustom.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "wizzardToCustomTriggerWin", + windowMessageType: 'warning', + title: 'Triggers'.translate(), + width: 490, + message: 'Do you want to save the changes? This Trigger will be saved like a custom Trigger.'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + openFormWizardEditMode(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.reset(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + updateCustom(dataToSend, formTriggerData.uid); + }, + buttonType: "success" + } + ] + + }); + message_window.open(); + message_window.showFooter(); + } else { + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + } + } else { + updateCustom(dataToSend, formTriggerData.uid); + } + } + } + } else if (formwizard.isVisible() == true) { + if (formEditTriggerWizard.isValid() || ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1))) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerWizard.html); + } else { + formTriggerData = formEditTriggerWizard.getData(); + } + + inputV = {}; + inputFields = formEditTriggerWizard.getItems()[3]; + for (i = 0; i < inputFields.getItems().length; i++) { + inputV[inputFields.getItems()[i].name] = formTriggerData[inputFields.getItems()[i].name]; + } + + outputV = {}; + outputFields = formEditTriggerWizard.getItems()[6]; + for (j = 0; j < outputFields.getItems().length; j++) { + outputV[outputFields.getItems()[j].name] = formTriggerData[outputFields.getItems()[j].name]; + } + + dataToSend = { + tri_title: formTriggerData.titleDetails, + tri_description: formTriggerData.descriptionDetails, + tri_type: "SCRIPT", + tri_params: { + input: inputV, + output: outputV + } + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName, + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + formEditTriggerWizard.getFields()[0].setValue(response.tri_uid); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName + '/' + formTriggerData.uid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + } + }, + buttonType: 'success' + }); + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + copyButton = new PMUI.ui.Button({ + id: 'copyAndSaveButton', + text: "Copy Trigger".translate(), + buttonType: 'success', + handler: function (event) { + var data, + dataToSend, + restClient; + if (formCopyTrigger.isValid()) { + formCopyTrigger.setDirty(false); + + data = formCopyTrigger.getData(); + dataToSend = { + tri_title: getData2PMUI(formCopyTrigger.html).tri_title.trim(), + tri_description: data.tri_description, + tri_webbot: data.tri_webbot, + tri_param: "" + }; + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + getListTrigger(); + formCopyTrigger.reset(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + }); + + //Buttons Apply for the Code Editor + applyButton = new PMUI.ui.Button({ + id: 'applyButton', + text: "Apply".translate(), + buttonType: 'success', + handler: function (event) { + + $("div.pmui-window-body.pmui-background").css('overflow', ''); + if (formEditCode.isValid()) { + var typeTitle = "Edit".translate(); + if (triggerWindow.getItems()[1].getData().uid == "") { + typeTitle = "Create".translate(); + } + openFormCustom(typeTitle); + formEditCode.setDirty(false); + + var editCode = formEditCode.getItems()[0].controls[0].cm; + editCodeValue = editCode.getValue(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorCustom != undefined) { + codeMirrorCustom.setSize(580, 150); //CodeMirror Size + } + codeMirrorCustom.setValue(editCodeValue); + formEditTriggerCustom.getItems()[1].setValue(editCodeValue); + + editCode.setValue(""); + editCodeValue = ""; + + formEditCode.getItems()[0].setValue(""); + } + } + }); + + //Button Edit Source Code (this is showed just when the Trigger Wizzard is opened in edition mode) + btnEditSourceCode = new PMUI.ui.Button({ + id: 'btnEditSourceCode', + text: "Edit Source Code".translate(), + buttonType: 'success', + handler: function (event) { + + var data = formEditTriggerWizard.getData(); + var fields; + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(650, 280); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.uid); + fields.getItems()[1].setValue(data.titleDetails); + fields.getItems()[2].setValue(data.descriptionDetails); + fields.getItems()[3].setValue(data.webbot); + fields.getItems()[3].setVisible(false); + formEditTriggerCustom.getItems()[1].setValue(data.webbot); + + codeMirrorControl.setValue(data.webbot); + + formEditTriggerCustom.getItems()[1].setHeight(300); + fields.getItems()[1].setVisible(false); + fields.getItems()[2].setVisible(false); + formEditTriggerCustom.footer.getItems()[1].setVisible(false); + formEditTriggerCustom.footer.getItems()[0].style.addProperties({'margin-right': "10px"}); + formEditTriggerCustom.footer.style.addProperties({width: '880px'}); + codeMirrorControl.refresh(); + } + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelTriggerButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + isDirtyFormTrigger(); + } + }); + + //Form to Edit the Custom trigger (we used a Form because we need buttons to save the changes) + formEditTriggerCustom = new PMUI.form.Form({ + id: "formEditTriggerCustom", + border: true, + visibleHeader: false, + width: '900px', + height: "365px", + name: "formcustom", + title: "Custom Trigger".translate(), + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + readOnly: true, + visible: false, + valueType: 'string' + }, + { + id: "title", + pmType: "text", + label: "Title".translate(), + value: "", + required: true, + name: "title", + valueType: 'string' + }, + { + id: "description", + pmType: "textarea", + rows: 70, + name: 'description', + label: "Description".translate(), + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "wizzard", + pmType: "text", + label: "Wizzard".translate(), + value: "", + name: "wizzard", + readOnly: true, + visible: false, + valueType: 'string' + } + ] + } + ], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditTriggerCustom.getItems()[1].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '208px', + "background": "rgb(30, 145, 209)", + "border": "0px solid rgb(30, 145, 209)" + } + } + }, { + text: "Open Editor".translate(), + id: "openEditorButton", + handler: function () { + openFormEditCode(); + formEditCode.showFooter(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + var value = codeMirrorCustom.getValue(); + + var codeMirrorCopy = formEditCode.getItems()[0].controls[0].cm; + + if (codeMirrorCopy != undefined) { + codeMirrorCopy.setSize(810, 315); //CodeMirror Size + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({'border': '1px solid #c0c0c0'}); + + } + + formEditCode.getItems()[0].setHeight(325); + + codeMirrorCopy.setValue(value); + formEditCode.getItems()[0].setValue(value); + formEditCode.setDirty(false); + + $('#codeEditor .pmui-field-label').hide(); + $('#formEditCode').children().last().css({ + 'margin-top': '-352px', + 'border': '0px', + 'margin-right': '-15px' + }).find('a').css('padding', '10px 5px'); + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({ + 'margin-left': '10px', + 'width': '850px', + 'height': '360px' + }); + $('#triggerWindow .pmui-window-body').css('overflow', 'hidden'); + codeMirrorCopy.refresh(); + }, + style: { + cssProperties: { + "margin-right": 2 + } + } + } + ] + }); + cd = new PMCodeMirrorField({ + labelWidth: '23.8%' + }); + cd.setLabel("Code".translate()); + formEditTriggerCustom.addItem(cd); + formEditTriggerCustom.getItems()[1].setName('code'); + formEditTriggerCustom.getItems()[1].setID('code'); + + formEditCode = new PMUI.form.Form({ + id: "formEditCode", + border: true, + visibleHeader: false, + width: '925px', + name: "formeditcode", + title: "Editor".translate(), + items: [], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditCode.getItems()[0].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '229px', + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + } + } + } + ] + }); + editCode = new PMCodeMirrorField({ + labelWidth: '9%' + }); + editCode.setLabel("Code".translate()); + formEditCode.addItem(editCode); + formEditCode.getItems()[0].setName('codeEditor'); + formEditCode.getItems()[0].setID('codeEditor'); + + //Trigger Window + triggerWindow = new PMUI.ui.Window({ + id: "triggerWindow", + title: "Triggers".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave, + btnEditSourceCode, + applyButton, + copyButton + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + isDirtyFormTrigger(); + } + }); + + + triggerWindow.addItem(gridListTrigger); + triggerWindow.addItem(formEditTriggerCustom); + triggerWindow.addItem(formEditTriggerWizard); + triggerWindow.addItem(formCopyTrigger); + triggerWindow.addItem(formEditCode); + triggerWindow.addItem(accordionNewTrigger); + + if (typeof listTriggers !== "undefined") { + triggerWindow.open(); + codMirr.dom.labelTextContainer.style.width = "23.8%"; + codMirr.html.style.padding = "10px"; + formEditTriggerCustom.panel.html.style.padding = "10px 10px"; + $('#listTriggers .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + applyStyleWindowForm(triggerWindow); + triggerWindow.hideFooter(); + openListTriggers(); + + gridListTrigger.dom.toolbar.appendChild(buttonNew.getHTML()); + buttonNew.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonCopy.getHTML()); + buttonCopy.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonWizard.getHTML()); + buttonWizard.defineEvents(); + + triggerWindow.defineEvents(); + gridListTrigger.sort('tri_title', 'asc'); + formEditTriggerCustom.panel.style.addProperties({'overflow': 'hidden'}); + + formcustom = triggerWindow.getItems()[1]; + valuesCustom=formcustom.getItems()[0]; + } + }; + + PMDesigner.trigger.create = function () { + var codeMirrorControl, cmControlCopyTrigger; + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + codeMirrorControl.refresh(); + } + codeMirrorControl.refresh(); + formEditTriggerCustom.getItems()[1].setHeight(170); + formEditTriggerCustom.reset(); + }; +}()); +/** + * new stepTask module + */ +var stepsTask = function (activity) { + this.mainWindow = null; + this.secondaryWindow = null; + this.stepsAssignTree = null; + this.mainContainer = null; + this.labelsPanel = null; + this.stepsMainContainer = null; + this.stepsAssignAccordion = null; + this.confirmWindow = null; + this.elementAccordionOpen = null; + this.groupType = null; + this.groupLabel = null; + this.stepsType = null; + this.stepsAssigned = null; + stepsTask.prototype.initialize.call(this, activity); +}; +/** + * initialization method steps settings, constants are created. + * components are created + * the data is loaded + * styles are customized + * It extends behaviors and events + */ +stepsTask.prototype.initialize = function () { + this.groupType = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL']; + this.groupLabel = ['Dynaform (s)'.translate(), 'Input Document (s)'.translate(), 'OutPut Document (s)'.translate(), 'External (s)'.translate()]; + this.stepsType = { + "DYNAFORM": "Dynaform".translate(), + "INPUT_DOCUMENT": "Input Document".translate(), + "OUTPUT_DOCUMENT": "Output Document".translate(), + "EXTERNAL": "External".translate() + }; + this.stepsAssigned = new PMUI.util.ArrayList(); + this.elementAccordionOpen = new PMUI.util.ArrayList(); + this.createWidgets(); + this.mainWindow.addItem(this.mainContainer); + this.mainWindow.open(); + this.loadInitialData(); + this.customStyles(); + this.elementsAccordionOpenFixed(); + this.addEventSortableInAccordionElements(); + this.addEventSortableInTreePanelElements(); +}; +/** + * the components are created PMUI UI + * - confirmWindow + * - mainWindow + * - labelsPanel + * - stepsAssignTree + * - stepsAssignAccordion + * - stepsMainContainer + * - mainContainer + * - secondaryWindow + */ +stepsTask.prototype.createWidgets = function () { + var that = this; + this.confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: '', + message: '', + footerItems: [ + { + id: 'confirmWindow-footer-no', + text: 'No'.translate(), + visible: true, + buttonType: "error" + }, { + id: 'confirmWindow-footer-yes', + text: 'Yes'.translate(), + visible: true, + buttonType: "success" + } + ], + visibleFooter: true + }); + this.mainWindow = new PMUI.ui.Window({ + id: "stepsForTask", + title: "Steps for task".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH + }); + this.labelsPanel = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + proportion: 0.08, + layout: "hbox", + items: [ + new PMUI.field.TextAnnotationField({ + text: 'Available Elements'.translate(), + text_Align: 'center', + proportion: 1.4 + }), + new PMUI.field.TextAnnotationField({ + text: 'Assigned Elements (Drop here)'.translate(), + text_Align: 'center', + proportion: 1.3 + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Expand all".translate(), + id: "expand-button", + proportion: 0.6, + handler: function () { + var items, i, item, buttonAfected; + items = that.stepsAssignAccordion.getItems(); + buttonAfected = that.labelsPanel.getItem("collapse-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + that.elementAccordionOpen.clear(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + item.expand(); + that.elementAccordionOpen.insert(item); + } + } + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Collapse all".translate(), + id: "collapse-button", + proportion: 0.7, + disabled: true, + handler: function () { + var items, i, item, buttonAfected; + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + items = that.stepsAssignAccordion.getItems(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + that.elementAccordionOpen.remove(item); + item.collapse(); + } + } + }) + ] + }); + this.stepsAssignTree = new PMUI.panel.TreePanel({ + id: 'stepsAssignTree', + proportion: 0.5, + height: 475, + filterable: true, + autoBind: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nodeDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true, + collapsed: false, + itemsDataBind: 'items', + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + behavior: 'drag' + }, + style: { + cssProperties: { + margin: '0px 0px 0px 0px', + float: 'left', + overflow: 'auto' + }, + cssClasses: ['mafe-border-panel'] + } + }); + this.stepsAssignAccordion = new PMUI.panel.AccordionPanel({ + id: 'stepsAssignAccordion', + multipleSelection: true, + hiddenTitle: true, + proportion: 1.5, + style: { + cssProperties: { + margin: '0px 0px 0px 0px' + }, + cssClasses: ['mafe-border-panel'] + }, + listeners: { + select: function (accordionItem, event) { + var buttonExpand, buttonCollapse, itemsAccod; + itemsAccod = that.stepsAssignAccordion.items; + if (accordionItem.collapsed) { + if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { + that.elementAccordionOpen.remove(accordionItem); + } + } else { + if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { + that.elementAccordionOpen.insert(accordionItem); + } + } + buttonCollapse = that.labelsPanel.getItem("collapse-button"); + buttonExpand = that.labelsPanel.getItem("expand-button"); + if (that.elementAccordionOpen.getSize() === 0) { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(true); + } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { + buttonExpand.setDisabled(true); + buttonCollapse.setDisabled(false); + } else { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(false); + } + } + } + }); + this.stepsMainContainer = new PMUI.core.Panel({ + id: "stepsMainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'hbox', + height: 475, + items: [ + this.stepsAssignTree, + this.stepsAssignAccordion + ] + }); + this.mainContainer = new PMUI.core.Panel({ + id: "mainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'vbox', + items: [ + this.labelsPanel, + this.stepsMainContainer + ] + }); + this.secondaryWindow = new PMUI.ui.Window({ + visibleFooter: true, + title: 'Trigger'.translate(), + footerAlign: 'right', + footerItems: [ + { + text: "@@", + id: "secondaryWindow-criteria", + handler: function () { + }, + style: { + cssProperties: { + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + }, + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-cancel', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + }, + handler: function () { + } + }, { + id: 'secondaryWindow-save', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + }, + handler: function () { + } + } + ] + }); +}; +/** + * This method loads the initial data module steps,for the components: + * - stepsAssignTree + * - stepsAssignAccordion + */ +stepsTask.prototype.loadInitialData = function () { + this.loadTreePanelData(this.getTreePanelData()); + this.loadAccordionItems(this.getAccordionData()); +}; +/** + * This method loads the options to stepsAssignAccordion + * @param {Array} response An array where each element can be a {Element} object or a JSON object + */ +stepsTask.prototype.loadAccordionItems = function (response) { + var firstResp = [], + secondResp = [], + i, + item, + assigmentConfig, + firstRes = 0, + secondRes = 1; + if (jQuery.isArray(response) && response.length) { + if (typeof response[firstRes] === "object") { + firstResp = response[firstRes].response ? response[firstRes].response : []; + } + if (typeof response[secondRes] === "object") { + secondResp = response[secondRes].response ? response[secondRes].response : []; + } + } + if (firstResp.length) { + for (i = 0; i < firstResp.length; i += 1) { + item = this.createAccordionItem(firstResp[i], true, true); + this.stepsAssignAccordion.addItem(item); + item.dataItem = firstResp[i]; + this.customAccordionItemButtons(item.html, firstResp[i], item); + } + } + assigmentConfig = { + step_type_obj: "Assignment".translate(), + triggers: secondResp, + st_type: "ASSIGNMENT", + obj_title: "Assignment".translate(), + step_uid_obj: "Assignment" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + assigmentConfig = { + step_type_obj: "Routing".translate(), + triggers: secondResp, + obj_title: "Routing".translate(), + st_type: 'ROUTING', + step_uid_obj: "Routing" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + this.stepsAssignAccordion.defineEvents(); +}; +/** + * This method creates an element for stepsAssignAccordion + * @param {data} It is an object with the settings to create the element + * @returns {PMUI.item.AccordionItem} + */ +stepsTask.prototype.createAccordionItem = function (data) { + var that = this, + gridBefore, + gridAfter, + beforeTitle, + afterTitle, + i, + textLabel; + if (this.stepsType[data.step_type_obj]) { + textLabel = this.stepsType[data.step_type_obj]; + } else { + textLabel = data.step_type_obj; + } + beforeTitle = new PMUI.field.TextAnnotationField({ + text: 'Before'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left' + }); + afterTitle = new PMUI.field.TextAnnotationField({ + text: 'After'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left', + visible: data.st_type === "ASSIGNMENT" ? false : true + }); + + gridBefore = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + st_type: 'BEFORE', + step_uid: data.step_uid, + visibleFooter: false, + width: '96%', + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: "st_position", + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridBefore.st_type = 'BEFORE'; + } else if (data.st_type === "ROUTING") { + gridBefore.st_type = "BEFORE_ROUTING"; + } else { + gridBefore.st_type = "BEFORE_ASSIGNMENT"; + } + gridBefore.step_uid = data.step_uid; + gridBefore.clearItems(); + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridBefore.st_type === data.triggers[i].st_type) { + gridBefore.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + gridAfter = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + visibleFooter: false, + width: '96%', + visible: data.st_type === "ASSIGNMENT" ? false : true, + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: 'st_position', + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridAfter.st_type = 'AFTER'; + } else if (data.st_type == "ROUTING") { + gridAfter.st_type = "AFTER_ROUTING"; + } else { + gridAfter.st_type = "AFTER_ASSIGNMENT"; + } + gridAfter.step_uid = data.step_uid; + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridAfter.st_type === data.triggers[i].st_type) { + gridAfter.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + var accordionItem = new PMUI.item.AccordionItem({ + id: 'id' + data.step_uid_obj, + dataStep: data, + closeable: true, + body: new PMUI.core.Panel({ + layout: 'vbox', + items: [ + beforeTitle, + gridBefore, + afterTitle, + gridAfter + ] + }) + }); + if (this.stepsType[data.step_type_obj]) { + accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + this.stepsType[data.step_type_obj] + ')'); + this.stepsAssigned.insert(accordionItem); + } else { + accordionItem.setTitle((this.stepsAssignAccordion.items.getSize() + 1) + ". " + data.obj_title); + } + return accordionItem; +}; +/** + * styles that can not be handled with the library are customized PMUI + * @chainable + */ +stepsTask.prototype.customStyles = function () { + this.mainWindow.body.style.overflow = "hidden"; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get + * dynaforms, output document, input Document and external, Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getStepAvailables = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + if (jQuery.isArray(response)) { + resp = response[0] ? response[0].response : []; + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get all Availables + * triggres and dynaforms Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getTreePanelData = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' + }, { + url: 'triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +} +/** + * this method loads the data to stepsAssignTree + * @param response, the answer is an array containing all the elements + * that will be loaded into the step stepsAssignTree + * @chainable + */ +stepsTask.prototype.loadTreePanelData = function (response) { + var that = this, + data, + i, + j, + type, + label, + items, + labelTrigger, + dataTree = [], + treeNode; + data = response[1].response; + labelTrigger = 'Trigger (s)'.translate(); + if (data.length === 0) { + dataTree.push({ + obj_title: labelTrigger, + items: [this.notItemConfig()] + }); + } else { + items = []; + for (i = 0; i < data.length; i += 1) { + items.push({ + obj_title: data[i]['tri_title'], + obj_type: data[i]['tri_type'], + obj_uid: data[i]['tri_uid'] + }); + } + dataTree.push({ + obj_title: labelTrigger, + items: items, + id: "TRIGGER" + }); + } + data = response[0].response; + type = this.groupType; + label = this.groupLabel; + items = []; + for (i = 0; i < type.length; i += 1) { + items = []; + for (j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [this.notItemConfig()], + behavior: '', + id: type[i] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items, + behavior: 'drag', + id: type[i] + }); + } + } + this.stepsAssignTree.clearItems(); + for (i = 0; i < dataTree.length; i += 1) { + this.stepsAssignTree.addDataItem(dataTree[i]); + treeNode = this.stepsAssignTree.getItem(i); + treeNode.setID(dataTree[i].id); + this.updateIndexPosition(treeNode); + } + return this; +}; +/** + * run the endpoint 'activity/{activity_id}/steps' and 'activity/{activity_id}/step/triggers' + * to get all triggres and dynaforms assigned + * @returns {Array} + */ +stepsTask.prototype.getAccordionData = function () { + var resp = [], + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + PMDesigner.act_uid + '/steps', + method: 'GET' + }, { + url: 'activity/' + PMDesigner.act_uid + '/step/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }); + restClient.executeRestClient(); + return resp; +}; +/** + * checks whether a trigger is already assigned in a grid + * @param grid, is instanceof PMUI.grid.Grid, in conducting the search + * @param tri_uid, search parameter in the rows of the grid + * @returns {boolean} + */ +stepsTask.prototype.isTriggerAssigned = function (grid, tri_uid) { + var data, i, exist = false; + data = grid.getData(); + if (grid && jQuery.isArray(data)) { + for (i = 0; i < data.length; i += 1) { + if (data[i].tri_uid === tri_uid) { + exist = true; + break; + } + } + } + return exist; +}; +/** + * retorna el tipo de de step, para la ejecucion de "endpoint" + * @param st_type, this a step type, the accepted parameters are: + * - BEFORE_ASSIGNMENT + * - BEFORE_ROUTING + * - AFTER_ROUTING + * - BEFORE + * - AFTER + * @returns {string} + */ +stepsTask.prototype.getStepType = function (st_type) { + var value; + switch (st_type) { + case 'BEFORE_ASSIGNMENT': + value = 'before-assignment'; + break; + case 'BEFORE_ROUTING': + value = 'before-routing'; + break; + case 'AFTER_ROUTING': + value = 'after-routing'; + break; + case 'BEFORE': + value = 'before'; + break; + case 'AFTER': + value = 'after'; + break; + default: + value = ''; + break; + } + return value; +}; +/** + * This method is executed when editing a "trigger" in a row of the grid. + * secondary window opens with the current configuration of the trigger + * @param trigger, is the return value when is update 'trigger' action in the enpoint + * @param triggerID, is the id of the trigger to update + * @chainable + */ +stepsTask.prototype.editTrigger = function (trigger, triggerID) { + var codeMirror, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + codeMirror = new PMCodeMirror({ + id: "codeMirror" + }); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + codeMirror.setValue(trigger); + this.secondaryWindow.setWidth(DEFAULT_WINDOW_WIDTH); + this.secondaryWindow.setHeight(DEFAULT_WINDOW_HEIGHT); + this.secondaryWindow.setTitle("Trigger".translate()); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + triggerID, + typeRequest: 'update', + data: { + tri_param: '', + tri_webbot: codeMirror.getValue() + }, + messageError: 'There are problems updating the trigger, please try again.'.translate(), + messageSuccess: 'Trigger updated correctly'.translate(), + flashContainer: that.mainWindow, + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(true); + criteriaButton.setHandler(function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var cursorPos, + codemirror; + codemirror = codeMirror.cm; + cursorPos = codemirror.getCursor(); + codemirror.replaceSelection(variable); + codemirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }); + } + this.secondaryWindow.open(); + this.secondaryWindow.addItem(codeMirror); + codeMirror.cm.setSize(this.secondaryWindow.getWidth(), 380); + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + $(".pmui-window-body").css("overflow", "hidden"); + codeMirror.cm.refresh(); +}; +/** + * edit the selected trigger condition + * @param stepID, It is the id of the step to upgrade + * @param triggerID, is the id of the trigger to update + * @param stepType, It is the kind of step to update + * @param row, PMUI.grid.GridPanelRow, is the row affected + */ +stepsTask.prototype.editCondition = function (stepID, triggerID, stepType, row) { + var saveButton, + cancelButton, + criteriaButton, + form, + dataRow, + that = this; + dataRow = row.getData(); + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(500); + this.secondaryWindow.setHeight(350); + this.secondaryWindow.setTitle('Condition Trigger'.translate()); + this.secondaryWindow.setTitle("Trigger".translate()); + form = new PMUI.form.Form({ + id: 'idFormEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + new CriteriaField({ + id: 'st_condition', + pmType: 'textarea', + name: 'st_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea', + value: dataRow.st_condition + }) + ] + }); + this.secondaryWindow.addItem(form); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var data, + restClient; + data = form.getData(); + data.st_type = stepType; + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + ((typeof(stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, + typeRequest: 'update', + data: data, + messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + functionSuccess: function (xhr, response) { + dataRow.st_condition = data.st_condition; + row.setData(dataRow); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + that.secondaryWindow.close(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(false); + criteriaButton.handler = null; + } + this.secondaryWindow.open(); +}; +/** + * eliminates the elements of the secondary window + * @chainable + */ +stepsTask.prototype.resetSecondaryWindow = function () { + var i, items; + if (this.secondaryWindow && this.secondaryWindow.items.getSize() > 0) { + items = this.secondaryWindow.items; + for (i = 0; i < items.getSize(); i += 1) { + this.secondaryWindow.removeItem(items.get(i)); + } + } +}; +/** + * It establishes a PMUI.util.ArrayList that stores the + * elements of "stepsAssignAccordion" that are open + * @chainable + */ +stepsTask.prototype.elementsAccordionOpenFixed = function () { + var i, + accordionItems; + if (this.stepsAssignAccordion) { + accordionItems = this.stepsAssignAccordion.getItems(); + if ($.isArray(accordionItems)) { + for (i = 0; i < accordionItems.length; i += 1) { + if (!accordionItems[i].collapsed) { + this.elementAccordionOpen.insert(accordionItems[i]); + } + } + } + } +}; +/** + * It is an extension to add the "sortable" event "stepAssignAccordion". + * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. + * @chainable + */ +stepsTask.prototype.addEventSortableInAccordionElements = function () { + var tagContainer, + newIndex, + index, + treeNodeObject, + treeNodeData, + that = this; + if (this.stepsAssignAccordion && this.stepsAssignAccordion.html) { + tagContainer = this.stepsAssignAccordion.body; + $(tagContainer).sortable({ + items: '>div:not(#idAssignment,#idRouting)', + placeholder: 'steps-placeholder', + receive: function (event, ui) { + var item = ui ? ui.item : null; + if (item && item instanceof jQuery && item.length) { + treeNodeObject = PMUI.getPMUIObject(item.get(0)); + treeNodeData = treeNodeObject.getData(); + } + }, + stop: function (event, ui) { + var itemClone = ui ? ui.item : null, + accordionItems, + accordionItem, + dataEdited, + restClientMultipart, + restClient; + var newIndex = ui.item.index(); + accordionItems = that.stepsAssignAccordion.getItems(); + if (itemClone && itemClone instanceof jQuery && itemClone.length) { + if (treeNodeObject) { + itemClone.remove(); + if (newIndex + 1 > accordionItems.length) { + newIndex = that.stepsAssigned.getSize(); + } + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step', + typeRequest: 'post', + data: { + step_type_obj: treeNodeData.obj_type, + step_uid_obj: treeNodeData.obj_uid, + step_condition: '', + step_position: newIndex + 1, + step_mode: 'EDIT' + }, + functionSuccess: function (xhr, response) { + var item, buttonAfected, treeNode; + that.stepsAssignTree.removeItem(treeNodeObject); + treeNode = that.stepsAssignTree.items.find("id", response.step_type_obj); + if (treeNode.items.getSize() === 0) { + treeNode.addDataItem(that.notItemConfig()); + } + response.obj_description = ''; + response.obj_title = treeNodeData.obj_title; + response.triggers = []; + item = that.createAccordionItem(response, true, true); + item.dataItem = response; + if (that.stepsAssignAccordion.items.getSize() === 2) { + that.stepsAssignAccordion.addItem(item, 0); + } else { + that.stepsAssignAccordion.addItem(item, newIndex); + } + that.stepsAssignAccordion.defineEvents(); + that.customAccordionItemButtons(item.html, response, item); + that.updateItemIndexToAccordion(); + that.addEventSortableInAccordionElements(); + that.addEventSortableInTreePanelElements(); + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while assigning the step, please try again later.'.translate(), + messageSuccess: 'Step assigned successfully.'.translate(), + flashContainer: that.stepsAssignAccordion.getParent() + }); + restClient.executeRestClient(); + } else { + accordionItem = PMUI.getPMUIObject(ui.item.get(0)); + index = that.stepsAssignAccordion.items.indexOf(accordionItem); + if (newIndex !== index) { + that.stepsAssignAccordion.items.remove(accordionItem); + that.stepsAssignAccordion.items.insertAt(accordionItem, newIndex); + dataEdited = { + step_position: newIndex + 1, + step_uid: accordionItem.dataItem.step_uid, + step_type_obj: accordionItem.dataItem.step_type_obj, + step_uid_obj: accordionItem.dataItem.step_uid_obj + }; + restClientMultipart = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + accordionItem.dataItem.step_uid, + typeRequest: 'update', + data: dataEdited, + functionSuccess: function (xhr, response) { + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while editing the step, please try again later.'.translate(), + messageSuccess: 'Step editing successfully.'.translate(), + flashContainer: this.mainWindow + }); + restClientMultipart.executeRestClient(); + } + } + } + }, + start: function (e, ui) { + newIndex = ui.item.index(); + } + }); + } +}; +/** + * It is an extension to add the "sortable" event "stepsAssignTree". + * when choosing a node treePanel and you want to add to the accordion or the grid + * @chainable + */ +stepsTask.prototype.addEventSortableInTreePanelElements = function () { + var items = this.stepsAssignTree.getItems(), + connect, + i, + sw, + that = this, + nodeItems; + for (i = 0; i < items.length; i += 1) { + nodeItems = items[i].getItems(); + if (nodeItems.length && nodeItems[0].getData().obj_type) { + sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; + connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; + $(items[i].html).find('ul').find('>li').draggable({ + appendTo: document.body, + revert: "invalid", + helper: "clone", + cursor: "move", + zIndex: 1000, + connectToSortable: connect, + start: function (e) { + var i, nodeTag, node, nodeData, accordionItems, item; + nodeTag = e.target; + node = PMUI.getPMUIObject(nodeTag); + nodeData = node.getData(); + accordionItems = that.stepsAssignAccordion.getItems(); + $(that.stepsAssignAccordion.body).hide(); + if (nodeData.obj_type !== "SCRIPT") { + for (i = 0; i < accordionItems.length; i += 1) { + item = accordionItems[i]; + item.collapse(); + } + } + $(that.stepsAssignAccordion.body).show(); + }, + stop: function () { + var i = 0, max; + if (that.elementAccordionOpen) { + max = that.elementAccordionOpen.getSize(); + for (i = 0; i < max; i += 1) { + that.elementAccordionOpen.get(i).expand(); + } + } + } + }); + } else { + $(nodeItems[0].html).draggable("disable"); + } + } +}; +/** + * add custom buttons on the head of an element of stepsAssignAccordion + * are three buttons + * properties + * edit + * remove + * @param html, is the html of the header accordion item + * @param step, the data of the step selected + */ +stepsTask.prototype.customAccordionItemButtons = function (html, step, accordionItem) { + var propertiesStep, + editStep, + removeStep, + $html, + containerButtons, + that = this, + title; + if (html) { + $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); + title = step.obj_title + ' (' + step.step_type_obj + ')'; + $html.find(".pmui-accordion-item-title").get(0).title = title; + containerButtons = $('
'); + containerButtons.addClass("propertiesTask-accordionItem"); + propertiesStep = $('' + 'Properties'.translate() + ''); + propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + editStep = $('' + 'Edit'.translate() + ''); + editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + removeStep = $('' + 'Remove'.translate() + ''); + removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); + + propertiesStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.propertiesStepShow(step); + return false; + }); + + editStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.editStepShow(step, accordionItem); + return false; + }); + + removeStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.removeStepShow(step); + return false; + }); + containerButtons.append(propertiesStep); + containerButtons.append(editStep); + containerButtons.append(removeStep); + $html.append(containerButtons); + } +}; +/** + * opens the properties of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ +stepsTask.prototype.propertiesStepShow = function (step) { + var form, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(520); + this.secondaryWindow.setHeight(370); + this.secondaryWindow.setTitle('Step Properties'.translate()); + form = new PMUI.form.Form({ + id: 'stepsEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + { + id: 'step_mode', + pmType: 'radio', + label: 'Mode'.translate(), + value: '', + visible: step.step_type_obj === "DYNAFORM" ? true : false, + name: 'step_mode', + options: [ + { + id: 'modeEdit', + label: 'Edit'.translate(), + value: 'EDIT', + selected: true + }, { + id: 'modeView', + label: 'View'.translate(), + value: 'VIEW' + } + ] + }, + new CriteriaField({ + id: 'step_condition', + pmType: 'textarea', + name: 'step_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea' + }) + ] + }); + this.secondaryWindow.addItem(form); + + var restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + form.getField('step_mode').setValue(response.step_mode); + form.getField('step_condition').setValue(response.step_condition); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient; + if (form.isValid()) { + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'update', + data: form.getData(), + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems update the Step Trigger, please try again.'.translate() + }); + restClient.executeRestClient(); + } + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.handler = null; + criteriaButton.setVisible(false); + } + this.secondaryWindow.open(); +}; +/** + * opens the step of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ +stepsTask.prototype.editStepShow = function (step, accordioItem) { + var inputDocument, + that = this; + switch (step.step_type_obj) { + case 'DYNAFORM': + var restProxy = new PMRestClient({ + endpoint: 'dynaform/' + step.step_uid_obj, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var old = PMUI.activeCanvas, + formDesigner; + PMUI.activeCanvas = false; + formDesigner = PMDesigner.dynaformDesigner(response); + formDesigner.onHide = function () { + var assignedDynaform, + i, + data, + title; + assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); + if (jQuery.isArray(assignedDynaform)) { + for (i = 0; i < assignedDynaform.length; i += 1) { + data = assignedDynaform[i]; + if (typeof data === "object") { + if (data.step_uid === step.step_uid) { + title = data.step_position + ". " + data.obj_title; + title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; + accordioItem.setTitle(title); + accordioItem.dataItem = data; + } + } + } + } + PMUI.activeCanvas = old; + }; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + break; + case 'OUTPUT_DOCUMENT': + PMDesigner.output(); + PMDesigner.output.showTiny(step.step_uid_obj); + break; + case 'INPUT_DOCUMENT': + inputDocument = new InputDocument({ + onUpdateInputDocumentHandler: function (data, inputDoc) { + var position, title; + position = accordioItem.dataItem.step_position; + title = position + ". " + data.inp_doc_title; + title = title + ' (' + that.stepsType["INPUT_DOCUMENT"] + ')'; + accordioItem.dataItem.obj_title = data.inp_doc_title; + accordioItem.setTitle(title); + inputDoc.winMainInputDocument.close(); + } + }); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); + break; + } +}; +/** + * the window opens for confirmation of the removal step + * @param step, the current step to remove + * @chainable + */ +stepsTask.prototype.removeStepShow = function (step) { + var title, + yesButton, + noButton, + that = this, + restClient; + if (this.stepsType[step.step_type_obj] !== undefined) { + title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); + this.confirmWindow.setTitle(title); + } else { + this.confirmWindow.setTitle("Step " + step.step_type_obj.capitalize()); + } + this.confirmWindow.setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.removingStepTask(step, response); + that.confirmWindow.close(); + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), + messageSuccess: 'Step removed successfully'.translate(), + flashContainer: that.mainWindow.getParent() + }); + restClient.executeRestClient(); + }); + } + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); + }); + } + this.confirmWindow.open(); +}; +/** + * eliminates the step of step Assign Accordion + * @param step, the current step to remove + * @param response, data from the endpoint + */ +stepsTask.prototype.removingStepTask = function (step, response) { + var stepObject, + stepAvailable, + treeNodeObject, + stepAvailables, + i, + itemsTreeNode = [], + items = []; + stepObject = this.stepsAssignAccordion.getItem("id" + step.step_uid_obj); + this.elementAccordionOpen.remove(stepObject); + this.stepsAssigned.remove(stepObject); + this.stepsAssignAccordion.removeItem(stepObject); + if (stepObject) { + stepAvailable = this.getStepAvailables(); + stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); + for (i = 0; i < stepAvailables.length; i += 1) { + items.push({ + obj_title: stepAvailables[i]['obj_title'], + obj_type: stepAvailables[i]['obj_type'], + obj_uid: stepAvailables[i]['obj_uid'] + }); + } + treeNodeObject = this.stepsAssignTree.getItem(step.step_type_obj); + itemsTreeNode = treeNodeObject.getItems(); + for (i = 0; i < itemsTreeNode.length; i += 1) { + treeNodeObject.removeItem(itemsTreeNode[i]); + } + treeNodeObject.clearItems(); + treeNodeObject.setDataItems(items); + this.updateIndexPosition(treeNodeObject); + this.addEventSortableInTreePanelElements(); + this.addEventSortableInAccordionElements(); + } +}; +/** + * get the steps is not assigned by a criterion + * @param criteria, It is the filter criteria search + * @param stepAvailable, all steps Unassigned + * @returns {Array}, filtered items + */ +stepsTask.prototype.getAvailablesStepsByCriteria = function (criteria, stepAvailable) { + var items = [], + i; + if (jQuery.isArray(stepAvailable)) { + for (i = 0; i < stepAvailable.length; i += 1) { + if (stepAvailable[i].obj_type === criteria) { + items.push(stepAvailable[i]); + } + } + } + return items; +}; +/** + * This method is executed when an element stepsAssignTree, is assigned in a grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @returns {stepsTask} + */ +stepsTask.prototype.receiveTreeNodeItem = function (receiveData, grid, index) { + var restClient, that = this, message; + if (that.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow + }); + message.show(); + return; + } + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + typeRequest: 'post', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: '', + st_position: index + 1 + }, + functionSuccess: function (xhr, response) { + grid.addDataItem({ + st_condition: '', + st_position: index + 1, + st_type: grid.st_type, + tri_description: '', + tri_title: receiveData.obj_title, + tri_uid: receiveData.obj_uid, + obj_title: receiveData.obj_title, + obj_uid: receiveData.obj_uid + }, index); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method is executed when a row is drop in another grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @param draggableItem + * @returns {*} + */ +stepsTask.prototype.receiveRowItem = function (receiveData, grid, index, draggableItem) { + var receiveParent = draggableItem.getParent(), + message, + restClient, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow + }); + index = receiveParent.items.indexOf(draggableItem); + receiveParent.items.remove(draggableItem); + receiveParent.addItem(draggableItem, index); + message.show(); + return false; + } + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + method: 'POST', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + } + }, { + url: receiveParent.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + receiveData.obj_uid + '/' + that.getStepType(receiveParent.st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + receiveParent.step_uid + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), + method: 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + var data; + data = receiveData; + if (data.hasOwnProperty("st_type")) { + data.st_type = grid.st_type; + grid.addDataItem(receiveData, index); + } + receiveParent.removeItem(draggableItem); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: [ + 'An unexpected error while assigning the trigger, please try again later.'.translate() + ], + messageSuccess: [ + 'Trigger assigned successfully.'.translate() + ] + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method is executed when a row is sorted in the grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the new index position row + * @returns {stepsTask} + */ +stepsTask.prototype.sortableRowHandler = function (receiveData, grid, index) { + var that = this, + restClient; + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + "/step/trigger/" + receiveData.tri_uid : + 'activity/' + PMDesigner.act_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, + typeRequest: 'update', + data: { + st_type: receiveData.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger assigned successfully.'.translate() + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method eliminates the list of triggers trigger an assigned step + * @param row, the row affected or selected + * @param grid, It is affected or grid to remove selected row + */ +stepsTask.prototype.removeTrigger = function (row, grid) { + var message = 'Do you want to remove the trigger "', + messageData = row.getData().tri_title ? row.getData().tri_title : "", + yesButton, + noButton, + that = this, + restClient; + message = message + messageData + '"?'; + this.confirmWindow.setMessage(message.translate()); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type), + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + that.confirmWindow.close(); + that.updateIndexToGrid(grid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger removed successfully'.translate() + }); + restClient.executeRestClient(); + }); + } + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); + }); + } + this.confirmWindow.open(); +}; +/** + * updates indexes of elements selected grid + * @param grid, It is affected or grid to remove selected row + * @returns {stepsTask} + */ +stepsTask.prototype.updateIndexToGrid = function (grid) { + var cell, rows, i, row; + if (grid) { + rows = grid.getItems(); + if (jQuery.isArray(rows)) { + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + cell = row.cells.find("columnData"); + if (cell) { + cell.setContent(i + 1); + } + } + } + } + return this; +}; +/** + * get the steps assigned by a search criterion + * @param criteria, search filter, after running the endpoint getAccordionData method + * @returns {Array}, response with criteria + */ +stepsTask.prototype.getStepsAssignedByCriteria = function (criteria) { + var allAssigned, + i, + elements, + j, + resp, + response = []; + allAssigned = this.getAccordionData(); + if (jQuery.isArray(allAssigned)) { + for (i = 0; i < allAssigned.length; i += 1) { + resp = allAssigned[i]; + if (typeof resp === "object") { + elements = resp.response ? resp.response : []; + for (j = 0; j < elements.length; j += 1) { + data = elements[j]; + if (typeof data === "object") { + if (data.step_type_obj && data.step_type_obj === criteria) { + response.push(data); + } + } + } + } + } + } + return response; +}; +/** + * updates indexes of elements assigned + * @returns {stepsTask} + */ +stepsTask.prototype.updateItemIndexToAccordion = function () { + var title, + i, + item, + dataItem, + items = this.stepsAssignAccordion.items, + position, + max; + max = items.getSize(); + for (i = 0; i < max; i += 1) { + item = items.get(i); + position = items.indexOf(item); + dataItem = item.dataItem; + title = (position + 1) + ". " + dataItem.obj_title; + if (this.stepsType[dataItem.step_type_obj]){ + title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; + } + item.dataItem.step_position = i + 1; + item.setTitle(title); + } + return this; +}; +/** + * add tooltip in treeNode elements + * @returns {stepsTask} + */ +stepsTask.prototype.updateIndexPosition = function (treeNode) { + var items, i, item, $item, text, data; + if (treeNode && treeNode.html) { + items = treeNode.getItems(); + if (jQuery.isArray(items)) { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + if (item.html) { + $item = $(item.html); + data = item.getData(); + text = $item.find("a").get(0); + text.title = data.obj_title; + } + } + } + } + return this; +}; +/** + * return the not items config. + * @returns {{obj_title: *, obj_uid: string, id: string}} + */ +stepsTask.prototype.notItemConfig = function () { + var config = { + obj_title: 'N/A'.translate(), + obj_uid: '', + id: "notItem" + }; + return config; +}; +( + function () { + var processPermissionsSetForm; + PMDesigner.processPermissions = function (event) { + var PROCESS_PERMISSIONS_OPTION = "", + PROCESS_PERMISSIONS_UID = "", + arrayCboGroup = [], + arrayCboUser = [], + winGrdpnlProcessPermissions, + grdpnlProcessPermissions, + frmProcessPermissions, + processPermissionsData, + btnCreate, btnSave, btnCancel, + loadDataFromServerToFields, + disableAllItems, + listProcessPermissions, + isDirty2, + isDirtyFormProcessPermission, + refreshGridPanelInMainWindow, + processPermissionsGetRestProxy, + processPermissionsPostRestProxy, + processPermissionGetRestProxy, + processPermissionsPutRestProxy, + cboTargetCboOriginTaskSetOptionsRestProxy, + cboDynaFormSetOptionsRestProxy, + cboInputDocumentSetOptionsRestProxy, + cboOutputDocumentSetOptionsRestProxy, + processPermissionsSetFormByType, + processPermissionsDeleteRestProxy, + cboStatusCase, + cboTargetTask, + cboGroupOrUser, + cboOriginTask, + optionsType, + cboType, + cboDynaForm, + cboInputDocument, + cboOutputDocument, + cboPermission, + cboParticipationRequired, + processPermissionsDataIni = {}, + notification, + notificationText = "Fields marked with an asterisk (%%ASTERISK%%) are required.".translate() + .replace(/%%ASTERISK%%/g, '*'); + + loadDataFromServerToFields = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/dynaforms', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/input-documents', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/output-documents', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var i; + data = response[0].response; + cboTargetTask.clearOptions(); + cboOriginTask.clearOptions(); + cboTargetTask.addOption({value: '', label: 'All Tasks'.translate()}); + cboOriginTask.addOption({value: '', label: 'All Tasks'.translate()}); + for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { + cboTargetTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + cboOriginTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + } + //project/dynaforms + data = response[1].response; + cboDynaForm.clearOptions(); + cboDynaForm.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); + } + //project/input-documents + data = response[2].response; + cboInputDocument.clearOptions(); + cboInputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); + } + //project/output-documents + data = response[3].response; + cboOutputDocument.clearOptions(); + cboOutputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + + disableAllItems = function () { + winGrdpnlProcessPermissions.getItems()[0].setVisible(false); + winGrdpnlProcessPermissions.getItems()[1].setVisible(false); + winGrdpnlProcessPermissions.hideFooter(); + }; + + isDirty2 = function () { + var user, + dynaForm, + inputDocument, + outputDocument, + flagInsert = (typeof(processPermissionsData.op_case_status) === "undefined") ? true : false; + + if (flagInsert) { + processPermissionsData = processPermissionsDataIni; + } + + if (cboStatusCase.getValue() != processPermissionsData.op_case_status) { + return true; + } + + if (cboTargetTask.getValue() != processPermissionsData.tas_uid) { + return true; + } + + user = (cboGroupOrUser.get("value") !== null && cboGroupOrUser.get("value")) ? cboGroupOrUser.get("value") : ""; + + if (user != processPermissionsData.usr_uid) { + return true; + } + + if (cboOriginTask.getValue() != processPermissionsData.op_task_source) { + return true; + } + + if (cboParticipationRequired.getValue() != processPermissionsData.op_participate) { + return true; + } + + if (cboType.getValue() != processPermissionsData.op_obj_type) { + return true; + } + + switch (cboType.getValue()) { + case "DYNAFORM": + dynaForm = (cboDynaForm.getValue() !== "") ? cboDynaForm.getValue() : "0"; + + if (dynaForm != processPermissionsData.op_obj_uid) { + return true; + } + + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + case "ATTACHMENT": + if (cboPermission.getValue() !== processPermissionsData.op_action) { + return true; + } + break; + case "INPUT": + inputDocument = (cboInputDocument.getValue() !== "") ? cboInputDocument.getValue() : "0"; + + if (inputDocument != processPermissionsData.op_obj_uid) { + return true; + } + + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + + break; + case "OUTPUT": + outputDocument = (cboOutputDocument.getValue() !== "") ? cboOutputDocument.getValue() : "0"; + + if (outputDocument != processPermissionsData.op_obj_uid) { + return true; + } + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "ANY": + case "MSGS_HISTORY": + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + } + + return false; + }; + + isDirtyFormProcessPermission = function () { + $("input,select,textarea").blur(); + if (frmProcessPermissions.isVisible()) { + var result = frmProcessPermissions.isDirty(), message_window; + + if (isDirty2()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Permissions".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + cboGroupOrUser.html.find("input").val(""); + cboGroupOrUser.value = ""; + if (clickedClose) { + winGrdpnlProcessPermissions.close(); + } else { + refreshGridPanelInMainWindow(false); + } + + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if (cboGroupOrUser.html.find("input").val()) { + cboGroupOrUser.html.find("input").val(""); + } + cboGroupOrUser.containerList.hide(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + refreshGridPanelInMainWindow(false); + if (clickedClose) { + winGrdpnlProcessPermissions.close(); + } + } + } else { + winGrdpnlProcessPermissions.close(); + } + }; + refreshGridPanelInMainWindow = function (load) { + disableAllItems(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + winGrdpnlProcessPermissions.getItems()[0].setVisible(true); + winGrdpnlProcessPermissions.setTitle("Permissions".translate()); + load = load != null ? load : true; + if (load) { + processPermissionsGetRestProxy(grdpnlProcessPermissions); + } + }; + + processPermissionsGetRestProxy = function (grdpnl) { + var restProxy = new PMRestClient({ + endpoint: "process-permissions", + typeRequest: "get", + functionSuccess: function (xhr, response) { + listProcessPermissions = response; + grdpnl.setDataItems(listProcessPermissions); + grdpnl.sort('group_user', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); + }; + + processPermissionsPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "process-permission", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission saved successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + processPermissionGetRestProxy = function (processPermissionsUid) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response; + processPermissionsSetForm("PUT", data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + processPermissionsPutRestProxy = function (processPermissionsUid, data) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission edited successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + cboTargetCboOriginTaskSetOptionsRestProxy = function (cboTargetTask, cboOriginTask) { + cboTargetTask.clearOptions(); + cboOriginTask.clearOptions(); + var restProxy = new PMRestClient({ + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboTargetTask.addOption({value: "", label: "All Tasks".translate()}); + cboOriginTask.addOption({value: "", label: "All Tasks".translate()}); + for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { + cboTargetTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + cboOriginTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); + }; + + cboDynaFormSetOptionsRestProxy = function (cboDynaForm) { + cboDynaForm.clearOptions(); + var restProxy = new PMRestClient({ + endpoint: "dynaforms", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboDynaForm.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + cboInputDocumentSetOptionsRestProxy = function (cboInputDocument) { + cboInputDocument.clearOptions(); + var restProxy = new PMRestClient({ + endpoint: "input-documents", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboInputDocument.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + cboOutputDocumentSetOptionsRestProxy = function (cboOutputDocument) { + var restProxy; + cboOutputDocument.clearOptions(); + restProxy = new PMRestClient({ + endpoint: "output-documents", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboOutputDocument.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + processPermissionsSetFormByType = function (type) { + cboPermission.removeOption("DELETE"); + cboPermission.removeOption("RESEND"); + + cboPermission.reset(); + cboOriginTask.setVisible(true); + cboParticipationRequired.setVisible(true); + cboStatusCase.setVisible(true); + cboDynaForm.setVisible(false); + cboInputDocument.setVisible(false); + cboOutputDocument.setVisible(false); + cboPermission.setVisible(false); + + switch (type) { + case "DYNAFORM": + cboDynaForm.setVisible(true); + cboPermission.setVisible(true); + break; + case "ATTACHMENT": + cboPermission.setVisible(true); + break; + case "INPUT": + cboPermission.addOption({value: "DELETE", label: "Delete".translate()}); + + cboInputDocument.setVisible(true); + cboPermission.setVisible(true); + break; + case "OUTPUT": + cboPermission.addOption({value: "DELETE", label: "Delete".translate()}); + + cboOutputDocument.setVisible(true); + cboPermission.setVisible(true); + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "MSGS_HISTORY": + cboPermission.addOption({value: "RESEND", label: "Resend".translate()}); + + cboPermission.setVisible(true); + break; + case "ANY": + cboPermission.setVisible(true); + break; + case "REASSIGN_MY_CASES": + cboOriginTask.setVisible(false); + cboParticipationRequired.setVisible(false); + cboStatusCase.setVisible(false); + break; + } + }; + + processPermissionsDeleteRestProxy = function (processPermissionsUid) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "remove", + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission deleted successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + processPermissionsSetForm = function (option, data) { + cboGroupOrUser.hideMessageRequired(); + processPermissionsData = data; + PROCESS_PERMISSIONS_OPTION = option; + PROCESS_PERMISSIONS_UID = (typeof(processPermissionsData.op_uid) !== "undefined") ? processPermissionsData.op_uid : ""; + + disableAllItems(); + winGrdpnlProcessPermissions.showFooter(); + winGrdpnlProcessPermissions.getItems()[1].setVisible(true); + + loadDataFromServerToFields(); + + switch (option) { + case "POST": + winGrdpnlProcessPermissions.setTitle("Create permission".translate()); + frmProcessPermissions.reset(); + processPermissionsSetFormByType(cboType.getValue()); + + break; + case "PUT": + winGrdpnlProcessPermissions.setTitle("Edit permission".translate()); + cboStatusCase.setValue(processPermissionsData.op_case_status); + cboTargetTask.setValue(processPermissionsData.tas_uid); + + var endpoint; + if (processPermissionsData.op_user_relation == 1) { + endpoint = "users/" + processPermissionsData.usr_uid; + } + if (processPermissionsData.op_user_relation == 2) { + endpoint = "groups/" + processPermissionsData.usr_uid; + } + + if (endpoint) { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (response.hasOwnProperty("usr_uid")) { + cboGroupOrUser.set("value", response["usr_uid"]); + cboGroupOrUser.data = response; + cboGroupOrUser.html.find("input").val(response["usr_firstname"] + " " + response["usr_lastname"] + " " + "(" + response["usr_username"] + ")"); + } + if (response.hasOwnProperty("grp_uid")) { + cboGroupOrUser.set("value", response["grp_uid"]); + cboGroupOrUser.data = response; + cboGroupOrUser.html.find("input").val(response["grp_title"]); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint(endpoint); + restClient.executeRestClient(); + } + + cboParticipationRequired.setValue(processPermissionsData.op_participate); + cboType.setValue(processPermissionsData.op_obj_type); + cboOriginTask.setValue(processPermissionsData.op_task_source); + processPermissionsSetFormByType(processPermissionsData.op_obj_type); + switch (processPermissionsData.op_obj_type) { + case "ANY": + cboPermission.setValue(processPermissionsData.op_action); + break; + case "DYNAFORM": + cboDynaForm.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "ATTACHMENT": + cboPermission.setValue(processPermissionsData.op_action); + break; + case "INPUT": + cboInputDocument.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "OUTPUT": + cboOutputDocument.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "MSGS_HISTORY": + cboPermission.setValue(processPermissionsData.op_action); + break; + } + break; + } + frmProcessPermissions.setFocus(); + }; + + cboStatusCase = new PMUI.field.DropDownListField({ + id: "cboStatusCase", + name: "cboStatusCase", + controlsWidth: "120px", + label: "Case Status".translate(), + value: "ALL", + options: [ + { + value: "ALL", + label: "All".translate() + }, + { + value: "DRAFT", + label: "DRAFT".translate() + }, + { + value: "TO_DO", + label: "TO DO".translate() + }, + { + value: "PAUSED", + label: "PAUSED".translate() + }, + { + value: "COMPLETED", + label: "COMPLETED".translate() + } + ] + }); + + cboTargetTask = new PMUI.field.DropDownListField({ + id: "cboTargetTask", + name: "cboTargetTask", + controlsWidth: "300px", + label: "Target Task".translate(), + options: null + }); + cboGroupOrUser = new SuggestField({ + label: "Group or User".translate(), + id: "cboGroupOrUser", + name: "cboGroupOrUser", + placeholder: "suggest users and groups", + width: 500, + required: true, + separatingText: ["Groups", "Users"], + dynamicLoad: { + data: [ + { + key: "grp_uid", + label: ["grp_title"] + }, + { + key: "usr_uid", + label: ["usr_firstname", "usr_lastname", "(", "usr_username", ")"] + } + ], + keys: { + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endpoints: [ + { + method: "GET", + url: 'groups' + }, { + method: "GET", + url: 'users' + } + ] + } + } + }); + + cboOriginTask = new PMUI.field.DropDownListField({ + id: "cboOriginTask", + name: "cboOriginTask", + controlsWidth: "300px", + label: "Origin Task".translate(), + options: null + }); + + cboParticipationRequired = new PMUI.field.DropDownListField({ + id: "cboParticipationRequired", + name: "cboParticipationRequired", + controlsWidth: "70px", + label: "Participation required?".translate(), + value: "0", + options: [ + { + value: "0", + label: "No".translate() + }, + { + value: "1", + label: "Yes".translate() + } + ] + }); + notification = new PMUI.field.TextAnnotationField({ + id: "requiredMessage", + name: "Message", + textType: PMUI.field.TextAnnotationField.TEXT_TYPES.HTML, + text: notificationText, + text_Align: "center" + }); + optionsType = [ + { + value: "ANY", + label: "All".translate() + }, + { + value: "DYNAFORM", + label: "Dynaform".translate() + }, + { + value: "ATTACHMENT", + label: "Attachment".translate() + }, + { + value: "INPUT", + label: "Input Document".translate() + }, + { + value: "OUTPUT", + label: "Output Document".translate() + }, + { + value: "CASES_NOTES", + label: "Cases Notes".translate() + }, + { + value: "MSGS_HISTORY", + label: "Messages History".translate() + }, + { + value: "REASSIGN_MY_CASES", + label: "Reassign my cases".translate() + } + ]; + + if (enterprise == "1") { + optionsType.push({value: "SUMMARY_FORM", label: "Summary Form".translate()}); + } + // sorting the optionsType + optionsType.sort(function(a, b) { + return (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0); + }); + + cboType = new PMUI.field.DropDownListField({ + id: "cboType", + name: "cboType", + controlsWidth: "180px", + label: "Type".translate(), + value: "ANY", + options: optionsType, + onChange: function (newValue, prevValue) { + processPermissionsSetFormByType(cboType.getValue()); + } + }); + + cboDynaForm = new PMUI.field.DropDownListField({ + id: "cboDynaForm", + name: "cboDynaForm", + controlsWidth: "300px", + label: "DynaForm".translate(), + options: [], + visible: false + }); + + cboInputDocument = new PMUI.field.DropDownListField({ + id: "cboInputDocument", + name: "cboInputDocument", + controlsWidth: "300px", + label: "Input Document".translate(), + options: [], + visible: false + }); + + cboOutputDocument = new PMUI.field.DropDownListField({ + id: "cboOutputDocument", + name: "cboOutputDocument", + controlsWidth: "300px", + label: "Output Document".translate(), + options: [], + visible: false + }); + + cboPermission = new PMUI.field.DropDownListField({ + id: "cboPermission", + name: "cboPermission", + controlsWidth: "100px", + label: "Permission".translate(), + value: "VIEW", + options: [ + { + value: "VIEW", + label: "View".translate() + }, + { + value: "BLOCK", + label: "Block".translate() + } + ], + visible: true + }); + + frmProcessPermissions = new PMUI.form.Form({ + id: "frmProcessPermissions", + + title: "", + width: "890px", + items: [ + cboType, + cboStatusCase, + cboTargetTask, + cboOriginTask, + cboParticipationRequired, + cboDynaForm, + cboInputDocument, + cboOutputDocument, + cboPermission + ] + }); + + btnCreate = new PMUI.ui.Button({ + id: "btnCreate", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + "mafe-button-create" + ] + }, + + handler: function () { + frmProcessPermissions.reset(); + processPermissionsDataIni = {}; + + processPermissionsDataIni.op_case_status = "ALL"; + processPermissionsDataIni.tas_uid = ""; + processPermissionsDataIni.usr_uid = ""; + processPermissionsDataIni.op_task_source = ""; + processPermissionsDataIni.op_participate = "0"; + processPermissionsDataIni.op_obj_type = "ANY"; + processPermissionsDataIni.op_obj_uid = ""; + processPermissionsDataIni.op_action = "VIEW"; + + processPermissionsSetForm("POST", {}); + } + }); + + grdpnlProcessPermissions = new PMUI.grid.GridPanel({ + id: "grdpnlProcessPermissions", + filterPlaceholder: "Search ...".translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + width: "96%", + tableContainerHeight: 374, + //height: DEFAULT_WINDOW_HEIGHT - 60, + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterable: true, + columns: [ + { + columnData: "group_user", + title: "Group or User".translate(), + alignmentCell: 'left', + width: "190px", + sortable: true + }, + { + columnData: "op_obj_type", + title: "Type".translate(), + alignmentCell: 'left', + width: "100px", + sortable: true + }, + { + columnData: "participated", + title: "Participation".translate(), + alignmentCell: 'left', + width: "115px", + sortable: true + }, + { + columnData: "object", + title: "Object".translate(), + alignmentCell: 'left', + width: "158px", + sortable: true + }, + { + columnData: "op_action", + title: "Permission".translate(), + alignmentCell: 'left', + width: "100px", + sortable: true + }, + { + columnData: "op_case_status", + title: "Status".translate(), + alignmentCell: 'left', + width: "70px", + sortable: true + }, + { + id: 'grdpnlProcessPermissionsButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: "70px", + buttonStyle: { + cssClasses: [ + "mafe-button-edit" + ] + }, + + onButtonClick: function (row, grid) { + var data; + frmProcessPermissions.reset(); + data = row.getData(); + processPermissionGetRestProxy(data.op_uid); + } + }, + { + id: 'grdpnlProcessPermissionsButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + width: "80px", + buttonStyle: { + cssClasses: [ + "mafe-button-delete" + ] + }, + + onButtonClick: function (row, grid) { + var data = row.getData(), msgWarning; + msgWarning = new PMUI.ui.MessageWindow({ + id: "msgWarning", + windowMessageType: 'warning', + width: 490, + title: "Permissions".translate(), + message: "Do you want to delete this permission?".translate(), + footerItems: [ + { + id: 'msgWarningButtonNo', + text: "No".translate(), + handler: function () { + msgWarning.close(); + }, + buttonType: "error" + }, + { + id: 'msgWarningButtonYes', + text: "Yes".translate(), + handler: function () { + processPermissionsDeleteRestProxy(data.op_uid); + msgWarning.close(); + }, + buttonType: "success" + } + ] + }); + + msgWarning.open(); + msgWarning.dom.titleContainer.style.height = '17px'; + msgWarning.showFooter(); + } + } + ], + dataItems: null + }); + + winGrdpnlProcessPermissions = new PMUI.ui.Window({ + id: "winGrdpnlProcessPermissions", + title: "Permissions".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + buttonPanelPosition: "bottom", + footerAlign: "right", + onBeforeClose: function () { + clickedClose = true; + isDirtyFormProcessPermission(); + }, + footerItems: [ + { + id: "btnCancel", + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + clickedClose = false; + isDirtyFormProcessPermission(); + } + }, + { + id: "btnSave", + text: "Save".translate(), + buttonType: "success", + handler: function () { + var cboGroupOrUserValue = "", groupOrUser, data; + + if (frmProcessPermissions.isValid() && cboGroupOrUser.isValid()) { + if (cboGroupOrUser.data) { + if (cboGroupOrUser.data.hasOwnProperty("usr_uid")) { + cboGroupOrUserValue = "1|" + cboGroupOrUser.get("value"); + } + if (cboGroupOrUser.data.hasOwnProperty("grp_uid")) { + cboGroupOrUserValue = "2|" + cboGroupOrUser.get("value"); + } + } else { + cboGroupOrUserValue = ""; + } + groupOrUser = cboGroupOrUserValue.split("|"); + + data = { + op_case_status: cboStatusCase.getValue(), + tas_uid: cboTargetTask.getValue() === '0' ? '' : cboTargetTask.getValue(), + op_user_relation: groupOrUser[0], + usr_uid: groupOrUser[1], + op_task_source: cboOriginTask.getValue() === '0' ? '' : cboOriginTask.getValue(), + op_participate: cboParticipationRequired.getValue() + }; + + switch (cboType.getValue()) { + case "DYNAFORM": + data["op_obj_type"] = cboType.getValue(); + data["dynaforms"] = cboDynaForm.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "INPUT": + data["op_obj_type"] = cboType.getValue(); + data["inputs"] = cboInputDocument.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "OUTPUT": + data["op_obj_type"] = cboType.getValue(); + data["outputs"] = cboOutputDocument.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "CASES_NOTES": + data["op_obj_type"] = cboType.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "REASSIGN_MY_CASES": + data = {}; + data["op_user_relation"] = groupOrUser[0]; + data["usr_uid"] = groupOrUser[1]; + data["tas_uid"] = cboTargetTask.getValue() === '0' ? '' : cboTargetTask.getValue(); + data["op_obj_type"] = cboType.getValue(); + break; + default: + data["op_obj_type"] = cboType.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + } + switch (PROCESS_PERMISSIONS_OPTION) { + case "POST": + processPermissionsPostRestProxy(data); + break; + case "PUT": + processPermissionsPutRestProxy(PROCESS_PERMISSIONS_UID, data); + break; + } + } else { + cboGroupOrUser.showMessageRequired(); + frmProcessPermissions.addItem(notification) + } + + cboGroupOrUser.html.find("input").val(""); + cboGroupOrUser.value = ""; + } + } + ] + }); + + winGrdpnlProcessPermissions.addItem(grdpnlProcessPermissions); + winGrdpnlProcessPermissions.addItem(frmProcessPermissions); + + refreshGridPanelInMainWindow(); + if (typeof listProcessPermissions !== "undefined") { + winGrdpnlProcessPermissions.open(); + $(cboGroupOrUser.createHTML()).insertBefore(cboType.html); + + + cboGroupOrUser.html.find("input").val(""); + jQuery(grdpnlProcessPermissions.html).css({ + margin: "2px" + }); + winGrdpnlProcessPermissions.body.style.height = "auto"; + $('#grdpnlProcessPermissions .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + winGrdpnlProcessPermissions.defineEvents(); + applyStyleWindowForm(winGrdpnlProcessPermissions); + + grdpnlProcessPermissions.dom.toolbar.appendChild(btnCreate.getHTML()); + btnCreate.defineEvents(); + disableAllItems(); + refreshGridPanelInMainWindow(); + } + }; + + PMDesigner.processPermissions.create = function () { + PMDesigner.processPermissions(); + + frmProcessPermissions.reset(); + processPermissionsDataIni = {}; + + processPermissionsDataIni.op_case_status = "ALL"; + processPermissionsDataIni.tas_uid = ""; + processPermissionsDataIni.usr_uid = ""; + processPermissionsDataIni.op_task_source = ""; + processPermissionsDataIni.op_participate = "0"; + processPermissionsDataIni.op_obj_type = "ANY"; + processPermissionsDataIni.op_obj_uid = ""; + processPermissionsDataIni.op_action = "VIEW"; + + processPermissionsSetForm("POST", {}); + }; + }() +); + +(function () { + var winHtmlShow, loadValuesStartMessage; + + PMDesigner.startMessage = function (element) { + var winGrdpnlStartMessage, + btnNew, + cboUser, + cboDynaForm, + btnGenerateStartMessagePage, + frmDataStartMessage, + frmHtml, + winFrmDataStartMessage, + restProxy, + disableAllItems, + winFrmStartMessageShow, + updateStartMessage, + loadDataDynaform, + loadDataUsers, + loadDataForm, + listUsers = [], + cboMethod, + listDynaforms = [], + dataForm = [], + enableGenerateWebEntry, + btnSaveStartMessagePage, + btnStartMessageCancel, + btnClose, + startMessage = element; + + disableAllItems = function () { + winGrdpnlStartMessage.getItems()[0].setVisible(false); + winGrdpnlStartMessage.getItems()[1].setVisible(false); + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(false); + winGrdpnlStartMessage.hideFooter(); + }; + + winFrmStartMessageShow = function () { + disableAllItems(); + frmDataStartMessage.reset(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.getItems()[0].setVisible(true); + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + loadDataUsers(); + loadDataDynaform(); + loadDataForm(); + frmDataStartMessage.setFocus(); + }; + + winHtmlShow = function (msgHtml) { + if (typeof msgHtml == 'undefined') { + msgHtml = dataForm.we_data; + if (dataForm.we_method == "WS") { + window.open(msgHtml); + winGrdpnlStartMessage.close(); + return false; + } + } + disableAllItems(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.getItems()[1].setVisible(true); + winGrdpnlStartMessage.getItems()[1].setWidth(925); + winGrdpnlStartMessage.getItems()[1].setHeight(440); + winGrdpnlStartMessage.getItems()[1].hideHeader(); + frmHtml.getFields()[0].setHeight(396); + frmHtml.getItems()[0].setValue(msgHtml); + frmHtml.panel.style.addProperties({'box-sizing': 'initial'}); + frmHtml.style.addProperties({marginLeft: '16px'}); + frmHtml.setFocus(); + return true; + }; + + loadValuesStartMessage = function (flag) { + var viewFlagForm, + restClient, + response; + listUsers = []; + listDynaforms = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startMessage.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: "activity/" + startMessage.ports.get(0).connection.flo_element_dest + "/steps", + method: 'GET' + }, { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + listDynaforms = response[1].response; + dataForm = response[2].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + if (flag) { + viewFlagForm = false; + if (typeof dataForm == 'object' && dataForm.we_data != null) { + viewFlagForm = true; + } + response = [listUsers.length, listDynaforms.length, viewFlagForm]; + return response; + } + return true; + }; + + updateStartMessage = function (data) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: "web-entry/" + startMessage.evn_uid, + method: 'PUT', + data: data + }, + { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataForm = response[1].response; + if (data.we_method == "HTML") { + winHtmlShow(response.we_data); + } + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ["There are problems updating the Web Entry, please try again.".translate()], + messageSuccess: ['Web Entry updated successfully'.translate()], + flashContainer: frmDataStartMessage + }); + restClient.executeRestClient(); + }; + + loadDataDynaform = function () { + var i; + cboDynaForm.clearOptions(); + for (i = 0; i <= listDynaforms.length - 1; i++) { + if (listDynaforms[i].step_type_obj == "DYNAFORM") { + cboDynaForm.addOption({ + value: listDynaforms[i].step_uid_obj, + label: listDynaforms[i].obj_title + }); + } + } + }; + + loadDataUsers = function () { + var i; + cboUser.clearOptions(); + for (i = 0; i <= listUsers.length - 1; i++) { + cboUser.addOption({ + value: listUsers[i].aas_uid, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + cboUser.setValue(dataForm.usr_uid); + cboDynaForm.setValue(dataForm.dyn_uid); + cboMethod.setValue(dataForm.we_method); + }; + + enableGenerateWebEntry = function () { + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + btnClose.setVisible(false); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(true); + }; + cboUser = new PMUI.field.DropDownListField({ + id: "cboUser", + name: "cboUser", + label: "User".translate(), + required: true, + options: null, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboDynaForm = new PMUI.field.DropDownListField({ + id: "cboDynaForm", + name: "cboDynaForm", + label: "Initial Dynaform".translate(), + options: null, + required: true, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboMethod = new PMUI.field.DropDownListField({ + id: "cboMethod", + name: "cboMethod", + label: "Method".translate(), + value: "WS", + options: [ + { + value: "WS", + label: "PHP pages with Web Services".translate() + }, + { + value: "HTML", + label: "Single HTML".translate() + } + ], + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + btnGenerateStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Generate Web Entry Page".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + btnSaveStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Save".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + + frmDataStartMessage = new PMUI.form.Form({ + id: "frmDataStartMessage", + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + items: [ + cboUser, + cboDynaForm, + cboMethod + ], + visibleHeader: false + }); + + btnClose = new PMUI.ui.Button({ + id: "btnClose", + text: "Close".translate(), + handler: function () { + winGrdpnlStartMessage.close(); + }, + buttonType: 'success', + height: 31 + }); + + btnStartMessageCancel = new PMUI.ui.Button({ + id: "btnStartMessageCancel", + text: "Cancel".translate(), + handler: function () { + var message_window; + if (frmDataStartMessage.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + id: "cancelMessageStartTimer", + title: "Start Message Event".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + bodyHeight: 'auto', + width: 490, + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + winGrdpnlStartMessage.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + frmDataStartMessage.reset(); + winGrdpnlStartMessage.close(); + } + } + }); + + frmHtml = new PMUI.form.Form({ + id: "frmHtml", + title: "", + width: DEFAULT_WINDOW_WIDTH - 43, + items: [ + { + id: "txtHtml", + name: "txtHtml", + pmType: "textarea", + valueType: "string", + rows: 400, + value: '', + controlsWidth: DEFAULT_WINDOW_WIDTH - 50, + labelVisible: false, + style: {cssClasses: ['mafe-textarea-resize']} + } + ] + }); + + winGrdpnlStartMessage = new PMUI.ui.Window({ + id: "winGrdpnlStartMessage", + title: "Start Message Event".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: "top", + buttons: [btnSaveStartMessagePage, {pmType: 'label', text: 'or'}, btnStartMessageCancel, btnClose] + }); + + winGrdpnlStartMessage.addItem(frmDataStartMessage); + + openForm = function () { + winGrdpnlStartMessage.open(); + winGrdpnlStartMessage.defineEvents(); + applyStyleWindowForm(winGrdpnlStartMessage); + winGrdpnlStartMessage.footer.html.style.textAlign = 'right'; + winFrmStartMessageShow(); + } + }; + + PMDesigner.startMessage.openForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.viewForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.validate = function (starMessageEvent) { + if (starMessageEvent.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 4000, 5); + return [false, false]; + } + PMDesigner.startMessage(starMessageEvent); + response = loadValuesStartMessage(true); + if (response[0] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 4000); + return [false, false]; + } + if (response[1] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned Dynaforms'.translate(), document.body, 'info', 4000); + return [false, false]; + } + return [true, response[2]]; + } +}()); + +(function () { + var windowPropSub; + + PMDesigner.propertiesSubProcess = function (activity) { + var typeVariables = ['@@', '@#', '@=', '@&'], + restClient, + isDirtyFormSubProcess, + getSubProcess, + formVarTexOriginOut, + updateSubProcess, + formVarTexOriginIn, + loadDropProcess, + formVarTexTargetOut, + formVarTexTargetIn, + windowPropertiesSub, + formProperties, + sepInputs, + gridVariablesOut, + gridVariablesIn, + formVariablesPanelOut, + formVariablesPanelIn, + validateVariable, + formVarButtonAddOut, + formVarButtonAddIn, + labelVariablesOut, + labelVariablesIn, + loadDataServer, + loadActivity, + isDirty = false; + + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i += 1) { + if (response[i].prj_uid != PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + isDirtyFormSubProcess = function () { + var message_window; + if (formProperties.isDirty() || isDirty) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: "cancelSaveSubprocPropertiesWin", + title: "Sub-process Properties".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + windowPropertiesSub.close(); + } + }; + getSubProcess = function () { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var yout, + oout, + jout, + itemsOut, + i, + xin, + yin, + oin, + jin, + dout, + din, + itemsIn, + xout; + formProperties.getField('out_doc_title').setValue(response.spr_name); + formProperties.getField('out_doc_process').setValue(response.spr_pro); + formProperties.getField('out_doc_type').setValue(response.spr_synchronous); + + if (response.spr_variables_out != false) { + xout = JSON.stringify(response.spr_variables_out); + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + + itemsOut = []; + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); + } + gridVariablesOut.setDataItems(itemsOut); + + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + } + + if (response.spr_variables_in != false && response.spr_variables_in != undefined) { + xin = JSON.stringify(response.spr_variables_in); + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + + itemsIn = []; + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } + gridVariablesIn.setDataItems(itemsIn); + } + + if (response.spr_synchronous == "1") { + gridVariablesIn.setVisible(true); + formVariablesPanelIn.setVisible(true); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + updateSubProcess = function (data) { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + var name = formProperties.getData().out_doc_title; + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + formVarTexOriginOut = new CriteriaField({ + id: 'idformVarTexOriginOut', + pmType: "text", + name: 'nmformVarTexOriginOut', + placeholder: 'Origin'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + formVarTexOriginIn = new CriteriaField({ + id: 'idformVarTexOriginIn', + pmType: "text", + name: 'nmformVarTexOriginIn', + placeholder: 'Select Origin Process'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + formVarTexTargetOut = new CriteriaField({ + id: 'idformVarTexTargetOut', + pmType: "text", + name: 'nmformVarTexTargetOut', + placeholder: 'Select Target Process'.translate(), + labelVisible: false, + controlsWidth: 150, + required: true + }); + + formVarTexTargetIn = new CriteriaField({ + id: 'idformVarTexTargetIn', + pmType: "text", + name: 'nmformVarTexTargetIn', + placeholder: 'Target'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + windowPropertiesSub = new PMUI.ui.Window({ + id: 'propSubWindow', + title: "Sub-process Properties".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + bodyHeight: '465px', + bodyWidth: '900px', + onBeforeClose: function () { + isDirtyFormSubProcess(); + }, + buttons: [ + { + id: 'propSubButtonClose', + text: "Close".translate(), + buttonType: 'error', + handler: function () { + isDirtyFormSubProcess(); + } + }, + { + id: 'propSubButtonSave', + text: "Save".translate(), + buttonType: 'success', + handler: function () { + if (!formProperties.isValid()) { + return; + } + var propertiesData = formProperties.getData(); + var variablesOutData = gridVariablesOut.getData(); + var variablesOut = {}; + if (variablesOutData.length > "0") { + for (i = 0; i < variablesOutData.length; i += 1) { + variablesOut[variablesOutData[i].origin] = variablesOutData[i].target; + } + } + var variablesIn = {}; + if (propertiesData.out_doc_type == "1") { + var variablesInData = gridVariablesIn.getData(); + if (variablesInData.length > "0") { + for (j = 0; j < variablesInData.length; j += 1) { + variablesIn[variablesInData[j].origin] = variablesInData[j].target; + } + } + } + + var dataToSend = { + spr_pro: propertiesData.out_doc_process, + spr_tas: propertiesData.spr_tas, + spr_name: propertiesData.out_doc_title, + spr_synchronous: propertiesData.out_doc_type, + spr_variables_out: variablesOut, + spr_variables_in: variablesIn + }; + + updateSubProcess(dataToSend); + } + } + ], + buttonPanelPosition: 'bottom', + buttonsPosition: 'right' + }); + + formProperties = new PMUI.form.Form({ + id: 'propSubForm', + title: "", + fieldset: true, + visibleHeader: false, + width: 926, + height: 'auto', + items: [ + { + id: 'propSubFormTitle', + pmType: "text", + name: 'out_doc_title', + label: "Sub-Process name".translate(), + required: true, + controlsWidth: 300 + }, + { + id: 'propSubFormProcess', + pmType: "dropdown", + name: 'out_doc_process', + label: "Process".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + if (a.trim().length !== 0) { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + formVarTexTargetOut.controls[0].setPlaceholder("Target"); + formVarTexOriginIn.controls[0].setPlaceholder("Origin"); + } else { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } + formVarTexTargetOut.setProcess(a); + formVarTexOriginIn.setProcess(a); + loadActivity(a); + } + }, + { + id: 'propSubFormActivity', + pmType: "dropdown", + name: 'spr_tas', + label: "Starting activity".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select starting activity -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + } + }, + { + id: 'propSubFormType', + pmType: "dropdown", + name: 'out_doc_type', + label: "Type".translate(), + controlsWidth: 150, + required: true, + options: [ + { + label: "Asynchronous".translate(), + value: "0" + }, + { + label: "Synchronous".translate(), + value: "1" + } + ], + value: "0", + onChange: function (a, b) { + isDirty = true; + } + } + ], + onChange: function (newValue, prevValue) { + switch (newValue.value) { + case "1" : + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + break; + case "0": + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + windowPropertiesSub.getItems()[4].setVisible(false); + break; + default : + break; + } + } + }); + + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + + formProperties.addItem(sepInputs); + + gridVariablesOut = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesOut', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + style: { + cssClasses: ["mafe-gridPanel"] + }, + columns: [ + { + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesOutButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + } + + } + ] + }); + + gridVariablesIn = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesIn', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + columns: [ + { + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesInButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + } + } + ] + }); + + formVariablesPanelOut = new PMUI.core.Panel({ + id: "formVariablesPanelOut", + layout: "hbox", + fieldset: true, + width: DEFAULT_WINDOW_WIDTH - 70 + }); + + formVariablesPanelIn = new PMUI.core.Panel({ + id: "formVariablesPanelIn", + layout: "hbox", + fieldset: true, + legend: "Variables In".translate(), + width: DEFAULT_WINDOW_WIDTH - 70 + }); + + validateVariable = function (field) { + var value; + field.controls[0].style.removeClasses(['error']) + value = field.getValue(); + if (value == '') { + PMDesigner.msgWinWarning('Please insert variable before adding to the list.'.translate()); + field.controls[0].style.addClasses(['error']) + return false; + } + if (typeVariables.indexOf(String(value.substring(0, 2))) != -1) { + return true; + } + PMDesigner.msgWinWarning("The value introduced doesn\'t have the correct format with a vallid prefix (@@, @#, @=, @&)".translate()); + field.controls[0].style.addClasses(['error']) + return false; + }; + + formVarButtonAddOut = new PMUI.ui.Button({ + id: 'formVarButtonAddOut', + text: 'Add'.translate(), + width: 60, + visible: false, + buttonType: "success", + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px" + } + }, + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginOut) && validateVariable(formVarTexTargetOut)) { + a = formVarTexOriginOut.getValue(); + b = formVarTexTargetOut.getValue(); + gridVariablesOut.addDataItem({origin: a, target: b}); + formVarTexOriginOut.setValue(""); + formVarTexTargetOut.setValue(""); + isDirty = true; + + gridOut = document.getElementById("propSubGridVariablesOut").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); + + formVarButtonAddIn = new PMUI.ui.Button({ + id: 'formVarButtonAddIn', + text: 'Add'.translate(), + width: 60, + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px", + } + }, + buttonType: 'success', + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginIn) && validateVariable(formVarTexTargetIn)) { + a = formVarTexOriginIn.getValue(); + b = formVarTexTargetIn.getValue(); + gridVariablesIn.addDataItem({origin: a, target: b}); + formVarTexOriginIn.setValue(""); + formVarTexTargetIn.setValue(""); + isDirty = true; + + gridOut = document.getElementById("propSubGridVariablesIn").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); + + labelVariablesOut = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables Out'.translate() + }); + + labelVariablesIn = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables In'.translate() + }); + + loadDropProcess = function () { + formProperties.getField('out_doc_process').clearOptions(); + formProperties.getField('out_doc_process').addOption({ + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }); + }; + loadDataServer = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'projects', + method: 'GET' + }, + { + url: 'project/' + PMDesigner.project.id + '/subprocess/' + activity.act_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var dt, + itemsOut, + yout, + oout, + jout, + dout, + xin, + yin, + oin, + jin, + din, + itemsIn, + xout; + + //projects + dt = response[0].response; + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].prj_uid !== PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: dt[i].prj_name, + value: dt[i].prj_uid + }); + } + } + //subprocess + dt = response[1].response; + formProperties.getField('out_doc_title').setValue(dt.spr_name); + formProperties.getField('out_doc_process').setValue(dt.spr_pro === '0' ? '' : dt.spr_pro); + formProperties.getField('out_doc_type').setValue(dt.spr_synchronous); + + if (dt.spr_variables_out !== false) { //Asynchronous + xout = JSON.stringify(dt.spr_variables_out); + itemsOut = []; + if (xout != "[]") { + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); + } + } + gridVariablesOut.setDataItems(itemsOut); + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + } + + if (dt.spr_variables_in !== false && dt.spr_variables_in !== undefined) { //Synchronous + xin = JSON.stringify(dt.spr_variables_in); + itemsIn = []; + if (xin != "[]") { + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } + } + gridVariablesIn.setDataItems(itemsIn); + } + + if (dt.spr_synchronous === "1") { + gridVariablesIn.setVisible(true); + formVariablesPanelIn.setVisible(true); + } + if (formProperties.getField('out_doc_process').getValue() !== '') { + loadActivity(formProperties.getField('out_doc_process').getValue()); + } + formProperties.getField('spr_tas').setValue(dt.spr_tas === '0' ? '' : dt.spr_tas); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadActivity = function (value) { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + value + '/starting-tasks', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var dropdown, + i, + dt = response[0].response; + dt = dt.sort(function (a, b) { + return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); + }); + dropdown = formProperties.getField('spr_tas'); + dropdown.clearOptions(); + dropdown.addOption({ + value: '', + label: '- Select starting activity -'.translate() + }); + for (i = 0; i < dt.length; i += 1) { + dropdown.addOption({ + value: dt[i].act_uid, + label: dt[i].act_name + }); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + + formVariablesPanelOut.addItem(formVarTexOriginOut); + formVariablesPanelOut.addItem(formVarTexTargetOut); + formVariablesPanelOut.addItem(formVarButtonAddOut); + + formVariablesPanelIn.addItem(formVarTexOriginIn); + formVariablesPanelIn.addItem(formVarTexTargetIn); + formVariablesPanelIn.addItem(formVarButtonAddIn); + + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + + windowPropertiesSub.addItem(formProperties); + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables Out'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '-15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' + } + }, + display: 'block' + })); + windowPropertiesSub.addItem(formVariablesPanelOut); + windowPropertiesSub.addItem(gridVariablesOut); + + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables In'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' + } + }, + display: 'block', + visible: false + })); + + windowPropertiesSub.addItem(formVariablesPanelIn); + windowPropertiesSub.addItem(gridVariablesIn); + + loadDropProcess(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + loadDataServer(); + + if (formProperties.getItems()[1].getValue() != "0") { + formVarTexTargetOut.setProcess(formProperties.getItems()[1].getValue()); + formVarTexOriginIn.setProcess(formProperties.getItems()[1].getValue()); + } + windowPropertiesSub.open(); + if (formProperties.getField('out_doc_process').getValue().trim().length === 0) { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } else { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + } + windowPropertiesSub.showFooter(); + applyStyleWindowForm(windowPropertiesSub); + formVariablesPanelIn.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelIn.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.style.addProperties({marginLeft: '45px'}); + gridVariablesOut.style.addProperties({marginLeft: '45px'}); + if (formVariablesPanelIn.visible == true) { + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + } + + formVariablesPanelOut.style.addProperties({width: '870px'}); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + windowPropertiesSub.defineEvents(); + gridVariablesOut.html.children[0].style.display = "none"; + gridVariablesIn.html.children[0].style.display = "none"; + formProperties.getField('out_doc_title').setFocus(); + formVarButtonAddOut.setWidth(80); + formVarButtonAddOut.setVisible(true); + + }; +}()); +if (typeof(consolidated) == 'undefined') { + consolidated = '0'; +} +PMDesigner.activityProperties = function (activity) { + switch (activity.getActivityType()) { + case "SUB_PROCESS": + PMDesigner.propertiesSubProcess(activity); + break; + case "TASK": + if (activity.getTaskType() === "SCRIPTTASK") { + PMDesigner.scriptTaskProperties(activity); + } else { + PMDesigner.taskProperties(activity); + } + break; + } +}; + +PMDesigner.taskProperties = function (activity) { + var formDefinitions, + featuresForms = [], + propertiesTabs, + formCaseLabels, + dataProperties, + formTimingControl, + configurationForms, + customGrid, + formNotifications, + buttonFieldCancel, + buttonFieldAdd, + abeForm, + MobilePanel, + enableTaskMobile, + routeCaseMobile, + abeMainPanel, + abeAddOption, + abeTemplates, + abeDynaforms, + abeReceiverAccount, + abeEmailAcount, + abeFields, + warningChanges, + windowProperties, + processDataProperties, + i, + editRow = null, + arrayTrue = '["TRUE"]', + arrayFalse = '["FALSE"]', + stringTrue = "TRUE", + stringFalse = "FALSE", + defaultServerlabel = "Mail (PHP)".translate(); + + configurationForms = [ + { + id: 'windowPropertiesTabPanelDefinitions', + icon: '', + title: 'Definitions'.translate(), + panel: formDefinitions = new PMUI.form.Form({ + id: 'formDefinitions', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formDefinitionsUID', + pmType: 'text', + name: 'UID', + valueType: 'string', + label: 'UID'.translate(), + controlsWidth: 300 + }, { + id: 'formDefinitionsTitle', + pmType: 'text', + name: 'tas_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300 + }, { + id: 'formDefinitionsDescription', + pmType: 'textarea', + name: 'tas_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: 300, + style: {cssClasses: ['mafe-textarea-resize']} + }, new CriteriaField({ + id: 'formDefinitionsVariable', + pmType: 'text', + name: 'tas_priority_variable', + valueType: 'string', + label: 'Variable for Case priority'.translate(), + controlsWidth: 300 + }), { + id: 'formDefinitionsRouting', + pmType: 'dropdown', + name: 'tas_derivation_screen_tpl', + valueType: 'string', + label: 'Routing Screen Template'.translate(), + controlsWidth: 150, + style: { + cssProperties: { + float: "left" + } + } + } + ] + }) + }, + { + id: 'windowPropertiesTabPanelCaseLabels', + icon: '', + title: 'Case Labels'.translate(), + panel: formCaseLabels = new PMUI.form.Form({ + id: 'formCaseLabels', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [new CriteriaField({ + id: 'formCaseLabelsTitle', + pmType: 'text', + name: 'tas_def_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + controlsWidth: DEFAULT_WINDOW_WIDTH - 527 + }), new CriteriaField({ + id: 'formCaseLabelsDescription', + pmType: 'textarea', + name: 'tas_def_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: DEFAULT_WINDOW_WIDTH - 527, + renderType: 'textarea' + }) + ] + }) + }, + { + id: 'windowPropertiesTabPanelTimingControl', + icon: '', + title: 'Timing Control'.translate(), + panel: formTimingControl = new PMUI.form.Form({ + id: 'formTimingControl', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formTimingControlFly', + pmType: 'checkbox', + name: 'tas_transfer_fly', + labelVisible: false, + options: [ + { + id: 'formTimingControlOption', + label: 'Allow users to change the task duration in runtime'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeTimingControl(this.controls[0].selected); + } + }, { + id: 'formTimingMainPanel', + pmType: 'panel', + items: [ + { + id: 'formTimingControlTask', + pmType: 'text', + name: 'tas_duration', + valueType: 'string', + label: 'Task duration'.translate(), + required: true, + maxLength: 3, + controlsWidth: 200, + validators: [ + { + pmType: "regexp", + criteria: /^\d*$/, + errorMessage: "Please enter a positive integer value".translate() + } + ] + }, + { + id: 'formTimingControlAverage', + pmType: 'text', + name: 'tas_average', + valueType: 'string', + label: 'Average'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlSdv', + pmType: 'text', + name: 'tas_sdv', + valueType: 'string', + label: 'SDV'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlTime', + pmType: 'dropdown', + name: 'tas_timeunit', + label: 'Time unit'.translate(), + controlsWidth: 100, + options: [{ + id: 'formTimingControlTime1', + label: 'Hours'.translate(), + value: 'HOURS' + }, { + id: 'formTimingControlTime2', + label: 'Days'.translate(), + value: 'DAYS' + }, { + id: 'formTimingControlTime3', + label: 'Minutes'.translate(), + value: 'MINUTES' + } + ] + }, { + id: 'formTimingControlCount', + pmType: 'dropdown', + name: 'tas_type_day', + label: 'Count days by'.translate(), + controlsWidth: 150, + options: [{ + id: 'formTimingControlCount1', + label: 'Work Days'.translate(), + value: 1 + }, { + id: 'formTimingControlCount2', + label: 'Calendar Days'.translate(), + value: 2 + } + ] + }, { + id: 'formTimingControlCalendar', + pmType: 'dropdown', + name: 'tas_calendar', + label: 'Calendar'.translate(), + options: [], + controlsWidth: 150 + } + ] + } + ] + }) + }, + { + id: 'windowPropertiesTabPanelNotifications', + icon: '', + title: 'Notifications'.translate(), + panel: formNotifications = new PMUI.form.Form({ + id: 'formNotifications', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formNotificationsTasSend', + pmType: 'checkbox', + name: 'tas_send_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasSend1', + label: 'After routing notify the next assigned user(s)'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeFormNotifications(this.controls[0].selected, 'text'); + } + }, { + id: 'formNotificationsMainPanel', + pmType: 'panel', + items: [ + { + id: 'tas_email_server_uid', + name: 'tas_email_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_not_email_from_format', + name: 'tas_not_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'formNotificationsSubject', + pmType: 'text', + name: 'tas_def_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), { + id: 'formNotificationsContent', + pmType: 'dropdown', + name: 'tas_def_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsContent1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsContent2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentType(value); + } + }, new CriteriaField({ + id: 'formNotificationsMessage', + pmType: 'textarea', + name: 'tas_def_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), { + id: 'formNotificationsTemplate', + pmType: 'dropdown', + name: 'tas_def_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" + } + ] + }, + { + id: 'formNotificationsTasReceive', + pmType: 'checkbox', + name: 'tas_receive_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasReceive', + label: 'Notify the assigned user to this task'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeFormNotificationsReceive(this.controls[0].selected, 'text'); + } + }, + { + id: 'formNotificationsReceivePanel', + pmType: 'panel', + items: [ + { + id: 'tas_receive_server_uid', + name: 'tas_receive_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_receive_email_from_format', + name: 'tas_receive_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'tas_receive_subject_message', + pmType: 'text', + name: 'tas_receive_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), + { + id: 'tas_receive_message_type', + pmType: 'dropdown', + name: 'tas_receive_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsReceive1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsReceive2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentTypeReceive(value); + } + }, + new CriteriaField({ + id: 'tas_receive_message', + pmType: 'textarea', + name: 'tas_receive_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), + { + id: 'tas_receive_message_template', + pmType: 'dropdown', + name: 'tas_receive_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" + } + + ] + } + ] + }) + } + ]; + if (consolidated == '1') { + configurationForms.push({ + id: 'windowPropertiesTabPanelConsolidated', + icon: '', + title: 'Consolidated Case '.translate(), + panel: formConsolidated = new PMUI.form.Form({ + id: 'formConsolidated', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formConsolidatedEnable', + pmType: 'checkbox', + name: 'consolidated_enable', + labelVisible: false, + options: [{ + label: 'Enable consolidate for this task.'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeConsolidated(this.controls[0].selected); + } + }, { + id: 'formConsolidatedMainPanel', + pmType: 'panel', + items: [ + { + id: 'formConsolidatedReportTable', + pmType: 'text', + name: 'consolidated_report_table', + visible: false, + valueType: 'string', + controlsWidth: 300 + }, { + id: 'formConsolidatedDynaform', + pmType: 'dropdown', + name: 'consolidated_dynaform', + label: 'Dynaform Template'.translate(), + options: [], + required: true, + controlsWidth: 300 + }, { + id: 'formConsolidatedTable', + pmType: 'text', + name: 'consolidated_table', + valueType: 'string', + label: 'Table Name'.translate(), + placeholder: 'Insert a table name'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + }, + validators: [{ + pmType: "regexp", + criteria: /^[a-zA-Z0-9_]+$/, + errorMessage: "The table name can not contain spaces".translate() + }] + }, { + id: 'formConsolidatedTitle', + pmType: 'text', + name: 'consolidated_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + } + } + ] + } + ] + }) + }); + } + + + warningChanges = new PMUI.ui.MessageWindow({ + id: 'warningChanges', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Activity Properties'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningChangesButtonNo', + text: "No".translate(), + handler: function () { + warningChanges.close(); + }, + buttonType: "error" + }, + { + id: 'warningChangesButtonYes', + text: "Yes".translate(), + handler: function () { + windowProperties.close(); + warningChanges.close(); + }, + buttonType: "success" + } + ] + }); + windowProperties = new PMUI.ui.Window({ + id: 'windowProperties', + title: 'Activity Properties'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + onOpen: function () { + loadServerData(); + }, + items: [ + propertiesTabs = new PMUI.panel.TabPanel({ + id: 'windowPropertiesTabPanel', + height: 435, + width: DEFAULT_WINDOW_WIDTH - 50, + style: { + cssProperties: { + 'margin-left': '10px' + } + }, + items: configurationForms.concat(featuresForms), + itemsPosition: { + position: 'left' + }, + onTabClick: function (tab) { + setFocusTab(tab); + } + }), + customGrid + ], + onBeforeClose: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonPanelPosition: 'bottom', + buttonsPosition: 'right', + buttons: [ + { + id: 'windowPropertiesButtonCancel', + text: 'Cancel'.translate(), + handler: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonType: "error" + }, + { + id: 'windowPropertiesButtonSave', + text: 'Save'.translate(), + handler: function () { + saveData(); + }, + buttonType: 'success' + } + ] + }); + + function changeConsolidated(value) { + var panel = formConsolidated.getItem('formConsolidatedMainPanel'); + formConsolidated.getField('consolidated_enable').setValue(value ? '["1"]' : '[]'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + + function changeTimingControl(value) { + var mainPanel = formTimingControl.getItem('formTimingMainPanel'); + formTimingControl.getField('tas_transfer_fly').setValue(value ? '["1"]' : '[]'); + if (mainPanel) { + if (value) { + mainPanel.disable(); + + } else { + mainPanel.enable(); + } + mainPanel.setVisible(!value); + } + if (window.enterprise !== "1") { + formTimingControl.getField('tas_average').setVisible(false); + formTimingControl.getField('tas_sdv').setVisible(false); + } + } + + function changeFormNotifications(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsMainPanel'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + if (value) { + formNotifications.getField('tas_def_message_type').setValue(valueTwo); + visibleContentType(valueTwo); + } + formNotifications.getField('tas_send_last_email').setValue(value ? '["1"]' : '[]'); + formNotifications.getField('tas_def_subject_message').setFocus(); + } + + /** + * Notification receive change handler, according to user selection + * @param value + * @param valueTwo + */ + function changeFormNotificationsReceive(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsReceivePanel'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + if (value) { + formNotifications.getField('tas_receive_message_type').setValue(valueTwo); + visibleContentTypeReceive(valueTwo); + } + formNotifications.getField('tas_receive_last_email').setValue(value ? '["1"]' : '[]'); + formNotifications.getField('tas_receive_subject_message').setFocus(); + } + + /** + * Get value parsed + * @param valueCheckBox '["TRUE"]'/'["FALSE"]' + * @returns {string} "TRUE"/"FALSE" + */ + function getValueCheckBox(valueCheckBox) { + var optionSelected = JSON.parse(valueCheckBox), + valChecked; + valChecked = (Array.isArray(optionSelected) && optionSelected.length === 1) ? optionSelected[0] : stringFalse; + return valChecked; + } + + function loadFormData(response) { + dataProperties = response.properties; + formDefinitions.getField('UID').setReadOnly(true); + formDefinitions.getField('UID').setValue(activity.id); + formDefinitions.getField('tas_title').setValue(dataProperties.tas_title); + formDefinitions.getField('tas_title').setFocus(); + formDefinitions.getField('tas_description').setValue(dataProperties.tas_description); + formDefinitions.getField('tas_priority_variable').setValue(dataProperties.tas_priority_variable); + formDefinitions.getField('tas_derivation_screen_tpl').setValue(dataProperties.tas_derivation_screen_tpl); + + formCaseLabels.getField('tas_def_title').setValue(dataProperties.tas_def_title); + formCaseLabels.getField('tas_def_description').setValue(dataProperties.tas_def_description); + + if (dataProperties.tas_transfer_fly === 'FALSE') { + changeTimingControl(false); + } else { + changeTimingControl(true); + } + formTimingControl.getField('tas_duration').setValue(dataProperties.tas_duration); + formTimingControl.getField('tas_timeunit').setValue(dataProperties.tas_timeunit); + formTimingControl.getField('tas_type_day').setValue(dataProperties.tas_type_day); + formTimingControl.getField('tas_calendar').setValue(dataProperties.tas_calendar); + + if (window.enterprise === "1") { + formTimingControl.getField('tas_average').setValue(dataProperties.tas_average); + formTimingControl.getField('tas_sdv').setValue(dataProperties.tas_sdv); + } + + changeFormNotifications(dataProperties.tas_send_last_email === 'TRUE', dataProperties.tas_def_message_type); + changeFormNotificationsReceive(dataProperties.tas_receive_last_email === 'TRUE', dataProperties.tas_receive_message_type); + formNotifications.getField('tas_def_subject_message').setValue(dataProperties.tas_def_subject_message); + formNotifications.getField('tas_def_message_type').setValue(dataProperties.tas_def_message_type); + formNotifications.getField('tas_def_message').setValue(dataProperties.tas_def_message); + formNotifications.getField('tas_email_server_uid').setValue(dataProperties.tas_email_server_uid); + formNotifications.getField('tas_def_message_template').setValue(dataProperties.tas_def_message_template); + formNotifications.getField('tas_not_email_from_format').setValue(dataProperties.tas_not_email_from_format); + // receive + formNotifications.getField('tas_receive_subject_message').setValue(dataProperties.tas_receive_subject_message); + formNotifications.getField('tas_receive_message_type').setValue(dataProperties.tas_receive_message_type); + formNotifications.getField('tas_receive_message').setValue(dataProperties.tas_receive_message); + formNotifications.getField('tas_receive_server_uid').setValue(dataProperties.tas_receive_server_uid); + formNotifications.getField('tas_receive_message_template').setValue(dataProperties.tas_receive_message_template); + formNotifications.getField('tas_receive_email_from_format').setValue(dataProperties.tas_receive_email_from_format); + } + function loadCalendar(response) { + var field = formTimingControl.getField('tas_calendar'), i; + field.clearOptions(); + field.addOption({ + value: '', + label: '- None -'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].cal_uid, + label: response[i].cal_name + }); + } + } + + /** + * Loads the template from rest service response + * @param response + * @param fieldName + */ + function loadTemplate(response, fieldName) { + var field = formNotifications.getField(fieldName), i, field2; + field.clearOptions(); + field.addOption({ + value: 'alert_message.html', + label: '-- Default --'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].prf_filename, + label: response[i].prf_filename + }); + } + field2 = formDefinitions.getField('tas_derivation_screen_tpl'); + field2.clearOptions(); + field2.addOption({ + value: '', + label: '-- Default --'.translate() + }); + for (i = 0; i < response.length; i += 1) { + if (response[i].prf_filename !== 'alert_message.html') { + field2.addOption({ + value: response[i].prf_filename, + label: response[i].prf_filename + }); + } + } + }; + /** + * Load Email account server dropdown options + * @param response + */ + function loadEmailAccount(response, fieldName) { + var field = formNotifications.getField(fieldName) || null, + i; + if (response instanceof Array && field) { + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + }; + + function loadABETemplateField(templates) { + var templateField = abeForm.getField('ABE_TEMPLATE'), i; + for (i in templates) { + if (templateField !== null) { + templateField.addOption({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + abeTemplates.options.push({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + }; + /** + * Loads the email accounts settings + * @param response + */ + function loadABEmailAccount(response) { + var accountField = abeForm.getField('ABE_EMAIL_SERVER_UID') || null, + i; + + if (response instanceof Array) { + for (i = 0; i < response.length; i += 1) { + if (accountField !== null) { + accountField.addOption({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + abeEmailAcount.options.push({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + + }; + + /** + * Loads the IMAP email accounts settings + * @param response + */ + function loadABImapEmailAccount(response) { + var accountField = abeForm.getField('ABE_RECEIVER_EMAIL_SERVER_UID') || null, + i; + + if (response instanceof Array) { + for (i = 0; i < response.length; i += 1) { + if (response[i].mess_engine === "IMAP") { + if (accountField !== null) { + accountField.addOption({ + value: response[i].mess_uid, + label: response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + abeReceiverAccount.options.push({ + value: response[i].mess_uid, + label: response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + } + + }; + + function loadABEDynaformField(dynaforms) { + var dynaformField = abeForm.getField('DYN_UID'), i; + for (i in dynaforms) { + if (dynaformField !== null) { + dynaformField.addOption({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME + }); + } + abeDynaforms.options.push({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME + }); + } + } + + function loadServerData() { + var restClient, i; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: { + "formconfig": { + "url": 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + "method": 'GET' + }, + "calendar": { + "url": 'calendar', + "method": 'GET' + }, + "templates": { + "url": 'project/' + PMDesigner.project.id + '/file-manager?path=templates', + "method": 'GET' + }, + "emailserver": { + "url": 'project/' + PMDesigner.project.id + '/email-event/accounts/emailServer', + "method": 'GET' + } + } + }, + functionSuccess: function (xhr, response) { + loadTemplate(response["templates"].response, 'tas_def_message_template'); + loadTemplate(response["templates"].response, 'tas_receive_message_template'); + loadCalendar(response["calendar"].response); + loadFormData(response["formconfig"].response); + loadEmailAccount(response["emailserver"].response, 'tas_email_server_uid'); + loadEmailAccount(response["emailserver"].response, 'tas_receive_server_uid'); + + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + if (consolidated == '1') { + $.extend(restClient.data.calls, { + "steps": { + 'url': 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/steps', + 'method': 'GET' + }, + "consolidate": { + "url": 'consolidated/' + activity.id, + "method": 'GET' + } + }); + } + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + } + + function visibleContentType(value) { + formNotifications.getField('tas_def_message_template').disable(); + formNotifications.getField('tas_def_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_def_message').enable(); + formNotifications.getField('tas_def_message').setVisible(true); + formNotifications.getField('tas_def_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_def_message_template').enable(); + formNotifications.getField('tas_def_message').setVisible(false); + formNotifications.getField('tas_def_message_template').setVisible(true); + } + }; + /** + * content type handler, enable or disable templates or message field + * @param value + */ + function visibleContentTypeReceive(value) { + formNotifications.getField('tas_receive_message_template').disable(); + formNotifications.getField('tas_receive_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_receive_message').enable(); + formNotifications.getField('tas_receive_message').setVisible(true); + formNotifications.getField('tas_receive_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_receive_message_template').enable(); + formNotifications.getField('tas_receive_message').setVisible(false); + formNotifications.getField('tas_receive_message_template').setVisible(true); + } + }; + function saveData() { + var tabPanel = windowProperties.getItem('windowPropertiesTabPanel'), + tabItems = tabPanel.getItems(), + valid = true, + panel, + tas_transfer_fly, + tas_send_last_email, + tas_receive_last_email, + dataCaseLabels, + dataDefinitions, + dataTimingControl, + dataNotification, + consolidated_enable, + message, + i; + + for (i = 0; i < tabItems.length; i += 1) { + panel = tabItems[i].getPanel(); + if (panel instanceof PMUI.form.Form) { + valid = valid && panel.isValid(); + } else { + if (panel.getID() === "ActionsByEmailPanel") { + if (!abeForm.isValid()) { + valid = false; + } + } + } + if (!valid) { + tabItems[i].select(); + return; + } + } + + tas_transfer_fly = formTimingControl.getField('tas_transfer_fly').getValue() === '["1"]'; + tas_send_last_email = formNotifications.getField('tas_send_last_email').getValue() === '["1"]'; + tas_receive_last_email = formNotifications.getField('tas_receive_last_email').getValue() === '["1"]'; + + if (tas_transfer_fly !== false) { + var a = formTimingControl.getField('tas_transfer_fly').getValue(); + formTimingControl.reset(); + formTimingControl.getField('tas_transfer_fly').setValue(a); + formTimingControl.getField('tas_duration').setValue('1'); + formTimingControl.getField('tas_timeunit').setValue('DAYS'); + formTimingControl.getField('tas_type_day').setValue(''); + formTimingControl.getField('tas_calendar').setValue(''); + } + + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataDefinitions = getData2PMUI(formDefinitions.html); + dataCaseLabels = getData2PMUI(formCaseLabels.html); + dataTimingControl = getData2PMUI(formTimingControl.html); + dataNotification = getData2PMUI(formNotifications.html); + if (!dataCaseLabels) { + dataCaseLabels = {}; + } + if (!dataTimingControl) { + dataTimingControl = {}; + } + if (!dataNotification) { + dataNotification = {}; + } + } else { + dataDefinitions = formDefinitions.getData(); + dataCaseLabels = formCaseLabels.getData(); + dataTimingControl = formTimingControl.getData(); + dataNotification = formNotifications.getData(); + } + + if (dataDefinitions['tas_title']) { + dataProperties.tas_title = dataDefinitions['tas_title']; + } + if (dataDefinitions['tas_description']) { + dataProperties.tas_description = dataDefinitions['tas_description']; + } + if (dataDefinitions['tas_priority_variable'] || typeof dataDefinitions['tas_priority_variable'] == "string") { + dataProperties.tas_priority_variable = dataDefinitions['tas_priority_variable']; + } + if (dataDefinitions['tas_derivation_screen_tpl'] || dataDefinitions['tas_derivation_screen_tpl'] == "") { + dataProperties.tas_derivation_screen_tpl = dataDefinitions['tas_derivation_screen_tpl']; + } + dataProperties.tas_def_title = dataCaseLabels['tas_def_title']; + dataProperties.tas_def_description = dataCaseLabels['tas_def_description']; + dataProperties.tas_transfer_fly = tas_transfer_fly ? 'TRUE' : 'FALSE'; + if (dataTimingControl['tas_duration']) { + dataProperties.tas_duration = dataTimingControl['tas_duration']; + } + if (dataTimingControl['tas_timeunit']) { + dataProperties.tas_timeunit = dataTimingControl['tas_timeunit']; + } + if (dataTimingControl['tas_type_day']) { + dataProperties.tas_type_day = dataTimingControl['tas_type_day']; + } + if (dataTimingControl['tas_calendar']) { + dataProperties.tas_calendar = dataTimingControl['tas_calendar']; + } + dataProperties.tas_send_last_email = tas_send_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_not_email_from_format']) { + dataProperties.tas_not_email_from_format = dataNotification['tas_not_email_from_format']; + } + if (dataNotification['tas_def_subject_message']) { + dataProperties.tas_def_subject_message = dataNotification['tas_def_subject_message']; + } + if (dataNotification['tas_def_message_type']) { + dataProperties.tas_def_message_type = dataNotification['tas_def_message_type']; + } + if (dataNotification['tas_def_message']) { + dataProperties.tas_def_message = dataNotification['tas_def_message']; + } + if (dataNotification['tas_def_message_template']) { + dataProperties.tas_def_message_template = dataNotification['tas_def_message_template']; + } + if (dataNotification['tas_email_server_uid'] !== 'undefined' && dataNotification['tas_email_server_uid'] !== null) { + dataProperties.tas_email_server_uid = dataNotification['tas_email_server_uid']; + } + + dataProperties.tas_receive_last_email = tas_receive_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_receive_email_from_format']) { + dataProperties.tas_receive_email_from_format = dataNotification['tas_receive_email_from_format']; + } + if (dataNotification['tas_receive_server_uid'] !== 'undefined' && dataNotification['tas_receive_server_uid'] !== null) { + dataProperties.tas_receive_server_uid = dataNotification['tas_receive_server_uid']; + } + if (dataNotification['tas_receive_subject_message']) { + dataProperties.tas_receive_subject_message = dataNotification['tas_receive_subject_message']; + } + if (dataNotification['tas_receive_message_type']) { + dataProperties.tas_receive_message_type = dataNotification['tas_receive_message_type']; + } + if (dataNotification['tas_receive_message']) { + dataProperties.tas_receive_message = dataNotification['tas_receive_message']; + } + if (dataNotification['tas_receive_message_template']) { + dataProperties.tas_receive_message_template = dataNotification['tas_receive_message_template']; + } + + if (consolidated == '1') { + consolidated_enable = false; + if (formConsolidated.getField('consolidated_enable').getValue() == '["1"]') { + consolidated_enable = true; + if (!formConsolidated.isValid()) { + return; + } + } + dataProperties.consolidate_data = { + "consolidated_enable": consolidated_enable, + "consolidated_dynaform": formConsolidated.getField('consolidated_dynaform').getValue(), + "consolidated_table": formConsolidated.getField('consolidated_table').getValue(), + "consolidated_title": formConsolidated.getField('consolidated_title').getValue(), + "consolidated_report_table": formConsolidated.getField('consolidated_report_table').getValue() + }; + } + + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: '', + data: { + definition: {}, + properties: dataProperties + }, + functionSuccess: function (xhr, response) { + setNameActivity(dataProperties.tas_title); + windowProperties.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Task properties saved successfully'.translate(), + flashContainer: document.body + })).executeRestClient(); + } + + function setFocusTab(tab) { + var style; + $customGrid = $("#customGrid"); + $customGrid.hide().appendTo($("#windowProperties").find(".pmui-window-body:eq(0)")); + + if (tab.getTitle() === 'Definitions'.translate()) { + formDefinitions.getField('tas_title').setFocus(); + } + if (tab.getTitle() === 'Case Labels'.translate()) { + formCaseLabels.getField('tas_def_title').setFocus(); + style = $('#formCaseLabelsDescription .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formCaseLabelsDescription .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Timing Control'.translate()) { + formTimingControl.getField('tas_duration').setFocus(); + } + if (tab.getTitle() === 'Notifications'.translate()) { + formNotifications.getField('tas_def_subject_message').setFocus(); + style = $('#formNotificationsMessage .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formNotificationsMessage .pmui-field-label').attr("style", style); + + style = $('#tas_receive_message .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#tas_receive_message .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Actions by Email'.translate()) { + abeForm.getField("ABE_TYPE").onChange(abeForm.getField("ABE_TYPE").getValue()); + } + } + + function isDirty() { + return formDefinitions.isDirty() || + formCaseLabels.isDirty() || + formTimingControl.isDirty() || + formNotifications.isDirty(); + } + + function setNameActivity(name) { + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + } + + windowProperties.open(); + windowProperties.showFooter(); + + applyStyleWindowForm(windowProperties); + if (consolidated == '1') { + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + function customDOM() { + $customGrid = $("#customGrid"); + $customGrid.show().appendTo($("#customGridPanel").find("fieldset:eq(0)")); + document.getElementById("customGridPanel").style.width = "720px"; + document.getElementById("customGridPanel").style.padding = ""; + document.getElementById("customGridPanel").getElementsByTagName("fieldset")[0].style.width = "100%"; + $(".pmui-gridpanel-footer").css({"text-align": "center", "margin-top": "10px", "width": "120%"}); + $(".pmui-gridpanel-footer").removeClass("pmui-gridpanel-footer"); + } + + function clearAddOptionForm() { + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + editRow = null; + }; + function addAcceptedValue() { + var abeValue = abeAddOption.getField("abe_custom_value_add").getValue(), + abeLabel = abeAddOption.getField("abe_custom_label_add").getValue(), + abeFormat = abeAddOption.getField("abe_custom_format_add").getValue(); + + if (abeAddOption && !abeAddOption.isValid()) { + return; + } + + if (!evaluateTags(abeFormat, 'validate')) { + return; + } + + if (editRow === null) { + customGrid.addItem(new PMUI.grid.GridPanelRow({ + data: { + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat + } + })); + } else { + editRow.setData({ + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat + }); + editRow = null; + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + } + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + } + + function customGridRowEdit(row) { + editRow = row; + row = row.getData(); + if (abeAddOption) { + abeAddOption.getField("abe_custom_value_add").setValue(row.abe_custom_value); + abeAddOption.getField("abe_custom_label_add").setValue(row.abe_custom_label); + abeAddOption.getField("abe_custom_format_add").setValue(row.abe_custom_format); + abeAddOption.getField("buttonFieldCancel").setVisible(true); + abeAddOption.getField("buttonFieldAdd").setValue("Save".translate()); + } + } + + function evaluateTags(html, action) { + var oldHtml; + var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*'; + var pattern = /^[a-zA-Z0-9\s\[\]\.\-_#%;,=:()']*$/; + var tagOrComment = new RegExp( + '<(?:' + // Comment body. + + '!--(?:(?:-*[^->])*--+|-?)' + // Special "raw text" elements whose content should be elided. + + '|script\\b' + tagBody + '>[\\s\\S]*?[\\s\\S]*?', + 'gi'); + + var action = (typeof action === 'undefined') ? 'delete' : 'validate'; + if (action == "validate") { + return pattern.test(html); + } else { + do { + oldHtml = html; + html = html.replace(tagOrComment, ''); + } while (html !== oldHtml); + return html.replace(/ -1) { + arrayObjectAdhocUser.splice(index, 1); + } + }, + onDrop: function (a, row) { + grid = this; + removeAD(row); + gridUserListAD.goToPage(gridUserListAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + assigmentPanelUserListAD = new PMUI.core.Panel({ + id: "assigmentPanelUserListAD", + layout: "vbox", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + }, + width: "60%" + }); + panelTitleUseListAD = new PMUI.core.Panel({ + id: "panelTitleUseListAD", + layout: "hbox" + }); + titleUserListAD = new PMUI.ui.TextLabel({ + id: "titleUserListAD", + textMode: 'plain', + text: 'Assigned users list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelGridUserListAD = new PMUI.core.Panel({ + id: "panelGridUserListAD", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] + } + }); + buttonsUserListAD = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUserListAD", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAs', + label: 'View all'.translate(), + value: 'all', + selected: true + }, { + id: 'buttonUsersAs', + label: 'View users'.translate(), + value: 'user' + }, { + id: 'buttonGroupsAs', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserListAD.typeList = "user"; + break; + case "group": + gridUserListAD.typeList = "group"; + break; + default: + gridUserListAD.typeList = ""; + break; + } + gridUserListAD.goToPage(0); + } + }); + gridUserListAD = new PMUI.grid.GridPanel({ + id: "gridUserListAD", + pageSize: pageSizeAssignmentAD - 1, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = "mafe-grid-panel-empty"; + div.style.height = gridUserListAD.dom.tableContainer.style.height; + div.style.width = gridUserListAD.dom.tableContainer.style.width; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserListAD.dom.tableContainer.style.overflow = "hidden"; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/adhoc-assignee/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].ada_type == "group") { + data[i]["assignee"] = data[i].ada_name; + } else { + data[i]["assignee"] = data[i].ada_name + " " + data[i].ada_lastname + " (" + data[i].ada_username + ")"; + } + } + return data; + }, + columns: [ + { + id: 'gridUserListADButtonLabel', + title: "", + width: "13%", + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem"; + if (row.getData()["ada_type"] === "group") { + var i, + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint("group/" + row.getData()["ada_uid"] + "/users?start=0&limit=11"); + restClient.executeRestClient(); + } + } + }, + { + title: '', + dataType: 'string', + columnData: "assignee", + alignmentCell: "left", + width: "330px" + }, + { + id: 'gridUserListADButtonDelete', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["ada_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUserListAD; + removeAD(row); + grid.goToPage(grid.currentPage); + gridUsersAD.goToPage(gridUsersAD.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (a, row) { + grid = this; + assigneeAD(row); + gridUsersAD.goToPage(gridUsersAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelContainerRules = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH - 55, + height: "auto", + fieldset: true, + items: [ + formAssignmentRules + ] + }); + panelContainerUsers = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobal + ] + }); + panelContainerUsersAdHoc = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobalAD + ] + }); + + tabPanelAssignmentRules = new PMUI.panel.TabPanel({ + id: 'tabPanelAssignmentRules', + width: "100%", + height: "auto", + items: [ + { + id: 'tabUsers', + title: 'Users'.translate(), + panel: panelContainerUsers + }, + { + id: 'tabUsersAdHoc', + title: 'Ad Hoc Users'.translate(), + panel: panelContainerUsersAdHoc + } + ], + onTabClick: function (item) { + quickMessageWindow.close(); + switch (item.id) { + case 'tabRules': + break; + case 'tabUsers': + applyStyles(); + gridUsers.goToPage(0); + gridUserList.goToPage(0); + break; + case 'tabUsersAdHoc': + applyStylesAD(); + gridUsersAD.goToPage(0); + gridUserListAD.goToPage(0); + break; + } + } + }); + windowAssignmentRules = new PMUI.ui.Window({ + id: 'windowAssignmentRules', + title: 'Assignment Rules'.translate() + ': ' + activity.act_name, + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerItems: [ + { + id: 'windowConnectionsButtonCancel', + text: 'Close'.translate(), + handler: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); + } + }, + buttonType: 'error' + }, + { + buttonType: 'success', + id: 'windowPropertiesButtonSave', + text: "Save".translate(), + handler: function () { + saveData(); + } + } + ], + visibleFooter: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); + } + } + }); + + loadTrigger = function (response) { + var field = formAssignmentRules.getField('tas_selfservice_trigger_uid'), i; + field.clearOptions(); + field.addOption({ + value: '', + label: '- Select Trigger -'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].tri_uid, + label: response[i].tri_title + }); + } + }; + loadFormData = function (response) { + dataProperties = response.properties; + formAssignmentRules.getField('tas_assign_type').setValue(dataProperties.tas_assign_type); + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + changeRadioButtons(formAssignmentRules.getField('tas_assign_type').getValue()); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + if (dataProperties.tas_selfservice_timeout === 1) { + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].select(); + } + formAssignmentRules.getField('tas_selfservice_time').setValue(dataProperties.tas_selfservice_time); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(dataProperties.tas_selfservice_time_unit); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(dataProperties.tas_selfservice_trigger_uid); + formAssignmentRules.getField('tas_selfservice_execution').setValue(dataProperties.tas_selfservice_execution); + visibleService(dataProperties.tas_selfservice_timeout === 1); + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadTrigger(response[1].response); + loadFormData(response[0].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadFreeUsers = function (response) { + var i; + gridUsers.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsers.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAssignmentUsers = function (response) { + var i; + gridUserList.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserList.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAdHocFreeUsers = function (response) { + var i; + gridUsersAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsersAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + loadAdHocAssignmentUsers = function (response) { + var i; + gridUserListAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserListAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + updateRules = function () { + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: ' ', + data: { + definition: {}, + properties: dataProperties + }, + messageSuccess: 'Assignment Rules saved successfully'.translate(), + flashContainer: document.body, + functionSuccess: function () { + formAssignmentRules.dirty = false; + windowAssignmentRules.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + }; + allHidden = function () { + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + formAssignmentRules.getField('tas_group_variable').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + formAssignmentRules.getField('tas_selfservice_time').setVisible(false); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(false); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(false); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(false); + }; + changeRadioButtons = function (newVal) { + allHidden(); + tabPanelAssignmentRules.setVisible(true); + switch (newVal) { + case 'EVALUATE': + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (dataProperties.tas_assign_variable === "" || dataProperties.tas_assign_variable === null) { + formAssignmentRules.getField('tas_assign_variable').setValue('@@SYS_NEXT_USER_TO_BE_ASSIGNED'); + } else { + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + } + break; + case 'SELF_SERVICE': + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'SELF_SERVICE_EVALUATE': + formAssignmentRules.getField('tas_group_variable').setVisible(true); + if (dataProperties.tas_group_variable === "@@SYS_GROUP_TO_BE_ASSIGNED" || dataProperties.tas_group_variable === "" || dataProperties.tas_group_variable === null) { + formAssignmentRules.getField('tas_group_variable').setPlaceholder('@@ARRAY_OF_USERS or @@GROUP_UID'); + } else { + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + } + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'REPORT_TO': + break; + case 'MULTIPLE_INSTANCE_VALUE_BASED': + formAssignmentRules.getField('tas_assign_variable').setLabel("Array of users".translate()); + if (formAssignmentRules.getField('tas_assign_variable').getValue() == "@@SYS_NEXT_USER_TO_BE_ASSIGNED" || formAssignmentRules.getField('tas_assign_variable').getValue() == "") { + formAssignmentRules.getField('tas_assign_variable').setValue(''); + formAssignmentRules.getField('tas_assign_variable').setPlaceholder('@@ARRAY_OF_USERS'); + } + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (activity.act_loop_type == "PARALLEL") { + tabPanelAssignmentRules.setVisible(false); + } + break; + default: + break; + } + }; + visibleService = function (value) { + var a = formAssignmentRules.getField('tas_assign_type').getValue(); + if (a === 'SELF_SERVICE' || a === 'SELF_SERVICE_EVALUATE') { + formAssignmentRules.getField('tas_selfservice_time').setVisible(value); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(value); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(value); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(value); + } + }; + hiddenTab = function (value) { + tabPanelAssignmentRules.showTab(2); + }; + saveData = function () { + var a, b, c, d, tas_selfservice_timeout, data; + tas_selfservice_timeout = formAssignmentRules.getField('tas_selfservice_timeout').getValue() === '["1"]'; + if (!tas_selfservice_timeout) { + //validation because getData method do not work in IE + if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { + data = getData2PMUI(formAssignmentRules.html); + b = data["tas_assign_variable"]; + } else { + b = formAssignmentRules.getField('tas_assign_variable').getValue(); + } + a = formAssignmentRules.getField('tas_assign_type').getValue(); + c = formAssignmentRules.getField('tas_group_variable').getValue(); + d = formAssignmentRules.getField('tas_group_variable').getValue(); + formAssignmentRules.getField('tas_assign_type').setValue(a); + formAssignmentRules.getField('tas_assign_variable').setValue(b); + formAssignmentRules.getField('tas_group_variable').setValue(c); + formAssignmentRules.getField('tas_selfservice_timeout').setValue(d); + formAssignmentRules.getField('tas_selfservice_time').setValue(''); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(''); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(''); + formAssignmentRules.getField('tas_selfservice_execution').setValue(''); + } else { + if (!formAssignmentRules.isValid()) { + return; + } + } + dataProperties.tas_assign_type = formAssignmentRules.getField('tas_assign_type').getValue(); + dataProperties.tas_assign_variable = formAssignmentRules.getField('tas_assign_variable').getValue() === '' ? '@@SYS_NEXT_USER_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_assign_variable').getValue(); + dataProperties.tas_group_variable = formAssignmentRules.getField('tas_group_variable').getValue() === '' ? '@@SYS_GROUP_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_group_variable').getValue(); + dataProperties.tas_selfservice_timeout = tas_selfservice_timeout ? 1 : 0; + dataProperties.tas_selfservice_time = formAssignmentRules.getField('tas_selfservice_time').getValue() !== "" ? parseInt(formAssignmentRules.getField('tas_selfservice_time').getValue(), 10) : 0; + dataProperties.tas_selfservice_time_unit = formAssignmentRules.getField('tas_selfservice_time_unit').getValue(); + dataProperties.tas_selfservice_trigger_uid = formAssignmentRules.getField('tas_selfservice_trigger_uid').getValue(); + dataProperties.tas_selfservice_execution = formAssignmentRules.getField('tas_selfservice_execution').getValue(); + updateRules(); + }; + saveOrUpdateUserAndAdHocUsers = function () { + //Assigne and Remove (users) + var i, b; + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); + } + } + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } + } + } + //Assigne and Remove (AdHocUsers) + if (gridUserListAD.getItems().length > 0) { + grid = gridUserListAD; + for (i = 0; i < arrayObjectAdhocUserList.length; i += 1) { + b = arrayObjectAdhocUserList[i]; + if (arrayObjectAdhocUserList2.indexOf(b) == -1) { + assigneeAD(b); + } + } + } + if (gridUsersAD.getItems().length > 0) { + for (i = 0; i < arrayObjectAdhocUser.length; i += 1) { + b = arrayObjectAdhocUser[i]; + if (arrayObjectAdhocUser2.indexOf(b) == -1) { + removeAD(arrayObjectAdhocUser[i]); + } + } + } + }; + applyStyles = function () { + gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + buttonsUsers.defineEvents(); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + buttonsUserList.defineEvents(); + gridUserList.dom.toolbar.style.height = "76px"; + buttonsUsers.dom.labelTextContainer.style.display = "none"; + buttonsUserList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + }; + applyStylesAD = function () { + gridUsersAD.dom.toolbar.appendChild(buttonsUsersAD.getHTML()); + buttonsUsersAD.defineEvents(); + gridUsersAD.dom.toolbar.style.height = "76px"; + + gridUserListAD.dom.toolbar.appendChild(buttonsUserListAD.getHTML()); + buttonsUserListAD.defineEvents(); + gridUserListAD.dom.toolbar.style.height = "76px"; + buttonsUsersAD.dom.labelTextContainer.style.display = "none"; + buttonsUserListAD.dom.labelTextContainer.style.display = "none"; + gridUsersAD.hideHeaders(); + gridUserListAD.hideHeaders(); + assigmentPanelUserListAD.setHeight('100%'); + gridUsersAD.filterControl.html.style.width = "300px"; + gridUserListAD.filterControl.html.style.width = "300px"; + }; + assignee = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/assignee"); + restClient.setData({aas_uid: row.getData()["aas_uid"], aas_type: row.getData()["aas_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + remove = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/assignee/" + row.getData().aas_uid); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + assigneeAD = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee"); + restClient.setData({ada_uid: row.getData()["ada_uid"], ada_type: row.getData()["ada_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + removeAD = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee/" + row.getData()["ada_uid"]); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().ass_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('fullName', 'asc'); + }; + + function onchangeRadio(grid, fieldName) { + var radioButTrat = document.getElementsByName(fieldName), i; + for (i = 0; i < radioButTrat.length; i += 1) { + if (radioButTrat[i].checked == true) { + quickMessageWindow.close(); + groupRows(grid, radioButTrat[i].value); + } + } + } + + function domSettings() { + if (activity.act_loop_type == "PARALLEL") { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().show(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE_VALUE_BASED"); + } else { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE"); + } + } else { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().hide(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("BALANCED"); + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + } + } + }; + + panelTitleUser.addItem(titleUser); + panelGridUser.addItem(gridUsers); + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelGridUser); + assigmentPanelGlobal.addItem(assigmentPanelUser); + panelTitleUserList.addItem(titleUserList); + panelGridUserList.addItem(gridUserList); + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelGridUserList); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + + panelTitleUserAD.addItem(titleUserAD); + panelSearchUserAD.addItem(searchGridUserAD); + panelGridUserAD.addItem(gridUsersAD); + assigmentPanelUserAD.addItem(panelTitleUserAD); + assigmentPanelUserAD.addItem(panelGridUserAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserAD); + panelTitleUseListAD.addItem(titleUserListAD); + panelGridUserListAD.addItem(gridUserListAD); + assigmentPanelUserListAD.addItem(panelTitleUseListAD); + assigmentPanelUserListAD.addItem(panelGridUserListAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserListAD); + + if (formAssignmentRules.dirty == null) { + formAssignmentRules.dirty = false; + } + windowAssignmentRules.addItem(formAssignmentRules); + windowAssignmentRules.addItem(tabPanelAssignmentRules); + windowAssignmentRules.open(); + applyStyleWindowForm(windowAssignmentRules); + windowAssignmentRules.body.style.overflowY = 'auto'; + windowAssignmentRules.body.style.overflowX = 'hidden'; + windowAssignmentRules.defineEvents(); + buttonsUsers.defineEvents(); + tabPanelAssignmentRules.itemClick(0); + loadServerData(); + domSettings(); + //array for Users + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + //array for AdHocUsers + usersgrid = gridUsersAD; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectAdhocUser2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserListAD; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectAdhocUserList2[i] = userslist.getItems()[i]; + } + formAssignmentRules.html.style.marginLeft = '30px'; + formAssignmentRulesSetTimeoutOption; + document.getElementById("formAssignmentRulesSetTimeoutOption").childNodes[0].onchange = function () { + visibleService(this.checked); + }; + $(".pmui-field-control-table").css("border", "0px"); + $(".pmui-field-label").css("padding", "0px"); + $(".mafe-designer-assigment-title").css("margin-top", "25px"); + $("#formTasAssignType").append("
"); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + buttonsUserList, + gridUserList, + applyStyles, + loadServerData, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + quickMessageWindow = new QuickMessageWindow(); + + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Assign Users and Groups as Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true + }); + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: 'There are problems, please try again.'.translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + assigmentPanelUser = new PMUI.core.Panel({ + layout: "vbox", + width: "49%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + } + }); + assigmentPanelUserList = new PMUI.core.Panel({ + layout: "vbox", + width: "50%", + style: { + cssClasses: [ + 'mafe-panel-assignment-smooth' + ] + } + }); + assigmentPanelGlobal = new PMUI.core.Panel({ + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH, + style: { + cssClasses: [ + 'mafe-assigment-panel-global' + ] + } + }); + + panelTitleUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUser = new PMUI.ui.TextLabel({ + id: 'titleUser', + label: ' ', + textMode: 'plain', + text: 'Available Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUser = new PMUI.field.TextField({ + id: 'searchGridUser', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); + buttonsUsers = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUsers', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + selected: true, + value: 'all', + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + ], + listeners: { + select: function (item, event) { + groupRows(gridUsers, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUsers = new PMUI.grid.GridPanel({ + id: 'gridUsers', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: '10%', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + var stringUsers = '', i; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'sup_name', + alignmentCell: 'left', + width: '80%' + }, { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: '19%', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Assign'.translate(); + }, + onButtonClick: function (row, grid) { + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(row); + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); + assignee(row); + } + } + ], + onDropOut: function (item, origin, destiny) { + assignee(item); + }, + onDrop: function (a, row) { + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelTitleUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUserList = new PMUI.ui.TextLabel({ + id: 'titleUserList', + textMode: 'plain', + text: 'Assigned Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + buttonsUserList = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUserList', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + value: 'all', + selected: true, + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + + ], + listeners: { + select: function (item, event) { + groupRows(gridUserList, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUserList = new PMUI.grid.GridPanel({ + id: 'gridUserList', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + filterable: true, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = 'mafe-grid-panel-empty'; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserList.dom.tableContainer.style.overflow = 'hidden'; + }, + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var stringUsers, i; + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + stringUsers = ''; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'sup_name', + width: '80%', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Remove'.translate(); + }, + onButtonClick: function (row, grid) { + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUsers.addItem(row); + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); + remove(row); + } + } + ], + onDropOut: function (item, origin, destiny) { + remove(item); + }, + onDrop: function (a, row) { + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + applyStyles = function () { + gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + buttonsUsers.dom.labelTextContainer.style.display = "none"; + buttonsUserList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/available-process-supervisors', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/process-supervisors', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadUsers(response[0].response); + loadUsersList(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); + } + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); + } + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.data.customKeys.sup_uid, + pu_type: row.data.customKeys.obj_type === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.data.customKeys.pu_uid, + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflow = "hidden"; + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); + + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); + + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(buttonsUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(buttonsUserList); + assigmentPanelUserList.addItem(panelGridUserList); + + assigmentWindow.defineEvents(); + applyStyles(); + + loadServerData(); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + flagEdit = 0, + i, + index = 0, + quickMessageWindow = new QuickMessageWindow(), + arrayObjectUserList = new Array(), + arrayObjectUsers = new Array(), + arrayObjectUserList2 = new Array(), + arrayObjectUsers2 = new Array(), + arrayDynaformInputDocumentID = new Array(), + arrayDynaformInputDocumentObject = new Array(), + arrayObjectRemovedSteps = new Array(), + message_window, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + radioUsersList, + buttonsUserList, + gridUserList, + radioUsers, + applyStylesRadioButtonGroupField, + applyStylesForToolbar, + applyStyles, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + loadGridCaseTacker, + orderDataTree, + titleTreeObjects, + titleGridObjects, + panelLabelObjects, + panelObjects, + treePanelObjects, + updateItem, + usersgrid, + saveItemDyanformInputDocuments, + getValuesAssignmentSteps, + gridPanelObjects, + panelContainerObjects, + userslist, + gridpanelobj, + flashMessage = new PMUI.ui.FlashMessage({ + message: '', + appendTo: document.body, + duration: 1000, + severity: "success" + }); + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + onBeforeClose: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } + }, + footerItems: [ + { + text: "Cancel", + handler: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } + }, + buttonType: 'error' + }, + { + text: 'Save', + handler: function () { + var i, j, idObject, objType, baseEndPointID; + if (flagEdit != 0) { + //save Configuration Supervisors and Steps(Dyanform - Inputs Documents) + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + grid.removeItem(b); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(b); + radioUsersList.setValue(radioUsers.getValue()); + groupRows(gridUserList, radioUsers.getValue()); + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); + } + } + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } + } + } + + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayDynaformInputDocumentID.indexOf(idObject); + if (index <= -1) { + saveItemDyanformInputDocuments(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); + } + } + + for (i = 0; i < arrayObjectRemovedSteps.length; i += 1) { + for (j = 0; j < arrayDynaformInputDocumentObject.length; j += 1) { + index = (arrayObjectRemovedSteps[i] == arrayDynaformInputDocumentObject[j].obj_uid) ? 0 : 1; + if (index == 0) { + objType = arrayDynaformInputDocumentObject[j].obj_type.toLowerCase(); + baseEndPointID = (objType === "dynaform") ? arrayDynaformInputDocumentObject[j].pud_uid : arrayDynaformInputDocumentObject[j].pui_uid; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + '/' + baseEndPointID, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } + } + } + assigmentWindow.close(); + } + else { + assigmentWindow.close(); + } + }, + buttonType: "success" + } + ], + visibleFooter: true, + buttonPanelPosition: "bottom", + footerAlign: "right" + }); + + message_window = new PMUI.ui.MessageWindow({ + id: "messageWindowCancel", + width: 490, + title: "Supervisors".translate(), + windowMessageType: "warning", + bodyHeight: "auto", + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: "messageWindowNo", + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: "messageWindowYes", + text: "Yes".translate(), + handler: function () { + message_window.close(); + assigmentWindow.close(); + }, + buttonType: "success" + } + ] + }); + + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: 'There are problems, please try again.'.translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + assigmentPanelUser = new PMUI.core.Panel({ + layout: "vbox", + width: "49%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + } + }); + assigmentPanelUserList = new PMUI.core.Panel({ + layout: "vbox", + width: "50%", + style: { + cssClasses: [ + 'mafe-panel-assignment-smooth' + ] + } + }); + assigmentPanelGlobal = new PMUI.core.Panel({ + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH, + style: { + cssClasses: [ + 'mafe-assigment-panel-global' + ] + } + }); + + panelTitleUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUser = new PMUI.ui.TextLabel({ + id: 'titleUser', + label: ' ', + textMode: 'plain', + text: 'Available Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUser = new PMUI.field.TextField({ + id: 'searchGridUser', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); + buttonsUsers = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUsers', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + selected: true, + value: 'all', + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + ], + listeners: { + select: function (item, event) { + groupRows(gridUsers, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUsers = new PMUI.grid.GridPanel({ + id: 'gridUsers', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/available-process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].obj_type == "group") { + data[i].available = data[i].grp_name; + } else { + data[i].available = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + } + } + return data; + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: '10%', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["obj_type"] === 'group') { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'available', + alignmentCell: 'left', + width: '330px' + }, { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: '19%', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit-assign' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["obj_type"] === 'user' ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + assignee(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (a, row) { + grid = this; + remove(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelTitleUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUserList = new PMUI.ui.TextLabel({ + id: 'titleUserList', + textMode: 'plain', + text: 'Assigned supervisors list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + radioUsersList = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsersList', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + label: "View all".translate(), + value: "all" + }, + { + label: "View users".translate(), + value: "user" + }, + { + label: "View groups".translate(), + value: "group" + } + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserList.typeList = "user".translate(); + break; + case "group": + gridUserList.typeList = "group".translate(); + break; + default: + gridUserList.typeList = ""; + break; + } + gridUserList.goToPage(0); + }, + required: true, + value: "all" + }); + buttonsUserList = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUserList', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + value: 'all', + selected: true, + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + + ], + listeners: { + select: function (item, event) { + groupRows(gridUserList, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUserList = new PMUI.grid.GridPanel({ + id: 'gridUserList', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + filterable: true, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = 'mafe-grid-panel-empty'; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserList.dom.tableContainer.style.overflow = 'hidden'; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].pu_type == "GROUP_SUPERVISOR") { + data[i].assignee = data[i].grp_name; + } else { + data[i].assignee = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + } + } + return data; + }, + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["pu_type"] === "GROUP_SUPERVISOR") { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'assignee', + width: '330px', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["pu_type"] === "SUPERVISOR" ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + remove(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (grid, row) { + var dataRow = {}; + grid = this; + assignee(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + radioUsers = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsers', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + label: "View all".translate(), + value: "all" + }, + { + label: "View users".translate(), + value: "user" + }, + { + label: "View groups".translate(), + value: "group" + } + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUsers.typeList = "user"; + break; + case "group": + gridUsers.typeList = "group"; + break; + default: + gridUsers.typeList = ""; + break; + } + gridUsers.goToPage(0); + }, + required: true, + value: "all", + style: { + cssProperties: { + 'margin-top': '15px' + } + } + }); + applyStylesRadioButtonGroupField = function () { + $('#idRadioUsers .pmui-field-control-table').css("border", "none"); + $('#idRadioUsers').css("margin-top", "12px"); + radioUsers.defineEvents(); + + $('#idRadioUsersList .pmui-field-control-table').css("border", "none"); + $('#idRadioUsersList').css("margin-top", "12px"); + radioUsersList.defineEvents(); + }; + + applyStylesForToolbar = function () { + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('#assigmentUserWindow')[0].childNodes[1].childNodes[0].childNodes[1].style.backgroundColor = "white"; + $('#gridUserList')[0].style.backgroundColor = "white"; + $('#gridUserList').css("width", "452px"); + $('#gridUsers').css({"width": "452px", "height": "175px"}); + $('.pmui-window-body .pmui-panel:eq(9)').css({ + 'width': '1000px', + 'border-top': '1px solid #cdd2d5', + 'margin-top': '36px', + 'height': '80px' + }); + }; + + applyStyles = function () { + applyStylesRadioButtonGroupField(); + gridUsers.dom.toolbar.appendChild(radioUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(radioUsersList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + radioUsers.dom.labelTextContainer.style.display = "none"; + radioUsersList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderRight = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[1].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.paddingLeft = "10px"; + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': '245px'}); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); + } + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); + } + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.getData()["obj_type"] == "group" ? row.getData()["grp_uid"] : row.getData()["usr_uid"], + pu_type: row.getData()["obj_type"] === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.getData()["pu_uid"], + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + //steps Dynaforms and InputDocuments + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ], + cssProperties: { + 'left': 40 + } + } + }); + + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 2, + 'margin-left': 50 + } + }, + layout: "hbox" + }); + + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 30, + fieldset: true, + items: [ + panelLabelObjects + ], + layout: "vbox" + }); + + //Objects + orderDataTree = function (data) { + var items = [], i, + type = ['DYNAFORM', 'INPUT-DOCUMENT'], + label = ['Dynaform', 'Input Document']; + for (i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + if (data[j].obj_type == "DYNAFORM") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['dyn_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + dyn_uid: data[j]['dyn_uid'] + }); + } else { + if (data[j].obj_type == "INPUT-DOCUMENT") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['inp_doc_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + obj_uid: data[j]['obj_uid'], + inp_uid: data[j]['inp_doc_uid'] + }); + } + } + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [{obj_title: 'N/A'.translate(), obj_uid: ''}] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items + }); + } + } + }; + + loadGridCaseTacker = function (data) { + var dataOrder = new Array(), i, j; + for (i = 0; i < data.length; i += 1) { + for (j = 0; j < data.length; j += 1) { + positionIndex = (data[j]['obj_type'] == 'DYNAFORM') ? data[j].pud_position : data[j].pui_position; + if (positionIndex == (i + 1)) { + dataOrder.push(data[j]); + switch (dataOrder[i]['obj_type']) { + case 'DYNAFORM': + label = dataOrder[i]['dyn_title'].translate(); + break; + case 'INPUT-DOCUMENT': + label = dataOrder[i]['input_doc_title'].translate(); + break; + default: + break; + } + dataOrder[i]['obj_title'] = label; + break; + } + } + } + gridPanelObjects.setDataItems(dataOrder); + }; + + getValuesAssignmentSteps = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "process-supervisor/available-assignmentsteps", + "method": 'GET' + }, + { + "url": "process-supervisor/assignmentsteps", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Text to search'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true + } + }); + + //Save Item (Drop) + saveItemDyanformInputDocuments = function (rowStep) { + rowStep = rowStep.getData(); + if (rowStep.obj_type === "DYNAFORM") { + data = { + "dyn_uid": rowStep.obj_uid, + "pud_position": rowStep.obj_position + }; + } else { + data = { + "inp_doc_uid": rowStep.obj_uid, + "pui_position": rowStep.obj_position + }; + } + + restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + rowStep.obj_type.toLowerCase(), + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + return data; + }; + + //Update SORT tree + updateItem = function (rowStep, i) { + var objType, + baseEndPointType, + baseEndPointID; + rowStep = rowStep.getData(); + rowStep.obj_position = i + 1; + objType = rowStep.obj_type.toLowerCase(), + baseEndPointType = (objType === "dynaform") ? 'dynaforms' : 'input-documents'; + baseEndPointID = (objType === "dynaform") ? rowStep.pud_uid : rowStep.pui_uid; + if (objType === "dynaform") { + rowStep.pud_position = rowStep.obj_position; + } else { + rowStep.pui_position = rowStep.obj_position; + } + + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + "/" + baseEndPointID, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + }; + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + style: { + cssClasses: ['itemsSteps'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_type", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + var rowStep, treePanelItems; + flagEdit = 1; + index = arrayDynaformInputDocumentID.indexOf(row.getData().obj_uid); + rowStep = row.getData(); + treePanelItems = treePanelObjects.getItems(); + + if (index > -1) { + arrayObjectRemovedSteps.push(row.getData().obj_uid); + arrayDynaformInputDocumentID.splice(index, 1); + } + function removeRowClass(treeNode) { + var childNodeEl = $(treeNode.html).find('.pmui-gridpanelrow'); + childNodeEl.removeClass('pmui-gridpanelrow'); + } + + function removeEmptyNode(indexNode) { + var parentNode = treePanelItems[indexNode]; + if (parentNode.getItems().length == 1 && + parentNode.getItems()[0].getData()['obj_uid'] == "") { + parentNode.removeItem(0); + } + parentNode.addItem(row); + removeRowClass(parentNode); + } + + if (rowStep.obj_type === "DYNAFORM") { + removeEmptyNode(0); + } else { + removeEmptyNode(1); + } + grid.removeItem(row); + } + } + ], + onDrop: function (grid, item, index) { + var parentItems; + if (item.getData()['obj_uid'] == "") { + return false; + + } + parentItems = item.parent.getItems(); + if (parentItems.length == 1 && item.getData()['obj_uid'] != "") { + item.parent.addDataItem( + {obj_title: 'N/A'.translate(), obj_uid: ''} + ); + item.parent.behaviorObject.draggedObject = item; + } + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + item.setData(rowStep); + index = arrayObjectRemovedSteps.indexOf(item.getData().obj_uid); + + if (index > -1) { + arrayDynaformInputDocumentID.push(item.getData().obj_uid); + arrayObjectRemovedSteps.splice(index, 1); + } + }, + onSort: function (grid, item, index) { + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + } + }); + + //principal Container Steps + panelContainerObjects = new PMUI.core.Panel({ + id: "panelContainerObjects", + width: DEFAULT_WINDOW_WIDTH, + height: 250, + fieldset: true, + items: [treePanelObjects, gridPanelObjects], + layout: "hbox", + style: { + cssProperties: { + 'margin-top': '-40px' + } + } + }); + + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflowX = "hidden"; + + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); + + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); + + assigmentWindow.addItem(panelObjects); + assigmentWindow.addItem(panelContainerObjects); + getValuesAssignmentSteps(); + + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(630); + gridPanelObjects.setHeight(250); + $('#gridPanelObjects').css("margin-right", "32px"); + $('#treePanelObjects').css("margin-left", "10px"); + + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(radioUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(radioUsersList); + assigmentPanelUserList.addItem(panelGridUserList); + gridUsers.dom.tableContainer.style.height = "245px"; + gridUserList.dom.tableContainer.style.height = "245px"; + gridUsers.goToPage(0); + gridUserList.goToPage(0); + assigmentWindow.defineEvents(); + applyStyles(); + treePanelObjects.style.addProperties({overflow: 'auto'}); + + applyStylesForToolbar(); + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + gridpanelobj = gridPanelObjects; + for (i = 0; i < gridpanelobj.getItems().length; i += 1) { + arrayDynaformInputDocumentID[i] = gridpanelobj.getItems()[i].getData().obj_uid; + arrayDynaformInputDocumentObject[i] = gridpanelobj.getItems()[i].getData(); + } + }; +}()); +( + function () { + PMDesigner.propertiesProcess = function () { + var responseProperties = null, + getValuesProperties, + isDirtyFormProcess, + saveProperties, + propertiesWindow, + processUID, + textTitle, + textDescription, + processOwner, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + loadProperties, + proUnitCost, + formEditProcess, + loadDynaforms, + loadCalendar, + loadTemplate, + loadTriggers, + loadTypeProcess, + loadCategory, + notification, + notificationText = "Fields marked with an asterisk (%%ASTERISK%%) are required.".translate() + .replace(/%%ASTERISK%%/g, '*'), + clickedClose; + + getValuesProperties = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "project/" + PMDesigner.project.id + "/dynaforms", + "method": 'GET' + }, + { + "url": "calendars", + "method": 'GET' + }, + { + "url": "project/categories", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/file-manager?path=templates", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/triggers", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/process", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadDynaforms(response[0].response); + loadCalendar(response[1].response); + loadCategory(response[2].response); + loadTemplate(response[3].response); + loadTriggers(response[4].response); + loadTypeProcess(response[5].response); + loadProperties(response[5].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + isDirtyFormProcess = function () { + var message_window + if (formEditProcess.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Edit process".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + propertiesWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + propertiesWindow.close(); + } + }; + saveProperties = function (data) { + var restClient = new PMRestClient({ + typeRequest: 'update', + data: data, + messageSuccess: "Properties saved successfully".translate(), + functionSuccess: function (xhr, response) { + propertiesWindow.close(); + + PMDesigner.project.setProjectName(data.pro_title); + PMDesigner.project.setDescription(data.pro_description); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + PMDesigner.project.dirty = false; + } + }); + restClient.setEndpoint("process"); + restClient.executeRestClient(); + }; + + propertiesWindow = new PMUI.ui.Window({ + id: "propertiesProcessWindow", + title: "Edit process".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: "auto", + modal: true, + buttonPanelPosition: "bottom", + footerAlign: "right", + onBeforeClose: function () { + clickClose = true; + isDirtyFormProcess(); + }, + buttons: [ + { + id: 'outputWindowDocButtonCancel', + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + clickedClose = false; + isDirtyFormProcess(); + } + }, + { + id: 'outputWindowDocButtonSave', + text: "Save".translate(), + buttonType: "success", + handler: function () { + var dataForm; + if (formEditProcess.isValid() && processOwner.isValid()) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataForm = getData2PMUI(formEditProcess.html); + } else { + dataForm = formEditProcess.getData(); + dataForm.pro_process_owner = processOwner.get("value"); + } + dataForm.pro_debug = checkDebug.controls[0].selected ? 1 : 0; + dataForm.pro_show_message = checkHideCase.controls[0].selected ? 1 : 0; + dataForm.pro_subprocess = checkSubProcess.controls[0].selected ? 1 : 0; + functionAssignmentUsers = function (xhr, response) { + }; + saveProperties(dataForm); + } else { + if (!(processOwner.isValid()) && formEditProcess.isValid()) { + formEditProcess.addItem(notification); + } else { + formEditProcess.removeItem(notification); + } + } + } + } + ] + }); + + processUID = new PMUI.field.TextField({ + label: "UID".translate(), + id: "process_uid", + name: "pro_uid", + labelWidth: "35%", + controlsWidth: "300px" + }); + + textTitle = new PMUI.field.TextField({ + label: "Title".translate(), + id: 'textTitle', + name: 'pro_title', + labelWidth: "35%", + placeholder: 'a text here'.translate(), + controlsWidth: "300px", + required: true + }); + + textDescription = new PMUI.field.TextAreaField({ + id: 'textDescription', + name: 'pro_description', + label: "Description".translate(), + labelWidth: "35%", + controlsWidth: "500px", + rows: 150, + style: {cssClasses: ['mafe-textarea-resize']} + }); + + processOwner = new SuggestField({ + id: 'processOwner', + name: 'pro_owner', + label: "Process Owner".translate(), + required: true, + width: 500, + placeholder: "suggest users".translate(), + separatingText: ["Users".translate()], + dynamicLoad: { + data: [ + { + key: "usr_uid", + label: ["usr_firstname", "usr_lastname", "(", "usr_username", ")"] + } + ], + keys: { + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endpoints: [ + { + method: "GET", + url: 'users' + } + ] + } + } + }); + + dropCalendar = new PMUI.field.DropDownListField({ + id: "dropCalendar", + name: "pro_calendar", + labelWidth: "35%", + label: "Calendar".translate(), + controlsWidth: "300px", + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropProcessCat = new PMUI.field.DropDownListField({ + id: "dropProcessCat", + name: "pro_category", + controlsWidth: "300px", + labelWidth: "35%", + label: "Process Category".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropDynaform = new PMUI.field.DropDownListField({ + id: "dropDynaform", + name: "pro_summary_dynaform", + controlsWidth: "300px", + labelWidth: "35%", + label: "Dynaform to show a case summary".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropRouting = new PMUI.field.DropDownListField({ + id: "dropRouting", + name: "pro_derivation_screen_tpl", + controlsWidth: "300px", + labelWidth: "35%", + label: "Routing Screen Template".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + checkDebug = new PMUI.field.CheckBoxGroupField({ + id: 'checkDebug', + labelWidth: "35%", + label: "Debug".translate(), + name: "pro_debug", + value: '1', + controlPositioning: 'vertical', + options: [ + { + id: 'pro_debug', + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + + checkHideCase = new PMUI.field.CheckBoxGroupField({ + id: 'checkHideCase', + labelWidth: "35%", + label: "Hide the case number and the case title in the steps".translate(), + value: '1', + name: "pro_show_message", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + + checkSubProcess = new PMUI.field.CheckBoxGroupField({ + id: 'checkSubProcess', + labelWidth: "35%", + label: "This a sub-process".translate(), + value: '1', + name: "pro_subprocess", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + dropCaseCreated = new PMUI.field.DropDownListField({ + id: "dropCaseCreated", + name: "pro_tri_create", + labelWidth: "35%", + label: "Execute a trigger when a case is created".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseDeleted = new PMUI.field.DropDownListField({ + id: "dropCaseDeleted", + name: "pro_tri_deleted", + labelWidth: "35%", + label: "Execute a trigger when a case is deleted".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseCancelled = new PMUI.field.DropDownListField({ + id: "dropCaseCancelled", + name: "pro_tri_canceled", + labelWidth: "35%", + label: "Execute a trigger when a case is cancelled".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCasePaused = new PMUI.field.DropDownListField({ + id: "dropCasePaused", + name: "pro_tri_paused", + labelWidth: "35%", + label: "Execute a trigger when a case is paused".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseUnpaused = new PMUI.field.DropDownListField({ + id: "dropCaseUnpaused", + name: "pro_tri_unpaused", + labelWidth: "35%", + label: "Execute a trigger when a case is unpaused".translate(), + valueType: "string", + controlsWidth: "300px" + }); + + dropCaseReassigned = new PMUI.field.DropDownListField({ + id: "dropCaseReassigned", + name: "pro_tri_reassigned", + labelWidth: "35%", + label: "Execute a trigger when a case is reassigned".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseOpen = new PMUI.field.DropDownListField({ + id: "dropCaseOpen", + name: "pro_tri_open", + label: "Execute a trigger when a case is opened".translate(), + labelWidth: "35%", + valueType: "string", + controlsWidth: "300px", + + onChange: function (newValue, prevValue) { + } + }); + + dropTypeProcess = new PMUI.field.DropDownListField({ + id: "dropTypeProcess", + name: "pro_type_process", + labelWidth: "35%", + label: "Process Design Access: Public / Private (Owner)".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + proCost = new PMUI.field.TextField({ + id: 'proCost', + name: 'pro_cost', + labelWidth: "35%", + value: 0, + placeholder: 'a cost here'.translate(), + label: "Cost".translate(), + valueType: 'integer', + controlsWidth: "300px", + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" + } + } + }); + + proUnitCost = new PMUI.field.TextField({ + id: 'proUnitCost', + name: 'pro_unit_cost', + labelWidth: "35%", + value: '$', + placeholder: 'a unit cost here'.translate(), + controlsWidth: "300px", + label: "Units".translate(), + valueType: 'string', + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" + } + } + }); + + notification = new PMUI.field.TextAnnotationField({ + id: "requiredMessage", + name: "Message", + textType: PMUI.field.TextAnnotationField.TEXT_TYPES.HTML, + text: notificationText, + text_Align: "center" + }); + + formEditProcess = new PMUI.form.Form({ + id: 'formEditProcess', + fieldset: true, + title: "Process Information".translate(), + width: DEFAULT_WINDOW_WIDTH - DEFAULT_WINDOW_WIDTH * 0.10, + items: [ + processUID, + textTitle, + textDescription, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + proUnitCost + ] + }); + + //Load Dynaforms + loadDynaforms = function (response) { + var i; + dropDynaform.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropDynaform.addOption({ + label: response[i].dyn_title, + value: response[i].dyn_uid, + select: false + }); + } + }; + + //Load calendar + loadCalendar = function (response) { + var i; + dropCalendar.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropCalendar.addOption({ + label: response[i].cal_name, + value: response[i].cal_uid, + select: false + }); + } + }; + + //Load category + loadCategory = function (response) { + var i; + dropProcessCat.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropProcessCat.addOption({ + label: response[i].cat_name, + value: response[i].cat_uid, + select: false + }); + } + }; + + //Load Templates + loadTemplate = function (response) { + var i; + dropRouting.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + if (response[i].prf_filename != "alert_message.html") { + dropRouting.addOption({ + label: response[i].prf_filename, + value: response[i].prf_filename, + select: false + }); + } + } + }; + + //Load triggers + loadTriggers = function (response) { + var i; + dropCaseCreated.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseDeleted.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseCancelled.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCasePaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseUnpaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseReassigned.addOption({ + label: "None".translate(), + value: "", + select: false + }); + + dropCaseOpen.addOption({ + label: "None".translate(), + value: "", + select: false + }); + + for (i = 0; i < response.length; i += 1) { + dropCaseCreated.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseDeleted.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseCancelled.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCasePaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseUnpaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseReassigned.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + + dropCaseOpen.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + } + }; + + // Load type of process + loadTypeProcess = function (response) { + dropTypeProcess.addOption({ + label: "Public".translate(), + value: "PUBLIC", + select: false + }); + dropTypeProcess.addOption({ + label: "Private".translate(), + value: "PRIVATE", + select: false + }); + }; + + // Load properties of process + loadProperties = function (response) { + propertiesWindow.addItem(formEditProcess); + propertiesWindow.open(); + $(processOwner.createHTML()).insertBefore(dropCalendar.html); + processOwner.html.find("input").blur(function () { + if (!(processOwner.isValid())) { + processOwner.showMessageRequiredExtended(); + } else { + processOwner.repaint("1px solid #adafb2", "2px", "", "1px solid white"); + } + }); + processOwner.html.find("input").focusin(function () { + if (processOwner.isValid()) { + processOwner.repaint("1px solid #adafb2", "2px", "#000", "-webkit-focus-ring-color auto 1px"); + } + }); + processOwner.containerLabel.css({ width: "35%" }); + processOwner.repaint("1px solid #adafb2", "2px", "", ""); + formEditProcess.getField("pro_type_process").hideColon(); + formEditProcess.reset(); + responseProperties = response; + processUID.setValue(response.pro_uid); + processUID.setReadOnly(true); + textTitle.setValue(response.pro_title); + textDescription.setValue(response.pro_description); + processOwner.set("value", response.pro_create_user); + processOwner.html.find("input").val(response.pro_create_firstname + " " + response.pro_create_lastname + " " + "(" + response.pro_create_username + ")"); + dropDynaform.setValue(response.pro_summary_dynaform); + dropCaseCancelled.setValue(response.pro_tri_canceled); + dropCaseCreated.setValue(response.pro_tri_create); + dropCaseDeleted.setValue(response.pro_tri_deleted); + dropCasePaused.setValue(response.pro_tri_paused); + dropCaseUnpaused.setValue(response.pro_tri_unpaused); + dropCaseReassigned.setValue(response.pro_tri_reassigned); + dropCaseOpen.setValue(response.pro_tri_open); + dropRouting.setValue(response.pro_derivation_screen_tpl); + dropCalendar.setValue(response.pro_calendar); + dropProcessCat.setValue(response.pro_category); + dropTypeProcess.setValue(response.pro_type_process); + checkHideCase.setHeight(57) + if (response.pro_debug == 1) { + checkDebug.getControls()[0].select(); + } + if (response.pro_show_message == 1) { + checkHideCase.getControls()[0].select(); + } + if (response.pro_subprocess == 1) { + checkSubProcess.getControls()[0].select(); + } + proCost.setValue(response.pro_cost); + if (response.pro_unit_cost != null && response.pro_unit_cost != '') { + proUnitCost.setValue(response.pro_unit_cost); + } + }; + + getValuesProperties(); + + propertiesWindow.showFooter(); + propertiesWindow.defineEvents(); + applyStyleWindowForm(propertiesWindow); + formEditProcess.getField('pro_title').setFocus(); + formEditProcess.getField("pro_type_process").html.style.float = "left"; + + dropCaseCancelled.style.addProperties({"float": "left"}); + dropCasePaused.style.addProperties({"float": "left"}); + dropCaseUnpaused.style.addProperties({"float": "left"}); + dropCaseReassigned.style.addProperties({"float": "left"}); + dropCaseOpen.style.addProperties({"float": "left"}); + + $("#dropCaseCancelled,#dropCasePaused,#dropCaseReassigned,#dropTypeProcess,#dropCaseOpen").find("select:eq(0)").css("z-index", 1); + + if (window.enterprise === "1") { + proCost.setVisible(true); + proUnitCost.setVisible(true); + } else { + proCost.setVisible(false); + proUnitCost.setVisible(false); + } + }; + + }() +); +(function () { + PMDesigner.caseTracker = function () { + var caseTrackerForm, + index, + flagEdit = 0, + caseTrackerWindow, + dataCaseTracker, + dataTree, + conditionform, + conditionWindows, + disableAllItems, + formIsDirty, + conditionformIsDirty, + orderDataTree, + saveItem, + updateItem, + treePanelObjects, + loadGridCaseTacker, + editCondition, + gridPanelObjects, + titleTreeObjects, + getValuesCaseTrackerObjects, + updateCaseTrackerPropertiesAndObjects, + loadPropertiesCaseTracker, + titleGridObjects, + panelLabelObjects, + panelContainerObjects, + panelObjects, + applyStylesWindow, + showObjects, + arrayObjectDropAssignedObjects = new Array(), + arrayObjectAvailableObjects = new Array(), + arrayObjectStepsCaseTracker = new Array(); + + disableAllItems = function () { + caseTrackerWindow.getItems()[0].setVisible(false); + caseTrackerWindow.getItems()[1].setVisible(false); + caseTrackerWindow.hideFooter(); + }; + formIsDirty = function () { + if (caseTrackerForm.isDirty() || flagEdit == 1) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + caseTrackerWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + caseTrackerWindow.close(); + } + }; + + conditionformIsDirty = function () { + if (conditionform.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + conditionWindows.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + conditionWindows.close(); + } + + }; + orderDataTree = function (data) { + var items = []; + var type = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL_STEP']; + var label = ['Dynaform', 'Input Document', 'OutPut Document', 'External Step']; + for (var i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items + }); + } + } + }; + + //Properties + loadPropertiesCaseTracker = function () { + dataCaseTracker = []; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + dataCaseTracker = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + updateCaseTrackerPropertiesAndObjects = function (data) { + //save steps Objects Case Tracker + var i, j; + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = (typeof gridPanelObjects.getItems()[i].getData().cto_uid_obj != 'undefined') ? gridPanelObjects.getItems()[i].getData().cto_uid_obj : gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayObjectStepsCaseTracker.indexOf(idObject); + if (index <= -1) { + saveItem(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); + } + } + ; + for (i = 0; i < arrayObjectAvailableObjects.length; i += 1) { + for (j = 0; j < arrayObjectDropAssignedObjects.length; j += 1) { + index = (arrayObjectAvailableObjects[i] == arrayObjectDropAssignedObjects[j].cto_uid_obj) ? 0 : 1; + if (index == 0) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + arrayObjectDropAssignedObjects[j].cto_uid, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } + } + } + + //save Properties Case Tracker + data ['map_type'] = data ['map_type'] == '["1"]' ? "PROCESSMAP" : "NONE"; + data ['routing_history'] = data ['routing_history'] == '["1"]' ? 1 : 0; + data ['message_history'] = data ['message_history'] == '["1"]' ? 1 : 0; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + caseTrackerWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the Case Tracker, please try again.".translate(), + messageSuccess: 'Case Tracker updated successfully'.translate(), + flashContainer: document.body + }); + restClient.executeRestClient(); + }; + + caseTrackerForm = new PMUI.form.Form({ + id: 'caseTrackerForm', + fieldset: true, + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + height: 30, + layout: "hbox", + items: [ + { + pmType: "annotation", + text: "Display :".translate(), + id: "DisplayMessage", + name: "DisplayMessage" + }, + { + id: 'map_type', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Processmap'.translate(), + value: '1' + } + ] + }, + { + id: 'routing_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Routing History'.translate(), + value: '1' + } + ] + }, + { + id: 'message_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + id: 'message_history', + label: 'Messages'.translate(), + value: '1' + } + ] + } + ], + style: { + cssProperties: { + 'margin-bottom': '70px' + } + } + }); + + //objects + loadGridCaseTacker = function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + switch (data[i]['cto_type_obj']) { + case 'DYNAFORM': + label = 'Dynaform'.translate(); + break; + case 'INPUT_DOCUMENT': + label = 'Input Document'.translate(); + break; + case 'OUTPUT_DOCUMENT': + label = 'OutPut Document'.translate(); + break; + case 'EXTERNAL_STEP': + label = 'External Step'.translate(); + break; + default: + label = data[i]['tri_type']; + break; + } + data[i]['obj_label'] = label; + } + gridPanelObjects.setDataItems(data); + }; + + getValuesCaseTrackerObjects = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "case-tracker/available-objects", + "method": 'GET' + }, + { + "url": "case-tracker/objects", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + saveItem = function (rowStep) { + rowStep = rowStep.getData(); + data = { + "cto_type_obj": rowStep.obj_type, + "cto_uid_obj": rowStep.obj_uid, + "cto_condition": (typeof rowStep.cto_condition != 'undefined') ? rowStep.cto_condition : '', + "cto_position": rowStep.cto_position + }; + restClient = new PMRestClient({ + endpoint: 'case-tracker/object', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + data = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems saved, please try again.".translate() + }); + restClient.executeRestClient(); + return data; + }; + + updateItem = function (rowStep, i) { + rowStep = rowStep.getData(); + rowStep.cto_position = i + 1; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + rowStep.cto_uid, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true + } + }); + + editCondition = function () { + var visible, dataEdit; + + conditionform = new PMUI.form.Form({ + id: 'conditionform', + title: "", + fieldset: true, + visibleHeader: false, + width: 500, + items: [ + new CriteriaField({ + id: 'cto_condition', + pmType: 'textarea', + name: 'cto_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 200, + width: 250, + controlsWidth: 285, + renderType: 'textarea' + }) + ] + }); + + if (rowStep != '' && rowStep != undefined) { + dataEdit = conditionform.getFields(); + dataEdit[0].setValue(rowStep['cto_condition']); + } + + conditionWindows = new PMUI.ui.Window({ + id: 'conditionWindows', + title: 'Condition'.translate(), + width: 500, + height: 'auto', + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: conditionformIsDirty, + buttons: [ + { + id: 'conditionObjectWindowButtonClose', + text: "Cancel".translate(), + handler: conditionformIsDirty, + buttonType: 'error' + }, + { + id: 'conditionObjectWindowButtonSave', + text: "Save".translate(), + handler: function () { + var i, item; + if (conditionform.isValid()) { + idrowStep = (typeof rowStep.cto_uid_obj != 'undefined') ? rowStep.cto_uid_obj : rowStep.obj_uid; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + item = gridPanelObjects.getItems()[i].getData(); + idObj = (typeof item.cto_uid_obj != 'undefined') ? item.cto_uid_obj : item.obj_uid; + if (idObj == idrowStep) { + rowStep.cto_condition = conditionform.getData()['cto_condition']; + gridPanelObjects.getItems()[i].setData(rowStep); + break; + } + } + conditionWindows.close(); + } + }, + buttonType: 'success' + } + ] + }); + conditionWindows.addItem(conditionform); + conditionWindows.open(); + conditionWindows.showFooter(); + applyStyleWindowForm(conditionWindows); + conditionWindows.defineEvents(); + conditionWindows.footer.html.style.textAlign = 'right'; + conditionform.setFocus(); + style = $('#cto_condition .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#cto_condition .pmui-field-label').attr("style", style); + }; + + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + width: '640px', + style: {cssClasses: ['itemsSteps']}, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_label", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonProperties', + title: '', + dataType: 'button', + buttonLabel: "Condition".translate(), + iconPosition: "center", + buttonStyle: {cssClasses: ['mafe-button-editstep']}, + buttonTooltip: 'Edit Properties'.translate(), + onButtonClick: function (row, grid) { + rowStep = row.getData(); + editCondition(); + } + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + flagEdit = 1; + rowStep = row.getData(); + index = (row.getData().cto_uid_obj != 'undefined') ? arrayObjectStepsCaseTracker.indexOf(row.getData().cto_uid_obj) : arrayObjectStepsCaseTracker.indexOf(row.getData().obj_uid); + if (index > -1) { + arrayObjectAvailableObjects.push(row.getData().cto_uid_obj); + arrayObjectStepsCaseTracker.splice(index, 1); + } + objType = (typeof row.getData().cto_type_obj != 'undefined') ? row.getData().cto_type_obj : row.getData().obj_type; + grid.removeItem(row); + switch (objType) { + case 'DYNAFORM': + treePanelObjects.getItems()[0].addItem(row); + break; + case 'INPUT_DOCUMENT': + treePanelObjects.getItems()[1].addItem(row); + break; + case 'OUTPUT_DOCUMENT': + treePanelObjects.getItems()[2].addItem(row); + break; + case 'EXTERNAL_STEP': + treePanelObjects.getItems()[3].addItem(row); + break; + default: + break; + } + } + } + ], + onDrop: function (grid, item, index) { + flagEdit = 1; + if (item.data.customKeys.obj_uid === '') { + return false; + } + rowStep = item.getData(); + rowStep.cto_position = index + 1; + item.setData(rowStep); + + index = (typeof item.getData().cto_uid_obj != 'undefined') ? arrayObjectAvailableObjects.indexOf(item.getData().cto_uid_obj) : arrayObjectAvailableObjects.indexOf(item.getData().obj_uid); + + if (index > -1) { + itemPush = (typeof item.getData().cto_uid_obj != 'undefined') ? item.getData().cto_uid_obj : item.getData().obj_uid; + arrayObjectStepsCaseTracker.push(itemPush); + arrayObjectAvailableObjects.splice(index, 1); + } + }, + onSort: function (grid, item, index) { + rowStep = item.getData(); + } + }); + + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-steps-tree' + ] + } + }); + + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-stesp-grid' + ] + } + }); + + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 4, + 'margin-top': 4, + 'margin-left': 4 + } + }, + layout: "hbox" + }); + + panelContainerObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 320, + fieldset: true, + items: [ + treePanelObjects, + gridPanelObjects + ], + layout: "hbox" + }); + + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: DEFAULT_WINDOW_HEIGHT * 0.70, + fieldset: true, + items: [ + panelLabelObjects, + panelContainerObjects + ], + layout: "vbox" + }); + + caseTrackerWindow = new PMUI.ui.Window({ + id: 'caseTrackerWindow', + title: "Case Tracker".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: "bottom", + onBeforeClose: formIsDirty, + visibleFooter: false, + footerAling: "right", + footerItems: [{ + id: 'btnCloseCaseTracker', + text: 'Cancel'.translate(), + buttonType: "error", + handler: formIsDirty + }, + { + id: 'btnSaveCaseTracker', + text: "Save".translate(), + buttonType: "success", + handler: function () { + if (caseTrackerForm.isValid()) { + data = caseTrackerForm.getData(); + updateCaseTrackerPropertiesAndObjects(data); + } + } + } + ], + spaceButtons: 30 + }); + + caseTrackerWindow.addItem(caseTrackerForm); + caseTrackerWindow.addItem(panelObjects); + caseTrackerWindow.open(); + caseTrackerWindow.showFooter(); + applyStyleWindowForm(caseTrackerWindow); + caseTrackerWindow.defineEvents(); + caseTrackerWindow.footer.html.style.textAlign = 'right'; + caseTrackerForm.setFocus(); + + applyStylesWindow = function () { + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': 'auto'}); + $('#caseTrackerForm :eq(2)').css({'padding': '0px 10px 0px 10px'}); + $('#caseTrackerForm :eq(0)').remove(); + items = caseTrackerWindow.getItems()[0].getItems(); + $(items[1].getHTML()).find('table').css('border', 'none'); + $(items[2].getHTML()).find('table').css('border', 'none'); + $(items[3].getHTML()).find('table').css('border', 'none'); + }; + + showObjects = function () { + disableAllItems(); + + loadPropertiesCaseTracker(); + caseTrackerWindow.getItems()[0].setVisible(true); + caseTrackerWindow.showFooter(); + caseTrackerWindow.setTitle("Case Tracker Properties".translate()); + + if (dataCaseTracker != '') { + var dataEdit = caseTrackerForm.getFields(); + dataEdit[1].setValue((dataCaseTracker['map_type'] == 'PROCESSMAP') ? '["1"]' : '[]'); + dataEdit[2].setValue((dataCaseTracker['routing_history'] == 1) ? '["1"]' : '[]'); + dataEdit[3].setValue((dataCaseTracker['message_history'] == 1) ? '["1"]' : '[]'); + } + + + getValuesCaseTrackerObjects(); + caseTrackerWindow.getItems()[1].setVisible(true); + caseTrackerWindow.setTitle("Case Tracker".translate()); + + caseTrackerWindow.body.style.overflow = 'initial'; + + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(640); + gridPanelObjects.setHeight(270); + applyStylesWindow(); + treePanelObjects.style.addProperties({float: 'left'}); + treePanelObjects.style.addProperties({overflow: 'auto'}); + treePanelObjects.setWidth(200); + treePanelObjects.setHeight(270); + + applyStyleTreePanel(treePanelObjects); + + panelLabelObjects.setHeight(15); + caseTrackerWindow.defineEvents(); + + caseTrackerWindow.setBodyPadding(5); + + panelObjects.style.addProperties({marginLeft: '15px'}); + for (var i = 0; i < gridPanelObjects.getItems().length; i += 1) { + arrayObjectStepsCaseTracker[i] = gridPanelObjects.getItems()[i].getData().cto_uid_obj; + arrayObjectDropAssignedObjects[i] = gridPanelObjects.getItems()[i].getData(); + } + }; + showObjects(); + }; + + PMDesigner.caseTracker.showObjects = function () { + PMDesigner.caseTracker(); + }; + +}()); +PMDesigner.gatewayProperties = function (gateway) { + if (gateway.getGatewayType() !== "PARALLEL") { + PMDesigner.RoutingRule(gateway); + } +}; + +PMDesigner.RoutingRule = function (shape) { + var formRoutingRule, + formPanelSelected, + arrayShapeIdRemoved = [], + buttonAdd, + windowConnections, + warningMessageWindowDelete, + warningMessageWindowDirty, + containerLabels, + deleteButton, + buttonSave, + buttonCancel, + labelNextTask, + labelCondition, + typeShapeValueText, + dataRouteGroup = [], + arrayElementName = [], + availableShapes = []; + + warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDelete', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Do you want to delete this routing rule?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, + { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteRow(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowConnections.close(); + }, + buttonType: "success" + } + ] + }); + + buttonAdd = new PMUI.ui.Button({ + id: 'routingRuleButtonAdd', + text: 'Add Routing Rule'.translate(), + style: { + cssProperties: { + marginLeft: '50px', + marginTop: '10px', + marginBottom: '10px', + padding: "5px" + } + }, + buttonType: 'success', + handler: function () { + // to add a new row + addRow(); + enableSorting(); + } + }); + buttonSave = new PMUI.ui.Button({ + id: 'windowConnectionsButtonSave', + text: 'Save'.translate(), + handler: function () { + //validate routing rules form + if (isValidRoutingRules()) { + //remove all flows an get points + var allPoints = removeConnectionsIntoCanvas(); + saveConnections(allPoints); + } + + }, + buttonType: 'success' + }); + buttonCancel = new PMUI.ui.Button({ + id: 'windowConnectionsButtonCancel', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + if (formRoutingRule.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowConnections.close(); + } + } + }); + + labelNextTask = new PMUI.ui.TextLabel({ + text: 'Next Task'.translate() + }); + labelNextTask.setWidth(382); + labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + + labelCondition = new PMUI.ui.TextLabel({ + text: 'Condition'.translate() + }); + labelCondition.setWidth(410); + labelCondition.style.addProperties({padding: '5px 0px 0px 5px'}); + labelCondition.style.addProperties({marginLeft: '31%'}); + + containerLabels = new PMUI.core.Panel({ + layout: 'hbox', + width: 'auto', + height: 29, + style: { + cssProperties: { + 'border-bottom': '1px solid #c0c0c0' + } + } + }); + containerLabels.addItem(labelNextTask); + containerLabels.addItem(labelCondition); + containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + + formRoutingRule = new PMUI.form.Form({ + id: 'formRoutingRule', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + height: 'auto', + items: [], + style: { + cssProperties: { + 'margin-left': '35px' + } + } + }); + formRoutingRule.hideFooter(); + + windowConnections = new PMUI.ui.Window({ + id: 'windowConnections', + title: 'Routing Rule'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + buttonPanelPosition: 'bottom', + items: [ + buttonAdd + ], + buttons: [ + buttonCancel, + buttonSave + ] + }); + + typeShapeValueText = (shape.gat_type === 'EXCLUSIVE') ? 'EXCLUSIVE'.translate() : 'INCLUSIVE'.translate(); + windowConnections.setTitle('Routing Rule'.translate() + ' - ' + typeShapeValueText); + windowConnections.showFooter(); + windowConnections.addItem(containerLabels); + if (formRoutingRule.dirty === null) { + formRoutingRule.dirty = false; + } + windowConnections.addItem(formRoutingRule); + windowConnections.open(); + + loadConnections(); + enableSorting(); + /** + * add a new row + * @returns {PMUI.form.FormPanel|*} + */ + function addRow() { + var dropDownControl, + criteriaField, + deleteButton, + newRow, + max, + i; + newRow = new PMUI.form.FormPanel({ + layout: 'hbox' + }); + + dropDownControl = new PMUI.field.DropDownListField({ + id: 'dropdownNextTask', + name: 'act_name', + valueType: 'string', + label: 'Next Task'.translate(), + labelPosition: 'top', + labelVisible: false, + value: '', + readOnly: false, + controlsWidth: 360, + proportion: 0.9, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + criteriaField = new CriteriaField({ + id: 'textCondition', + pmType: 'text', + renderType: 'textarea', + name: 'flo_condition', + valueType: 'string', + label: 'Condition'.translate(), + labelPosition: 'top', + labelVisible: false, + controlsWidth: 345, + required: false, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + deleteButton = new PMUI.field.ButtonField({ + id: 'buttonDelete', + value: 'Delete'.translate(), + handler: function (e, a) { + formPanelSelected = this.getParent(); + warningMessageWindowDelete.open(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; + warningMessageWindowDelete.showFooter(); + enableSorting(); + }, + name: 'delete', + labelVisible: false, + buttonAling: 'left', + controlsWidth: 60, + proportion: 0.1, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + newRow.addItem(dropDownControl); + newRow.addItem(criteriaField); + newRow.addItem(deleteButton); + loadOptions(dropDownControl); + //apply styles; + if (availableShapes && availableShapes.length > 0) { + deleteButton.controls[0].button.setButtonType('error'); + $(deleteButton.getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(newRow); + for (i = 0, max = formRoutingRule.getItems().length; i < max; i += 1) { + formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); + } + dropDownControl.dom.labelTextContainer.style.display = 'none'; + criteriaField.dom.labelTextContainer.style.display = 'none'; + criteriaField.setValue(true); + } else { + PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer, 'error'); + } + return newRow; + } + + function loadOptions(dropdown) { + var i, + customShapes, + element, + nameGroup, + evnLabelMap; + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + dropdown.clearOptions(); + dropdown.setUID = function (uid) { + this.uid = uid; + }; + dropdown.getUID = function () { + return this.uid; + }; + dropdown.addOptionGroup({ + label: 'Task'.translate(), + selected: true, + options: [] + }); + dropdown.addOptionGroup({ + label: 'Sub-process'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Event'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Gateway'.translate(), + options: [] + }); + customShapes = PMUI.getActiveCanvas().getCustomShapes(); + + for (i = 0; i < customShapes.getSize(); i += 1) { + element = customShapes.get(i); + // verify pool and participant + if (element.getType() !== 'PMParticipant' && element.getType() !== 'PMPool') { + //itself verify and same parent + if (shape.getID() !== element.getID() + && element.businessObject + && shape.businessObject + && shape.businessObject.elem.$parent + && element.businessObject.elem.$parent + && element.businessObject.elem.$parent.id === shape.businessObject.elem.$parent.id) { + switch (element.type) { + case 'PMActivity': + nameGroup = element.act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); + dropdown.addOption({ + value: element.act_uid, + label: element.act_name + }, nameGroup); + arrayElementName[element.act_uid] = element.act_name; + availableShapes.push(element); + break; + case 'PMEvent': + evnLabelMap = { + 'END': 'End Event'.translate(), + 'INTERMEDIATE': 'Intermediate Event'.translate() + }; + + if (element.evn_type !== 'START') { + dropdown.addOption({ + value: element.evn_uid, + label: element.evn_name || evnLabelMap[element.evn_type] + }, 'Event'.translate()); + + arrayElementName[element.evn_uid] = element.evn_name || evnLabelMap[element.evn_type]; + availableShapes.push(element); + } + break; + case 'PMGateway': + dropdown.addOption({ + value: element.gat_uid, + label: element.gat_name || 'Gateway'.translate() + }, 'Gateway'); + arrayElementName[element.gat_uid] = element.gat_name || 'Gateway'.translate(); + availableShapes.push(element); + break; + } + } + } + } + } + + function removeConnectionsIntoCanvas() { + var shapeDest, connection, dt, allPoints = {}, i, j; + for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', arrayShapeIdRemoved[j]); + dt = shape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() === connection.getSrcPort().getParent().getID() && + shapeDest.getID() === connection.getDestPort().getParent().getID()) { + //caching points + allPoints[shapeDest.getID()] = getPoints(connection); + removeConnection(connection); + + break; + } + } + } + arrayShapeIdRemoved = []; + return allPoints; + } + + /** + * to remove a individual connection and getting points + * @param connection + */ + function removeConnection(connection) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().executeCommandDelete(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + } + + /** + * gets conenctions inital and final points + * @param connection + */ + function getPoints(connection) { + var result = []; + result[0] = connection.points[0]; + result[1] = connection.points[connection.points.length - 1]; + return result; + } + + + function editAllConnections(connArray) { + var i, + elem, + canvas = PMUI.getActiveCanvas(); + for(i = 0; i < connArray.length; i += 1) { + elem = connArray[i]; + if (elem && elem.connection) { + elem.oldShapeDest.removePort(elem.connection.destPort); + elem.shapeDest.addPort(elem.connection.destPort, 100, 100, + false, elem.connection.srcPort); + + elem.connection.lineSegments.clear(); + canvas.commandStack.add(new PMUI.command.CommandConnect(elem.connection)); + elem.connection.connect(); + canvas.triggerPortChangeEvent(elem.connection.destPort); + } + } + } + + + function createEndShape() { + var customShape, canvas = PMUI.getActiveCanvas(), command, x, y; + customShape = canvas.shapeFactory('END'); + + x = shape.getX() + shape.getWidth(); + y = shape.getY() + shape.getHeight() + 20; + + canvas.addElement(customShape, x, y, + customShape.topLeftOnCreation); + + //since it is a new element in the designer, we triggered the + //custom on create element event + canvas.updatedElement = customShape; + + // create the command for this new shape + command = new PMUI.command.CommandCreate(customShape); + canvas.commandStack.add(command); + command.execute(); + return customShape; + } + + /** + * new method to validate routing rules + * @returns {boolean} + */ + function isValidRoutingRules() { + var result = true, + arrayAux = [], + i, + max, + id, + dt = formRoutingRule.getItems(); + if (!formRoutingRule.isValid()) { + result = false; + return; + } + + for (i = 0, max = dt.length; i < max; i += 1) { + id = dt[i].getField("act_name").getValue(); + if (typeof(arrayAux[id]) === "undefined") { + arrayAux[id] = "1"; + } else { + result = false; + PMDesigner.msgWinError("The routing rule to \"{0}\" already exists".translate([arrayElementName[id]])); + return; + } + } + return result; + } + + function saveConnections(allPoints) { + var dt = formRoutingRule.getItems(), + id, + i, + oldId, + shapeDest, + oldShapeDest, + connection, + newConnection, + dataRouteAll, + dataRoute, + restClient, + newPoints, + conectionsArray = []; + + + for (i = 0; i < dt.length; i += 1) { + id = dt[i].getField('act_name').getValue(); + oldId = dt[i].getField('act_name').getUID(); + if (id !== '0') { + dataRouteGroup.push(id); + if (dt[i].getField('flo_condition').getValue() == "") { + dt[i].getField('flo_condition').setValue(true); + } + if (oldId === undefined) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + //getting current connection + + newPoints = allPoints[id]; + + newConnection = createConnection(shape, shapeDest, newPoints); + newConnection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id === oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id !== oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + oldShapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', oldId); + connection = isConnection(shape, oldShapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + conectionsArray.push({ + "connection" : isConnection(shape, oldShapeDest) || null, + "shapeDest": shapeDest, + "oldShapeDest": oldShapeDest + }); + } + } else { + var customShape = createEndShape(); + createConnection(shape, customShape); + } + } + editAllConnections(conectionsArray); + + /*update routing order*/ + dataRouteAll = []; + for (i = 0; i < dataRouteGroup.length; i += 1) { + dataRoute = { + 'rou_case': parseInt(i) + 1, + 'rou_next_task': dataRouteGroup[i], + 'pro_uid': PMDesigner.project.id + }; + dataRouteAll.push(dataRoute); + } + restClient = new PMRestClient({ + endpoint: 'update-route-order', + typeRequest: 'update', + data: dataRouteAll, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the routing rule, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + /*end update routing order*/ + + windowConnections.close(); + PMDesigner.msgFlash('Saved correctly'.translate(), document.body); + PMDesigner.project.dirty = true; + PMDesigner.project.setDirty(true); + } + + function createConnection(sourceShape, shape, points) { + var sourcePort, endPort, connection, canvas = PMUI.getActiveCanvas(), points; + sourcePort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + endPort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + if (!points) { + points = findBestPorts(sourceShape, shape); + } + sourceShape.addPort(sourcePort, points[0].x - sourceShape.getZoomX(), points[0].y - sourceShape.getZoomY()); + shape.addPort(endPort, points[1].x - shape.getZoomX(), points[1].y - shape.getZoomY(), false, sourcePort); + + //add ports to the canvas array for regularShapes + //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); + //create the connection + connection = new PMFlow({ + srcPort: sourcePort, + destPort: endPort, + segmentColor: new PMUI.util.Color(0, 0, 0), + name: '', + canvas: shape.canvas, + segmentStyle: shape.connectionType.segmentStyle, + flo_type: shape.connectionType.type + }); + connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' + && shape.connectionType.srcDecorator !== null) ? + shape.connectionType.srcDecorator : 'mafe-sequence', + decoratorType: 'source', + parent: connection + })); + connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' + && shape.connectionType.destDecorator !== null) ? + shape.connectionType.destDecorator : 'mafe-sequence', + decoratorType: 'target', + parent: connection + })); + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + + //connect the two ports + connection.connect(); + connection.setSegmentMoveHandlers(); + + //add the connection to the canvas, that means insert its html to + // the DOM and adding it to the connections array + canvas.addConnection(connection); + + // Filling PMFlow fields + connection.setTargetShape(endPort.parent); + connection.setOriginShape(sourcePort.parent); + connection.savePoints(); + + // now that the connection was drawn try to create the intersections + connection.checkAndCreateIntersectionsWithAll(); + + //attaching port listeners + sourcePort.attachListeners(sourcePort); + endPort.attachListeners(endPort); + + // finally trigger createEvent + canvas.triggerCreateEvent(connection, []); + connection.flo_state = connection.points; + return connection; + } + + function findBestPorts(sourceShape, shape) { + var result = [], i, j, + distance = 99999999, + initPoint, + secondPoint, + midPoints = getMiddlePoints(sourceShape), + midPoints2 = getMiddlePoints(shape); + for (i = 0; i < midPoints.length; i += 1) { + initPoint = midPoints[i]; + for (j = 0; j < midPoints2.length; j += 1) { + secondPoint = midPoints2[j]; + if (distance > initPoint.getManhattanDistance(secondPoint)) { + distance = initPoint.getManhattanDistance(midPoints2[j]); + result[0] = (initPoint); + result[1] = (midPoints2[j]); + } + } + } + return result; + } + + function getMiddlePoints(shape) { + return [ + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), 0 + shape.getZoomY()), // TOP + new PMUI.util.Point(shape.zoomWidth + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()), // RIGHT + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), shape.zoomHeight + shape.getZoomY()), // BOTTOM + new PMUI.util.Point(0 + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()) // LEFT + ]; + } + + function loadConnections() { + var row, connection, dt = shape.getPorts().asArray(), + i, j; + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID() && shape.gat_default_flow !== connection.flo_uid) { + row = addRow(); + row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); + row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); + row.getField('flo_condition').setValue(connection.getFlowCondition()); + + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + } + } + } + + function isConnection(sourceShape, shape) { + var connection, + i, + dt = sourceShape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && + shape.getID() === connection.getDestPort().getParent().getID()) { + return connection; + } + } + return false; + } + + function deleteRow() { + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); + } + + function enableSorting() { + var index = 0, + div = $(formRoutingRule.getHTML()).find(">div:nth-child(2)").css({"overflow": "initial"}); + div.sortable({ + items: '>div', + placeholder: 'steps-placeholder', + cursor: "move", + change: function (event, ui) { + index = ui.placeholder.index(); + }, + start: function (event, ui) { + }, + stop: function (event, ui) { + var dt = [], + row, + formPanelSelected, + id, + i, + j, + shapeDest, + connection; + + ui.item.parent().find(">div").each(function (i, e) { + dt.push(PMUI.getPMUIObject(e)); + }); + for (i = 0; i < dt.length; i += 1) { + formPanelSelected = dt[i]; + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + } + for (i = 0; i < dt.length; i += 1) { + row = addRow(); + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + row.getField('act_name').setValue(dt[i].getField('act_name').getValue()); + row.getField('flo_condition').setValue(dt[i].getField('flo_condition').getValue()); + id = dt[i].getField('act_name').getValue(); + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + } + enableSorting(); + } + }); + } +}; + +PMDesigner.RoutingRuleDeleteAllFlow = function (shape) { + var warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + id: 'warningMessageWindowDelete', + message: 'Do you want to delete all routing rules?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteAllConnection(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + + function deleteAllConnection() { + var connection, elements = [], + i, + sw, + msg, + ports; + PMUI.getActiveCanvas().emptyCurrentSelection(); + //IMPORTANT: You must empty elements in another array due to the array reference indices managed. + //referer: PMDesigner.canvas.removeConnection & element.getPorts().asArray() + + ports = shape.getPorts().asArray(); + for (i = 0; i < ports.length; i += 1) { + elements.push(ports[i]); + } + sw = false; + for (i = 0; i < elements.length; i += 1) { + connection = elements[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID()) { + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().removeElements(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + sw = true; + } + } + msg = sw ? 'Routing rules deleted successfully' : 'There aren\'t routing rules'; + PMDesigner.msgFlash(msg.translate(), document.body); + } + + warningMessageWindowDelete.open(); + warningMessageWindowDelete.showFooter(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; +}; + +PMDesigner.RoutingRuleSetOrder = function (diagram) { + var restClient = new PMRestClient({ + endpoint: 'update-route-order-from-project', + typeRequest: 'update', + data: {}, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + } + }); + restClient.executeRestClient(); +}; +PMDesigner.dynaformDesigner = function (data) { + var old = PMUI.activeCanvas, a; + PMUI.activeCanvas = false; + a = new FormDesigner.main.Designer(data); + a.show(); + a.onHide = function () { + PMUI.activeCanvas = old; + }; + return a; +}; + +PMDesigner.complexRoutingRule = function (shape) { + var formRoutingRule, + formPanelSelected, + arrayShapeIdRemoved = [], + buttonAdd, + windowConnections, + warningMessageWindowDelete, + containerLabels, + buttonSave, + buttonCancel, + labelNextTask, + labelCondition, + warningMessageWindowDirty, + deleteButton; + + //Window + //button add routing rule + buttonAdd = new PMUI.ui.Button({ + id: 'routingRuleButtonAdd', + text: 'Add Routing Rule'.translate(), + style: { + cssProperties: { + marginLeft: '50px', + marginTop: '10px', + marginBottom: '10px', + fontSize: '16px' + } + }, + buttonType: 'success', + height: 31, + handler: function () { + var item, btnDel; + if (countActivities() > 0) { + item = addRow(); + item.getItems()[2].style.addProperties({display: 'none'}); + item.getItems()[2].controls[0].button.setButtonType('error'); + formRoutingRule.addItem(item); + for (var i = 0; i < formRoutingRule.getItems().length; i += 1) { + //formRoutingRule.getItems()[i].style.addProperties({'box-sizing': 'initial'}); + //item.style.addProperties({padding : 'initial'}); + formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); + } + item.getItems()[0].dom.labelTextContainer.style.display = "none"; + item.getItems()[1].dom.labelTextContainer.style.display = "none"; + + } else { + PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer); + } + } + }); + //button Save + buttonSave = new PMUI.ui.Button({ + id: 'windowConnectionsButtonSave', + text: 'Apply'.translate(), + handler: function () { + removeConnectionsIntoCanvas(); + saveConnections(); + }, + buttonType: 'success', + height: 31 + }); + //Button cancel + buttonCancel = new PMUI.ui.Button({ + id: 'windowConnectionsButtonCancel', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + if (formRoutingRule.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowConnections.close(); + } + } + }); + + windowConnections = new PMUI.ui.Window({ + id: 'windowConnections', + title: 'Routing Rule'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + buttonPanelPosition: 'top', + items: [ + buttonAdd + ], + buttons: [ + buttonCancel, + buttonSave + ] + }); + windowConnections.showFooter(); + //END WINDOW + + containerLabels = new PMUI.core.Panel({ + layout: 'hbox', + width: 'auto', + height: 29, + style: { + cssProperties: { + 'border-bottom': '1px solid #c0c0c0' + } + } + }); + + labelNextTask = new PMUI.ui.TextLabel({ + text: 'Next Task'.translate(), + style: { + cssProperties: { + 'font-weight': 'bold' + } + } + }); + + labelCondition = new PMUI.ui.TextLabel({ + text: 'Description'.translate(), + style: { + cssProperties: { + 'font-weight': 'bold' + } + } + }); + + containerLabels.addItem(labelNextTask); + containerLabels.addItem(labelCondition); + + windowConnections.addItem(containerLabels); + + formRoutingRule = new PMUI.form.Form({ + id: 'formRoutingRule', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + height: 'auto', + items: [], + style: { + cssProperties: { + 'margin-left': '35px' + } + } + }); + + warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDelete', + windowMessageType: 'warning', + width: 490, + title: "Routing Rule".translate(), + bodyHeight: 'auto', + message: 'Do you want to delete this routing rule?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteRow(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Routing Rule".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + }, + buttonType: "error" + }, + { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowConnections.close(); + }, + buttonType: "success" + } + ] + }); + + //main + formRoutingRule.hideFooter(); + windowConnections.addItem(formRoutingRule); + windowConnections.open(); + labelNextTask.setWidth(382); + labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + labelCondition.setWidth(410); + labelCondition.style.addProperties({padding: '5px 0px 0px 0px'}); + containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + windowConnections.setTitle('Routing Rule'.translate() + ' - ' + ((shape.gat_type === 'COMPLEX') ? 'Exclusive (Manual)'.translate() : shape.gat_type)); + loadConnections(); + + function countActivities() { + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + var n = 0, i, dt; + dt = PMDesigner.project.getDirtyObject().diagrams[0].activities; + for (i = 0; i < dt.length; i += 1) { + n = n + 1; + } + + dt = PMDesigner.project.getDirtyObject().diagrams[0].events; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].evn_type !== 'START') { + n = n + 1; + } + } + return n; + } + + function addRow() { + + var dropDownControl, description, deleteButton, newRow; + + newRow = new PMUI.form.FormPanel({ + layout: 'hbox' + }); + + dropDownControl = new PMUI.field.DropDownListField({ + id: 'dropdownNextTask', + name: 'act_name', + valueType: 'string', + label: 'Next Task'.translate(), + labelPosition: 'top', + labelVisible: false, + value: '', + readOnly: true, + controlsWidth: 360, + proportion: 1.1, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + description = new PMUI.field.TextField({ + id: 'textCondition', + pmType: 'text', + name: 'flo_description', + valueType: 'string', + label: 'Description'.translate(), + labelPosition: 'top', + labelVisible: false, + controlsWidth: 320, + required: true, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + deleteButton = new PMUI.field.ButtonField({ + id: 'buttonDelete', + value: 'Delete'.translate(), + handler: function (e, a) { + var i; + for (i = 0; i < formRoutingRule.getItems().length; i += 1) { + if (formRoutingRule.getItems()[i].getItems()[2].controls[0].button.id == this.id) { + formPanelSelected = formRoutingRule.getItems()[i]; + warningMessageWindowDelete.open(); + warningMessageWindowDelete.dom.titleContainer.style.height = "17px"; + warningMessageWindowDelete.showFooter(); + } + } + + }, + name: 'delete', + labelVisible: false, + buttonAling: 'left', + controlsWidth: 100, + proportion: 0.3, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + newRow.addItem(dropDownControl); + newRow.addItem(description); + newRow.addItem(deleteButton); + loadActivities(dropDownControl); + return newRow; + } + + function loadActivities(dropdown) { + var i, dt; + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + dropdown.clearOptions(); + dropdown.setUID = function (uid) { + this.uid = uid; + }; + dropdown.getUID = function () { + return this.uid; + }; + dropdown.addOptionGroup({ + label: 'Task'.translate(), + selected: true, + options: [] + }); + dropdown.addOptionGroup({ + label: 'Sub-process'.translate(), + options: [] + }); + dt = PMDesigner.project.getDirtyObject().diagrams[0].activities, nameGroup; + dt = dt.sort(function (a, b) { + return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); + }); + for (i = 0; i < dt.length; i += 1) { + nameGroup = dt[i].act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); + dropdown.addOption({ + value: dt[i].act_uid, + label: dt[i].act_name + }, nameGroup); + } + + dropdown.addOptionGroup({ + label: 'End of process'.translate(), + options: [] + }); + dt = PMDesigner.project.getDirtyObject().diagrams[0].events; + dt = dt.sort(function (a, b) { + return a.evn_name.toString().toLowerCase() > b.evn_name.toString().toLowerCase(); + }); + for (i = 0; i < dt.length; i += 1) { + if (dt[i].evn_type !== 'START') { + dropdown.addOption({ + value: dt[i].evn_uid, + label: dt[i].evn_name + }, 'End of process'.translate()); + } + } + } + + function removeConnectionsIntoCanvas() { + var shapeDest, connection, dt, i, j; + for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { + shapeDest = getShapeForId(arrayShapeIdRemoved[j]); + dt = shape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() === connection.getSrcPort().getParent().getID() && + shapeDest.getID() === connection.getDestPort().getParent().getID()) { + PMDesigner.canvas.emptyCurrentSelection(); + PMDesigner.canvas.setCurrentConnection(connection); + PMDesigner.canvas.removeElements(); + connection.saveAndDestroy(); + PMDesigner.canvas.removeConnection(connection); + break; + } + } + } + arrayShapeIdRemoved = []; + } + + function editShapeDestConnection(shapeDest, oldShape) { + var connection, canvas = PMDesigner.canvas; + connection = isConnection(shape, oldShape); + oldShape.removePort(connection.destPort); + shapeDest.addPort(connection.destPort, 100, 100, + false, connection.srcPort); + + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + connection.connect(); + canvas.triggerPortChangeEvent(connection.destPort); + } + + function createEndShape() { + var customShape, canvas = PMDesigner.canvas, command, x, y; + customShape = canvas.shapeFactory('END'); + + x = shape.getX() + shape.getWidth(); + y = shape.getY() + shape.getHeight() + 20; + + canvas.addElement(customShape, x, y, + customShape.topLeftOnCreation); + + //since it is a new element in the designer, we triggered the + //custom on create element event + canvas.updatedElement = customShape; + + // create the command for this new shape + command = new PMUI.command.CommandCreate(customShape); + canvas.commandStack.add(command); + command.execute(); + return customShape; + } + + function saveConnections() { + var dt, i; + if (!formRoutingRule.isValid()) { + return; + } + dt = formRoutingRule.getItems(), id, oldId, shapeDest, oldShapeDest, connection; + for (i = 0; i < dt.length; i += 1) { + id = dt[i].getField('act_name').getValue(); + oldId = dt[i].getField('act_name').getUID(); + if (id !== '0') { + if (oldId === undefined) { + shapeDest = getShapeForId(id); + createConnection(shape, shapeDest).setFlowCondition(dt[i].getField('flo_description').getValue()); + } + if (oldId !== undefined && id === oldId) { + shapeDest = getShapeForId(id); + connection = isConnection(shape, shapeDest); + $a = connection; + connection.setFlowCondition(dt[i].getField('flo_description').getValue()); + } + if (oldId !== undefined && id !== oldId) { + shapeDest = getShapeForId(id); + oldShapeDest = getShapeForId(oldId); + connection = isConnection(shape, oldShapeDest); + connection.setFlowCondition(dt[i].getField('flo_description').getValue()); + editShapeDestConnection(shapeDest, oldShapeDest); + } + } else { + var customShape = createEndShape(); + createConnection(shape, customShape); + } + } + windowConnections.close(); + PMDesigner.msgFlash('Saved correctly'.translate(), document.body); + PMDesigner.project.dirty = true; + } + + function getShapeForId(id) { + var dt = PMDesigner.canvas.getChildren().asArray(), i; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].act_uid === id || dt[i].evn_uid === id) { + return dt[i]; + } + } + return null; + } + + function createConnection(sourceShape, shape) { + //referer to /processmaker/vendor/colosa/MichelangeloFE/src/connectiondrop.js + //method PMConnectionDropBehavior.prototype.onDrop + var sourcePort, endPort, connection, canvas = PMDesigner.canvas; + sourcePort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + endPort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + + sourceShape.addPort(sourcePort, 100, 100); + shape.addPort(endPort, 100, 100, + false, sourcePort); + + //add ports to the canvas array for regularShapes + //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); + //create the connection + connection = new PMFlow({ + srcPort: sourcePort, + destPort: endPort, + segmentColor: new PMUI.util.Color(92, 156, 204), + name: "", + canvas: shape.canvas, + segmentStyle: shape.connectionType.segmentStyle, + flo_type: shape.connectionType.type + }); + connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' + && shape.connectionType.srcDecorator !== null) ? + shape.connectionType.srcDecorator : "mafe-sequence", + decoratorType: "source", + parent: connection + })); + connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' + && shape.connectionType.destDecorator !== null) ? + shape.connectionType.destDecorator : "mafe-sequence", + decoratorType: "target", + parent: connection + })); + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + + //connect the two ports + connection.connect(); + connection.setSegmentMoveHandlers(); + + //add the connection to the canvas, that means insert its html to + // the DOM and adding it to the connections array + canvas.addConnection(connection); + + // Filling PMFlow fields + connection.setTargetShape(endPort.parent); + connection.setOriginShape(sourcePort.parent); + connection.savePoints(); + + // now that the connection was drawn try to create the intersections + connection.checkAndCreateIntersectionsWithAll(); + + //attaching port listeners + sourcePort.attachListeners(sourcePort); + endPort.attachListeners(endPort); + + // finally trigger createEvent + canvas.triggerCreateEvent(connection, []); + return connection; + } + + function loadConnections() { + var row, connection, dt = shape.getPorts().asArray(), i, j; + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID()) { + row = addRow(); + row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); + row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); + row.getField('flo_description').setValue(connection.getFlowCondition()); + + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = "none"; + row.getItems()[1].dom.labelTextContainer.style.display = "none"; + } + } + } + + function isConnection(sourceShape, shape) { + var connection, dt, i; + dt = sourceShape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && + shape.getID() === connection.getDestPort().getParent().getID()) { + return connection; + } + } + return false; + } + + function deleteRow() { + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); + } + +}; + +var PMVariables = function (options) { + var that = this; + this.initialFormAcceptedValuesKeyValue = null; + this.initialFormAcceptedValuesValue = null; + this.initialGridAcceptedValuesOrder = []; + this.validateAcceptedValuesFlag = false; + this.var_uid = null; + this.var_name = null; + this.edit = false; + this.editRow = null; + this.dirtyAcceptedValue = false; + this.fieldInfo = null; + this.onSave = new Function(); + this.onEdit = new Function(); + this.clickedClose = true; + this.editingOptions = false; + this.editRow = null; + this.currentVariable = null; + this.onWindowClose = new Function(); + this.buttonCreate = new PMUI.ui.Button({ + id: 'buttonCreate', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + + }, + handler: function () { + that.showForm(); + } + }); + + this.buttonCreateInputDocument = new PMUI.field.ButtonField({ + id: 'buttonCreateInputDocument', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + proportion: 0.8, + handler: function (field) { + var inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.method = "POST"; + } + }); + + this.buttonEditInputDocument = new PMUI.field.ButtonField({ + id: 'buttonEditInputDocument', + value: 'Edit'.translate(), + labelVisible: false, + buttonAlign: 'center', + proportion: 0.8, + handler: function (field) { + var form = that.formVariables, + fieldInpDoc = form.getField('inp_doc_uid'), + inp_doc_uid = fieldInpDoc.getValue(), + defaultText = "- Select an input document -".translate(), + inputDocument; + if (inp_doc_uid && inp_doc_uid !== defaultText) { + inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.inputDocumentOriginDataForUpdate = {}; + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(inp_doc_uid); + } else { + fieldInpDoc.setValue(""); + form.isValid(); + } + } + }); + + that.buttonCreateInputDocument.controls[0].button.setButtonType("success"); + that.buttonCreateInputDocument.controls[0].button.setStyle({ + cssClasses: ["mafe-button-create-variable", "pmui-success"], + cssProperties: {padding: "8px 15px", border: "0px"} + }); + that.buttonEditInputDocument.controls[0].button.setButtonType("success"); + that.buttonEditInputDocument.controls[0].button.setStyle({ + cssClasses: ["mafe-button-edit-variable", "pmui-success"], + cssProperties: {padding: "8px 15px", border: "0px"} + }); + + var inp_doc_uid = new PMUI.field.DropDownListField({ + id: "inp_doc_uid", + name: "inp_doc_uid", + value: "", + required: true, + label: "Related Input Document".translate(), + controlsWidth: 460, + valueType: "string", + labelPosition: "top", + onChange: function () { + that.validateInputDoc(); + } + }); + + this.buttonFieldAdd = new PMUI.field.ButtonField({ + id: 'buttonFieldAdd', + pmType: 'buttonField', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.8, + handler: function (field) { + that.addAcceptedValue(); + }, + style: { + cssProperties: { + "margin-left": "10px" + } + } + }); + this.buttonFieldAdd.getControl().button.setButtonType("success"); + this.buttonFieldCancel = new PMUI.field.ButtonField({ + id: 'buttonFieldCancel', + pmType: 'buttonField', + value: 'Cancel'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 55, + proportion: 0.6, + handler: function (field) { + that.clickedClose = false; + that.cancelAcceptedValue(); + that.editingOptions = false; + } + }); + this.buttonFieldCancel.getControl().button.setButtonType("error"); + + this.formVariables = new PMUI.form.Form({ + id: 'formVariables', + width: 'auto', + title: '', + visibleHeader: false, + items: [ + { + pmType: 'text', + label: 'Variable Name'.translate(), + placeholder: "Name".translate(), + id: 'variableName', + value: '', + name: 'var_name', + required: true, + valueType: 'string', + maxLength: 60, + controlsWidth: 460, + validators: [ + { + pmType: "regexp", + criteria: /^[a-zA-Z\_]{1}\w+$/, + errorMessage: "A valid variable starts with a letter or underscore, followed by any number of letters, numbers, or underscores.".translate() + } + ] + }, { + pmType: 'text', + label: 'Label'.translate(), + placeholder: 'Label'.translate(), + id: 'variableLabel', + value: 'label', + name: 'var_label', + valueType: 'string', + maxLength: 60, + controlsWidth: 460, + visible: false + }, { + pmType: 'dropdown', + label: 'Variable Type'.translate(), + placeholder: 'Variable type'.translate(), + id: 'varType', + value: 'string', + name: 'var_field_type', + required: true, + valueType: 'string', + controlsWidth: 460, + options: [ + { + label: 'String', + value: 'string' + }, { + label: 'Integer', + value: 'integer' + }, { + label: 'Float', + value: 'float' + }, { + label: 'Boolean', + value: 'boolean' + }, { + label: 'Datetime', + value: 'datetime' + }, { + label: 'Grid', + value: 'grid' + }, { + label: 'Array', + value: 'array' + }, { + label: "File", + value: "file" + }, { + label: "Multiple File", + value: "multiplefile" + }, { + label: "Object", + value: "object" + } + + ], + onChange: function (newValue, oldValue) { + var sw = that.gridAcceptedValues.visible === false ? true : (that.gridAcceptedValues.getData().length === 0); + var sw2 = that.formBooleanOptions.visible === false ? true : (that.formBooleanOptions.getField('trueOption').getValue() + that.formBooleanOptions.getField('falseOption').getValue()) === ''; + if (sw && sw2) { + that.changeViewFieldType(newValue, oldValue); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + return; + } + var message_window = new PMUI.ui.MessageWindow({ + id: 'messageWindowCancel', + width: 490, + title: 'Variables'.translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: "This action will delete all options. Do you want to continue?".translate(), + footerItems: [ + { + id: 'messageWindowNo', + text: 'No'.translate(), + handler: function () { + message_window.close(); + that.formVariables.getField('var_field_type').setValue(oldValue); + }, + buttonType: "error" + }, + { + id: 'messageWindowYes', + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + that.changeViewFieldType(newValue, oldValue); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + }, + buttonType: "success" + } + ], + onClose: function () { + } + }); + message_window.open(); + message_window.showFooter(); + } + }, { + pmType: "panel", + id: "inp_doc_uidPanel", + fieldset: false, + layout: "hbox", + items: [ + inp_doc_uid, + that.buttonCreateInputDocument, + that.buttonEditInputDocument + ] + }, + { + id: 'booleanPanel', + pmType: 'panel', + legend: 'Options'.translate(), + fieldset: true, + layout: 'vbox', + items: [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + new PMLabelField({ + text: 'Key'.translate(), + textMode: 'plain', + style: { + cssProperties: { + color: '#AEAEAE', + 'font-weight': 'bold' + } + }, + proportion: 0.3 + }), + new PMLabelField({ + text: 'Label'.translate(), + textMode: 'plain', + style: { + cssProperties: { + color: '#AEAEAE', + 'font-weight': 'bold' + } + } + }) + ] + }, + { + pmType: 'text', + name: 'trueOption', + label: 'True'.translate(), + controlsWidth: 460, + valueType: 'string', + maxLength: 100, + required: true + }, { + pmType: 'text', + name: 'falseOption', + label: 'False'.translate(), + controlsWidth: 460, + valueType: 'string', + maxLength: 100, + required: true + } + ] + }, + { + pmType: 'dropdown', + label: 'Database Connection'.translate(), + placeholder: 'Database Connection'.translate(), + id: 'varConnection', + value: 'none', + name: 'var_dbconnection', + controlsWidth: 460, + options: [{ + label: 'PM Database', + value: 'workflow' + } + ], + onChange: function (newValue, oldValue) { + } + }, { + pmType: 'textarea', + label: 'SQL'.translate(), + placeholder: "Insert a SQL query like: SELECT [Key field], [Label field] FROM [Table name]".translate(), + id: 'varSql', + value: '', + name: 'var_sql', + valueType: 'string', + controlsWidth: 460, + style: {cssClasses: ['mafe-textarea-resize']} + }, { + pmType: 'checkbox', + label: 'Define accepted variable values'.translate(), + id: "chckboxOption", + name: 'var_options_control', + controlsWidth: 460, + options: [{value: '1', label: ''}], + onChange: function (newValue, oldValue) { + that.changeViewFieldType(that.formVariables.getField('var_field_type').getValue()); + } + }, + { + id: 'formAcceptedValues', + pmType: 'panel', + fieldset: false, + layout: 'hbox', + items: [ + { + pmType: 'text', + name: 'keyValue', + id: "variable-keyvalue", + label: 'Key'.translate(), + labelWidth: '100%', + controlsWidth: 210, + proportion: 2.5, + valueType: 'string', + maxLength: 255, + labelPosition: "top" + }, + { + pmType: 'text', + name: 'value', + id: "variable-value", + label: 'Label'.translate(), + labelWidth: '100%', + controlsWidth: 300, + valueType: 'string', + maxLength: 255, + proportion: 3.4, + labelPosition: "top" + }, + that.buttonFieldCancel, + that.buttonFieldAdd + ] + } + ] + }); + this.formVariables.getData = function () { + var data = getData2PMUI(that.formVariables.html); + return data; + }; + this.gridVariables = new PMUI.grid.GridPanel({ + id: 'gridVariables', + pageSize: 10, + width: '96%', + style: { + cssClasses: ['mafe-gridPanel'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: 'varName', + title: 'Name'.translate(), + dataType: 'string', + columnData: 'var_name', + alignmentCell: 'left', + width: '300px', + sortable: true + }, { + id: 'varType', + title: 'Type'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'var_field_type', + sortable: true + }, { + id: 'varEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: '60px', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + that.showFormEdit(row.getData()); + } + }, { + id: 'varDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: '70px', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + that.del(row.getData(), row, grid); + } + } + ], + dataItems: null + }); + this.gridAcceptedValues = new PMUI.grid.GridPanel({ + id: 'gridAcceptedValues', + pageSize: 5, + style: {cssClasses: ['mafe-gridPanel']}, + filterPlaceholder: 'Text to Search'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + filterable: false, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: 'keyvalue', + title: 'Key'.translate(), + columnData: 'keyValue', + dataType: 'string', + alignmentCell: 'left', + width: 180 + }, { + id: 'label', + title: 'Label'.translate(), + columnData: 'value', + dataType: 'string', + alignmentCell: 'left', + width: 300 + }, { + id: 'buttonEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: 60, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + that.editRow = row; + that.editAcceptedValue(row); + } + }, { + id: 'buttonDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: 75, + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + if (row !== that.editRow) { + that.deleteAcceptedValue(row); + } else { + PMDesigner.msgFlash('The row can not be removed, because is being edited.'.translate(), document.getElementById('windowVariables'), 'error', 1000, 5); + } + } + } + ], + dataItems: null, + behavior: 'dragdropsort' + }); + this.isDirtyFormVariables = function () { + $("input,select,textarea").blur(); + if (this.formVariables.isVisible()) { + this.validateAcceptedValues(); + if (this.formVariables.isDirty() || this.dirtyAcceptedValue || this.validateAcceptedValuesFlag) { + //if (this.formVariables.getField("var_options_control").controls[0].selected) { + var message_window = new PMUI.ui.MessageWindow({ + id: "messageWindowCancel", + width: 490, + title: "Variables".translate(), + windowMessageType: "warning", + bodyHeight: "auto", + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: "messageWindowNo", + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: "messageWindowYes", + text: "Yes".translate(), + handler: function () { + if (that.clickedClose) { + that.windowVariables.close(); + } + message_window.close(); + that.showGrid(); + that.windowVariables.hideFooter(); + }, + buttonType: "success" + }, + ] + }); + + message_window.open(); + message_window.showFooter(); + /*} else { + that.showGrid(); + }*/ + } else { + if (that.clickedClose) { + that.windowVariables.close(); + } else { + that.showGrid(); + } + this.initialFormAcceptedValuesKeyValue = null; + this.initialFormAcceptedValuesValue = null; + this.initialGridAcceptedValuesOrder = []; + that.windowVariables.hideFooter(); + } + } else { + this.windowVariables.close(); + } + }; + this.windowVariables = new PMUI.ui.Window({ + id: 'windowVariables', + title: 'Variables'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFormVariables(); + }, + footerItems: [ + new PMUI.ui.Button({ + id: "windowVariablesCancel", + text: "Cancel".translate(), + + handler: function () { + that.clickedClose = false; + that.isDirtyFormVariables(); + }, + + buttonType: "error" + }), + + new PMUI.ui.Button({ + id: "windowVariablesSave", + text: "Save".translate(), + + handler: function () { + if (that.edit) { + that.updateVariables(); + } else { + that.saveVariables(); + } + }, + + buttonType: "success" + }) + ], + onClose: function () { + that.onWindowClose(that.currentVariable); + }, + visibleFooter: true, + buttonPanelPosition: "bottom" + }); + PMVariables.prototype.init.call(this); + that.setInputDocuments(inp_doc_uid); +}; +PMVariables.prototype.init = function () { + var that = this, + acceptedValuesForm, + label; + + that.buttonCreate.defineEvents(); + + that.windowVariables.addItem(that.gridVariables); + that.windowVariables.addItem(that.formVariables); + that.windowVariables.addItem(that.gridAcceptedValues); + that.windowVariables.hideFooter(); + that.windowVariables.open(); + label = $('#booleanPanel'); + acceptedValuesForm = $('#formAcceptedValues'); + that.customCss(); + acceptedValuesForm.find(".pmui-field-message").css("marginLeft", 10); + $("#gridAcceptedValues").css({"height": "254px", "margin": "0 10px"}); + $("#requiredMessage").css({"margin-top": "10px"}); + $("#inp_doc_uid").find(".pmui-field-message:eq(0)").css("left", "226px"); + this.formAcceptedValues = PMUI.getPMUIObject(acceptedValuesForm.get(0)); + + this.buttonFieldAdd.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + this.buttonFieldCancel.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + $('#gridVariables .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + that.gridVariables.dom.toolbar.appendChild(that.buttonCreate.getHTML()); + + this.formBooleanOptions = PMUI.getPMUIObject(label.get(0)); + that.showGrid(); + that.loadDataBaseConnections(); + + validateKeysField(that.formVariables.getField('var_name').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + + that.resetAcceptedValuesPanel(); + label = $('#booleanPanel').css({'width': '675px', margin: '10px'}).find(".pmui-pmlabelfield"); + $(label[0]).replaceWith($(label[0]).find(".pmui-pmlabelcontrol").css({ + "font-size": "14px", + "margin-right": "127px" + })); + $(label[1]).replaceWith($(label[1]).find(".pmui-pmlabelcontrol").css({ + "font-size": "14px", + "margin-right": "127px" + })); + this.formVariables.panel.html.style.overflow = "scroll !important"; + $(this.formVariables.panel.html).removeClass("pmui-formpanel"); + $(this.formVariables.panel.html).append(that.formAcceptedValues.html); + $(this.formVariables.panel.html).append(that.gridAcceptedValues.html); + $(that.formAcceptedValues.html).find(".pmui-formpanel").css({"display": "inline-block"}); + that.windowVariables.footer.html.style.textAlign = "right"; +}; +PMVariables.prototype.saveVariables = function () { + var that = this, + data, + inp_doc_uid_value = this.formVariables.getField("inp_doc_uid").controls[0].value; + this.formVariables.getField("inp_doc_uid").setValue(inp_doc_uid_value); + if (!this.formVariables.isValid()) { + return; + } + if (this.formBooleanOptions.visible && !this.formBooleanOptions.isValid()) { + return; + } + data = this.formVariables.getData(); + data.var_label = data.var_field_type; + + data.var_default = ''; + data.var_accepted_values = that.getDataAcceptedValues(); + data.var_field_size = 10; + if (!this.formVariables.getField('var_sql').visible) + data.var_sql = ""; + (new PMRestClient({ + endpoint: 'process-variable', + typeRequest: 'post', + functionSuccess: function (xhr, response) { + if (that.onSave(xhr, response) === false) { + that.var_uid = null; + return; + } + that.showGrid(); + that.load(); + that.var_uid = null; + that.windowVariables.hideFooter(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ' ', + data: data, + messageSuccess: 'Variable saved successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.updateVariables = function () { + var that = this, + data, + inp_doc_uid_value = this.formVariables.getField("inp_doc_uid").controls[0].value; + this.formVariables.getField("inp_doc_uid").setValue(inp_doc_uid_value); + if (!this.formVariables.isValid()) { + return; + } + if (this.formBooleanOptions.visible && !this.formBooleanOptions.isValid()) { + return; + } + data = this.formVariables.getData(); + data.var_label = data.var_field_type; + data.var_field_size = 10; + if (that.formVariables.getField('var_name').getValue().trim() === that.var_name.trim()) { + delete data['var_name']; + } + data.var_default = ''; + data.var_accepted_values = that.getDataAcceptedValues(); + if (!this.formVariables.getField('var_sql').visible) + data.var_sql = ""; + (new PMRestClient({ + endpoint: 'process-variable/' + that.var_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + if (that.onEdit(xhr, response, data) === false) { + that.var_uid = null; + return; + } + var var_name_old = that.currentVariable.var_name; + that.currentVariable = data; + that.currentVariable.var_uid = that.var_uid; + that.currentVariable.var_name_old = var_name_old; + that.showGrid(); + that.load(); + that.var_uid = null; + that.windowVariables.hideFooter(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ' ', + messageSuccess: 'Variable edited successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.deleteVariable = function (var_uid) { + var that = this; + (new PMRestClient({ + endpoint: 'process-variable/' + var_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'working...'.translate(), + messageSuccess: 'Variable deleted successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.load = function () { + var that = this; + var restProxy = new PMRestClient({ + endpoint: 'process-variables', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var listInputDocs = response; + that.gridVariables.setDataItems(listInputDocs); + that.gridVariables.sort('var_name', 'asc'); + $(that.gridVariables.dom.toolbar).find("input").val(""); + that.gridVariables.clearFilter(); + if (that.currentVariable !== null) { + var var_name_old = that.currentVariable.var_name_old; + for (var i = 0; i < response.length; i++) { + if (that.currentVariable.var_uid === response[i].var_uid) { + that.currentVariable = response[i]; + } + } + that.currentVariable.var_name_old = var_name_old; + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +PMVariables.prototype.del = function (data, row, grid) { + var that = this; + var confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDel', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Variables".translate(), + message: 'Do you want to delete this variable?'.translate(), + footerItems: [{ + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.deleteVariable(data.var_uid, row); + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMVariables.prototype.customCss = function () { + $("#inp_doc_uidPanel").css({padding: ""}); + $("#inp_doc_uid").css({width: "75%"}).find("label:eq(0)").css({float: "left", width: "31.5%"}); + + var td = $("#chckboxOption .pmui-field-control-table td")[0]; + + if (typeof(td) != "undefined") { + td.setAttribute("style", "padding:0px !important"); + } + + this.formVariables.panel.getHTML().setAttribute("style", "overflow: initial"); +}; + +PMVariables.prototype.showGrid = function () { + var that = this; + that.formVariables.setVisible(false); + that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(false); + that.disableBooleanPanel(); + $(that.gridVariables.dom.toolbar).find("input").val(""); + that.gridVariables.clearFilter(); + that.gridVariables.setVisible(true); + that.windowVariables.setTitle('Variables'.translate()); +}; +PMVariables.prototype.showForm = function () { + var that = this; + that.edit = false; + that.dirtyAcceptedValue = false; + that.formVariables.setVisible(true); + that.enableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true); + that.enableBooleanPanel(); + that.gridVariables.setVisible(false); + that.windowVariables.setTitle('Create Variable'.translate()); + that.formVariables.reset(); + that.formVariables.setFocus(); + that.changeViewFieldType('string'); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + that.buttonFieldCancel.setVisible(false); + that.windowVariables.showFooter(); + that.buttonCreateInputDocument.setVisible(false); + that.buttonEditInputDocument.setVisible(false); +}; +PMVariables.prototype.showFormEdit = function (data) { + var that = this; + that.showForm(); + that.var_uid = data.var_uid; + that.edit = true; + that.var_name = data.var_name; + that.windowVariables.setTitle('Edit Variable'.translate()); + that.formVariables.getField('var_dbconnection').setValue(data.var_dbconnection); + that.formVariables.getField('var_field_type').setValue(data.var_field_type); + that.formVariables.getField('var_label').setValue(data.var_label); + that.formVariables.getField('var_name').setValue(data.var_name); + that.formVariables.getField('var_sql').setValue(data.var_sql); + that.formVariables.getField('inp_doc_uid').setValue(data.inp_doc_uid); + + that.setVarOptionsControl(data.var_accepted_values); + that.changeViewFieldType(data.var_field_type); + that.setDataAcceptedValues(data.var_accepted_values); + that.currentVariable = data; + that.currentVariable.var_name_old = that.currentVariable.var_name; +}; +PMVariables.prototype.loadDataBaseConnections = function () { + var that = this; + var restProxy = new PMRestClient({ + endpoint: 'database-connections', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var dropdown = that.formVariables.getField('var_dbconnection'); + for (var i = 0; i < response.length; i++) { + if (response[i].dbs_connection_type == "TNS") { + dropdown.addOption({ + label: "[" + response[i].dbs_tns + "] " + response[i].dbs_type + " : " + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } else { + dropdown.addOption({ + label: "[" + response[i].dbs_server + ":" + response[i].dbs_port + "] " + response[i].dbs_type + ": " + response[i].dbs_database_name + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +PMVariables.prototype.changeViewFieldType = function (newValue) { + var that = this; + var sw = that.formVariables.getField('var_options_control').controls[0].selected; + + that.formVariables.getField('var_dbconnection').setVisible(false); + that.formVariables.getField('var_sql').setVisible(false); + that.formVariables.getField('var_options_control').setVisible(false); + that.formVariables.getField('inp_doc_uid').setVisible(false); + that.formVariables.getField('inp_doc_uid').setRequired(false); + that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(false); + that.disableBooleanPanel(); + that.buttonCreateInputDocument.setVisible(false); + that.buttonEditInputDocument.setVisible(false); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), []); + + if (this.fieldInfo === null) { + this.fieldInfo = document.createTextNode(''); + var a = that.formVariables.getField('var_field_type').getControls()[0]; + a.html.parentNode.appendChild(document.createElement('br')); + a.html.parentNode.appendChild(this.fieldInfo); + } + + switch (newValue) { + case 'string': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + + + break; + case 'integer': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'ishyphen']); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + break; + case 'float': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isperiod', 'ishyphen']); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + break; + case 'boolean': + that.enableBooleanPanel(); + this.fieldInfo.data = "Supported Controls: checkbox, radio, hidden.".translate(); + break; + case 'datetime': + this.fieldInfo.data = "Supported Controls: datetime, hidden.".translate(); + break; + case "grid": + this.fieldInfo.data = "Supported Controls: grid.".translate(); + break; + case "array": + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + this.fieldInfo.data = "Supported Controls: checkgroup.".translate(); + break; + case 'file': + that.formVariables.getField('inp_doc_uid').setVisible(true); + that.buttonCreateInputDocument.setVisible(true); + that.buttonEditInputDocument.setVisible(true); + that.formVariables.getField('inp_doc_uid').setRequired(true); + this.fieldInfo.data = "Supported Controls: file.".translate(); + that.validateInputDoc(); + break; + case 'multiplefile': + this.fieldInfo.data = "Supported Controls: Multiple File.".translate(); + break; + case 'object': + this.fieldInfo.data = "Supported Controls:".translate(); + break; + } +}; +/** + * Enable or disable edit button of input document + */ +PMVariables.prototype.validateInputDoc = function () { + var form = this.formVariables, + fieldInpDoc = form.getField("inp_doc_uid"), + defaultText = "- Select an input document -".translate(); + if (fieldInpDoc && fieldInpDoc.getValue() && fieldInpDoc.getValue() !== defaultText) { + this.buttonEditInputDocument.enable(); + } else { + this.buttonEditInputDocument.disable(); + } +}; +PMVariables.prototype.addAcceptedValue = function () { + var that = this, + key = jQuery.trim(that.formAcceptedValues.getField('keyValue').getValue()), + value = jQuery.trim(that.formAcceptedValues.getField('value').getValue()); + + if (that.isAcceptedValueAdded()) { + return PMDesigner.msgFlash('The key value already exists.'.translate(), + document.getElementById('windowVariables'), 'error', 1000, 5); + } + if (!(key && value)) { + return PMDesigner.msgFlash('The key and label must be supplied.'.translate(), + document.getElementById('windowVariables'), 'error', 1000, 5); + } + if (that.editRow === null) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + keyValue: key, + value: value + } + })); + } else { + this.editingOptions = false; + that.editRow.setData({ + keyValue: key, + value: value + }); + } + that.dirtyAcceptedValue = true; + that.cancelAcceptedValue(); +}; +PMVariables.prototype.editAcceptedValue = function (row) { + var that = this; + this.editingOptions = true; + that.editRow = row; + var data = row.getData(); + that.formAcceptedValues.getField('keyValue').setValue(data.keyValue); + that.formAcceptedValues.getField('value').setValue(data.value); + that.buttonFieldAdd.setValue('Save'.translate()); + that.buttonFieldCancel.setVisible(true); + + that.initialFormAcceptedValuesKeyValue = data.keyValue; + that.initialFormAcceptedValuesValue = data.value; +}; +PMVariables.prototype.deleteAcceptedValue = function (row) { + var that = this; + var confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Variables".translate(), + message: 'Do you want to delete this Key Value?'.translate(), + footerItems: [{ + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.gridAcceptedValues.removeItem(row); + that.dirtyAcceptedValue = true; + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; +PMVariables.prototype.getDataAcceptedValues = function () { + var that = this, data = [], i, dt = []; + if (that.gridAcceptedValues.visible) { + dt = that.gridAcceptedValues.getData(); + for (i = 0; i < dt.length; i++) { + delete dt[i].key; + delete dt[i].type; + data.push({ + value: dt[i].keyValue, + label: dt[i].value + }); + } + } + if (that.formBooleanOptions.visible) { + var a = that.formBooleanOptions.getItems("fields").reduce(function (prev, curr) { + prev[curr.getName()] = curr.getValue(); + return prev; + }, {}); + + data = [ + {value: '1', label: a.trueOption}, + {value: '0', label: a.falseOption} + ]; + } + return data; +}; +PMVariables.prototype.setDataAcceptedValues = function (stringJsonData) { + if (!stringJsonData) { + return; + } + var that = this, i, data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + if (that.gridAcceptedValues.visible) { + for (i = 0; i < data.length; i++) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + keyValue: data[i].keyValue ? data[i].keyValue : data[i].value, + value: data[i].keyValue ? data[i].value : data[i].label + } + })); + that.initialGridAcceptedValuesOrder.push(data[i].keyValue ? data[i].keyValue : data[i].value); + } + } + if (that.formBooleanOptions.visible) { + that.formBooleanOptions.getField('trueOption').setValue(data[0].label); + that.formBooleanOptions.getField('falseOption').setValue(data[1].label); + } +}; +PMVariables.prototype.validateAcceptedValues = function () { + var that = this, + dirty = false, + finalVal1, + finalVal2, + initVal1, + initVal2, + gridAcceptedValues, + finalGridAcceptedValuesOrder = [], + key; + if (that.initialFormAcceptedValuesValue && that.formAcceptedValues.getField('value').getValue() != '') { + finalVal1 = that.formAcceptedValues.getField('value').getValue(); + finalVal2 = that.formAcceptedValues.getField('keyValue').getValue(); + initVal1 = that.initialFormAcceptedValuesValue; + initVal2 = that.initialFormAcceptedValuesKeyValue; + if (finalVal1 !== initVal1 || finalVal2 !== initVal2) { + dirty = true; + } + } else if (that.formAcceptedValues.getField('value').getValue() !== '' || that.formAcceptedValues.getField('keyValue').getValue()) { + dirty = true; + } + + if (that.initialGridAcceptedValuesOrder.length) { + gridAcceptedValues = that.gridAcceptedValues.getData(); + for (key in gridAcceptedValues) { + if (gridAcceptedValues.hasOwnProperty(key)) { + finalGridAcceptedValuesOrder.push(gridAcceptedValues[key].keyValue); + } + } + if (JSON.stringify(finalGridAcceptedValuesOrder) !== JSON.stringify(that.initialGridAcceptedValuesOrder)) { + dirty = true; + } + } + this.validateAcceptedValuesFlag = dirty; +}; +PMVariables.prototype.setVarOptionsControl = function (stringJsonData) { + if (!stringJsonData) { + return; + } + var that = this, i, data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + if (data.length > 0) { + that.formVariables.getField('var_options_control').setValue("['1']"); + } +}; +PMVariables.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that.buttonFieldAdd.setValue('Add'.translate()); + that.buttonFieldCancel.setVisible(false); + that.resetAcceptedValuesPanel(); +}; +PMVariables.prototype.isAcceptedValueAdded = function () { + var that = this, i, keyValue, data, exist, i, index, rowEditValue; + data = that.gridAcceptedValues.getData(); + keyValue = that.formAcceptedValues.getField('keyValue').getValue() || ""; + if (this.editingOptions) { + rowEditValue = this.editRow.getData()["keyValue"]; + for (i = 0; i < data.length; i++) { + if (rowEditValue === data[i].keyValue) { + index = i; + break; + } + } + for (i = 0; i < data.length; i++) { + if (i !== index) { + if (keyValue === data[i].keyValue) { + exist = true; + } + } + } + if (exist) { + return true; + } else { + return false; + } + } else { + for (i = 0; i < data.length; i++) { + if (data[i].keyValue === keyValue) { + return true; + } + } + } + return false; +}; +PMVariables.prototype.setInputDocuments = function (inp_doc_uid) { + var restClient = new PMRestClient({ + endpoint: 'input-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + inputDocumentsData = response; + var arrayOptions = []; + arrayOptions[0] = { + label: "- Select an input document -".translate(), + value: "", + disabled: true, + selected: true + }; + for (var i = 0; i <= inputDocumentsData.length - 1; i++) { + arrayOptions.push( + { + value: inputDocumentsData[i].inp_doc_uid, + label: inputDocumentsData[i].inp_doc_title + } + ); + } + inp_doc_uid.setOptions(arrayOptions); + inp_doc_uid.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + }); + restClient.executeRestClient(); +}; +PMVariables.prototype.setInputDocumentsFromIDModule = function (inp_doc_uid, response) { + var inp_doc_uid_val = $("#inp_doc_uid").find("select:eq(0) option:selected").val(); + var arrayOptions = []; + inputDocumentsData = response; + arrayOptions[0] = { + label: "- Select an input document -".translate(), + value: "", + disabled: true, + selected: true + }; + for (var i = 0; i <= inputDocumentsData.length - 1; i++) { + arrayOptions.push( + { + value: inputDocumentsData[i].inp_doc_uid, + label: inputDocumentsData[i].inp_doc_title + } + ); + } + inp_doc_uid.setOptions(arrayOptions); + inp_doc_uid.setValue(arrayOptions[0].value); + if (inp_doc_uid_val) { + inp_doc_uid.setValue(inp_doc_uid_val); + } +}; +PMVariables.prototype.isWindowActive = function () { + if ($("#formVariables").is(":visible")) { + return true; + } + return false; +}; +/** + * Reset the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.resetBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.getItems("fields").forEach(function (i) { + i.setValue(""); + }); + } + return this; +}; +/** + * Disable the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.disableBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.setVisible(false) + .getItems("fields").forEach(function (i) { + i.disable(); + }); + } + return this; +}; +/** + * Enable the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.enableBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.setVisible(true) + .getItems("fields").forEach(function (i) { + i.enable(); + }); + } + return this; +}; +/** + * Reset the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.resetAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.getItems().forEach(function (i) { + i.setValue(""); + }); + } + return this; +}; +/** + * Enable the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.enableAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.setVisible(true) + .getItems('fields').forEach(function (i) { + i.enable(""); + }); + } + return this; +}; +/** + * Disable the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.disableAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.setVisible(false) + .getItems('fields').forEach(function (i) { + i.disable(""); + }); + } + return this; +}; +PMDesigner.variables = function () { + var pmvariables = new PMVariables(); + pmvariables.load(); +}; +PMDesigner.variables.create = function () { + var pmvariables = new PMVariables(); + pmvariables.showForm(); + pmvariables.load(); +}; + +RowVariableCondition = function () { + PMUI.form.FormPanel.call(this, { + layout: 'hbox' + }); + RowVariableCondition.prototype.init.call(this); +}; +RowVariableCondition.prototype = new PMUI.form.FormPanel(); +RowVariableCondition.prototype.createHTML = function () { + var items; + PMUI.form.FormPanel.prototype.createHTML.call(this); + items = this.getItems(); + items[0].dom.labelTextContainer.style.display = 'none'; + items[1].dom.labelTextContainer.style.display = 'none'; + items[2].dom.labelTextContainer.style.display = 'none'; + items[2].style.addProperties({display: 'none'}); + items[2].controls[0].button.setButtonType('error'); + return this.html; +}; +RowVariableCondition.prototype.init = function () { + var that = this, + typeData, + field, + remove; + field = new PMUI.field.TextField({ + id: 'idField', + name: '', + required: true, + controlsWidth: 425, + proportion: 2.1, + labelVisible: false + }); + typeData = new PMUI.field.DropDownListField({ + id: 'idTypeData', + name: '', + valueType: 'string', + value: '', + readOnly: true, + controlsWidth: 200, + labelVisible: false, + options: [{ + value: 'integer', + label: 'Integer'.translate() + }, { + value: 'string', + label: 'String'.translate() + }, { + value: 'float', + label: 'Float'.translate() + }, { + value: 'boolean', + label: 'Boolean'.translate() + }, { + value: 'date', + label: 'Date'.translate() + }, { + value: 'datetime', + label: 'Datetime'.translate() + } + ] + }); + remove = new PMUI.field.ButtonField({ + id: 'idRemove', + value: 'Delete'.translate(), + labelVisible: false, + handler: function (e, a) { + that.getParent().removeItem(that); + }, + name: 'delete', + controlsWidth: 60 + }); + that.addItem(field); + that.addItem(typeData); + that.addItem(remove); +}; + +PropertiesReceiveMessage = function (menuOption) { + this.variables = []; + this.onApply = new Function(); + this.onCancel = new Function(); + this.menuOption = menuOption; + Mafe.Window.call(this); + PropertiesReceiveMessage.prototype.init.call(this); +}; +PropertiesReceiveMessage.prototype = new Mafe.Window(); +PropertiesReceiveMessage.prototype.init = function () { + var that = this; + that.setTitle(that.menuOption.getMenuTargetElement().evn_name); + that.setButtons([ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + handler: function () { + that.close(); + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSaveOpen', + text: 'Apply'.translate(), + buttonType: 'success', + height: 31, + handler: function () { + that.onApply(); + } + }) + ]); + that.buttonAdd = new PMUI.ui.Button({ + text: 'Add Variable'.translate(), + buttonType: 'success', + height: 31, + style: {cssProperties: {marginLeft: '50px', marginTop: '10px'}}, + handler: function () { + that.addVariable(); + } + }); + that.form = new Mafe.Form({ + title: that.menuOption.getMenuTargetElement().evn_name, + width: DEFAULT_WINDOW_WIDTH - 60, + style: {cssProperties: {'margin-left': '35px'}} + }); + that.conditionForm = new Mafe.Form({ + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + style: {cssProperties: {'margin-left': '35px'}}, + items: [{ + label: 'Condition', + labelPosition: 'top', + pmType: 'textarea', + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + } + ] + }); + + that.addItem(that.buttonAdd); + that.addItem(that.form); + that.addItem(that.conditionForm); + + that.addVariable(); +}; +PropertiesReceiveMessage.prototype.addVariable = function () { + var that = this, a, i; + a = new RowVariableCondition(this.variables); + that.form.addItem(a); + //force padding + for (i = 0; i < that.form.getItems().length; i += 1) { + that.form.getItems()[i].style.addProperties({'padding': 'initial'}); + } +}; + +EventMessagesGrid = function () { + this.onCreate = new Function(); + this.onEdit = new Function(); + this.onDel = new Function(); + Mafe.Grid.call(this); + EventMessagesGrid.prototype.init.call(this); +}; +EventMessagesGrid.prototype = new Mafe.Grid(); +EventMessagesGrid.prototype.createHTML = function () { + Mafe.Grid.prototype.createHTML.call(this); + this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); + return this.html; +}; +EventMessagesGrid.prototype.init = function () { + var that = this; + that.buttonCreate = new PMUI.ui.Button({ + id: 'idButtonEventMessagesGrid', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: {cssClasses: ['mafe-button-create']}, + handler: function (event) { + that.onCreate(event); + } + }); + that.buttonCreate.defineEvents(); + that.setID('idEventMessagesGrid'); + that.setColumns([{ + id: '', + title: 'Nombre', + sortable: true, + width: '460px', + dataType: 'string', + alignmentCell: 'left', + columnData: 'mes_title' + }, { + id: 'dynaformGridPanelEdit', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-edit']}, + buttonLabel: function (row, data) { + return 'Edit'.translate(); + }, + onButtonClick: function (row, grid) { + that.onEdit(row, grid); + } + }, { + id: 'dynaformGridPanelDelete', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-delete']}, + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + onButtonClick: function (row, grid) { + that.onDel(row, grid); + } + } + ]); + that.load(); +}; +EventMessagesGrid.prototype.show = function () { + +}; +EventMessagesGrid.prototype.create = function () { + +}; +EventMessagesGrid.prototype.load = function () { + var that = this, + dt = [ + {mes_title: 'message1-1'}, + {mes_title: 'message1-2'}, + {mes_title: 'message1-3'}, + {mes_title: 'message1-4'} + ]; + that.setDataItems(dt); +}; + +EventMessagesForm = function () { + Mafe.Form.call(this); + EventMessagesForm.prototype.init.call(this); +}; +EventMessagesForm.prototype = new Mafe.Form(); +EventMessagesForm.prototype.init = function () { + var that = this; + that.setID('idEventMessagesForm'); + that.setItems({ + id: '', + pmType: 'text', + label: 'Name'.translate(), + value: '', + maxLength: 100, + placeholder: '', + name: '', + required: true, + controlsWidth: 300 + }); + that.buttons = [ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + handler: function () { + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformPmtableSave', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + handler: function () { + that.onSave(); + } + }) + ]; +}; +EventMessagesForm.prototype.getButtons = function () { + return this.buttons; +}; + +EventMessages = function () { + Mafe.Window.call(this); + + this.list = new EventMessagesGrid(); + this.form = new EventMessagesForm(); + + EventMessages.prototype.init.call(this); +}; +EventMessages.prototype = new Mafe.Window(); +EventMessages.prototype.init = function () { + var that = this; + that.list.onCreate = function () { + that.resetView(); + that.form.setVisible(true); + }; + that.setTitle("Event Messages"); + that.addItem(that.list); +}; +EventMessages.prototype.showForm = function () { + this.list.show(); +}; + +PMDesigner.eventMessages = function () { + var a = new EventMessages(); + a.open(); +}; +PMDesigner.eventMessages.create = function () { +}; + +var UserPicker = function (options) { + this.relatedField = null; + this.processId = null; + this.workspace = null; + this.window = null; + this.currentVariable = {}; + this.pageSize = 10; + UserPicker.prototype.init.call(this, options); +}; + +UserPicker.prototype.type = 'UserPicker'; + +UserPicker.prototype.family = 'UserPicker'; + +UserPicker.prototype.init = function (options) { + var defaults = { + relatedField: null, + processId: PMDesigner.project.projectId, + workspace: WORKSPACE + }; + + jQuery.extend(true, defaults, options); + + this.setRelatedField(defaults.relatedField) + .setProcessId(defaults.processId) + .setWorkspace(defaults.workspace); +}; + +UserPicker.prototype.setRelatedField = function (field) { + if (field instanceof PMUI.form.Field) { + this.relatedField = field; + } + return this; +}; + +UserPicker.prototype.setProcessId = function (process) { + this.processId = process; + return this; +}; + +UserPicker.prototype.setWorkspace = function (workspace) { + this.workspace = workspace; + return this; +}; + +UserPicker.prototype.open = function (callback) { + var w, rc, fieldC, dataGrid, panel, textField, that = this, button, panelFilter; + button = new PMUI.ui.Button({ + id: 'insertUser', + text: 'Insert User'.translate(), + handler: function () { + if (callback && callback.success && typeof callback.success === 'function') { + callback.success.call(that, that.currentVariable); + } + that.close(); + }, + disabled: true + }); + + textField = new PMUI.field.TextField({ + id: 'textFieldSearch', + label: '', + placeholder: 'Search ...'.translate() + }); + + w = new PMUI.ui.Window({ + id: 'processVariables', + title: 'Process Users'.translate(), + width: 480, + height: 420, + closable: true, + modal: true, + buttons: [ + button + ], + buttonsPosition: 'center' + }); + + textField = new PMUI.field.TextField({ + id: 'textFieldSearch', + label: '', + placeholder: 'Search ...'.translate(), + width: 150 + }); + + dataGrid = new PMUI.grid.GridPanel({ + id: 'gridPanel', + selectable: true, + pageSize: this.pageSize, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'gridPanelUserName', + title: 'User Name'.translate(), + columnData: 'usr_username', + width: 150, + sortable: true, + alignmentCell: 'left' + }, + { + id: 'gridPanelRole', + title: 'Role'.translate(), + columnData: 'usr_role', + width: 230, + sortable: false, + alignmentCell: 'left' + } + ], + onRowClick: function (row, data) { + button.enable(); + that.currentVariable.username = data.usr_username; + that.currentVariable.uid = data.usr_uid; + } + + }); + + panelFilter = new PMUI.core.Panel({ + id: 'panelFilter', + layout: 'vbox', + items: [/*fieldC,*/ textField] + }); + + panel = new PMUI.core.Panel({ + id: 'paneldataGrid', + layout: 'vbox', + items: [panelFilter, dataGrid] + }); + + rc = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + console.log(response); + that.window = w; + dataGrid.setDataItems(response); + w.open(); + w.showFooter(); + w.addItem(panel); + panelFilter.setWidth(430); + textField.controls[0].onKeyUp = function () { + console.log(textField.controls[0].html.value); + dataGrid.filter(textField.controls[0].html.value); + }; + dataGrid.dom.toolbar.style.display = 'none'; + textField.dom.labelTextContainer.innerHTML = ''; + textField.dom.labelTextContainer.style.marginTop = 5; + panel.style.addProperties({'padding-left': 20}); + textField.dom.labelTextContainer.style.display = 'none'; + textField.controls[0].setWidth(200); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + rc.setBaseEndPoint('users').executeRestClient(); +}; + +UserPicker.prototype.close = function () { + if (this.window) { + this.window.close(); + this.window = null; + } +}; + +var CriteriaUserField = function (options) { + this.renderType = (options && options.renderType) || "text"; + PMUI.field.TextField.call(this, options); + this.process = null; + this.workspace = null; + this.buttonHTML = null; + this.rows = options.rows; + this.user_uid = null; + CriteriaUserField.prototype.init.call(this, options); +}; + +CriteriaUserField.prototype = new PMUI.field.TextField(); + +CriteriaUserField.prototype.setProcess = function (process) { + this.process = process; + return this; +}; + +CriteriaUserField.prototype.setWorkspace = function (workspace) { + this.workspace = workspace; + return this; +}; + +CriteriaUserField.prototype.init = function (options) { + var defaults = { + process: PMDesigner.project.projectId, + workspace: WORKSPACE + }; + jQuery.extend(true, defaults, options); + this.setProcess(defaults.process) + .setWorkspace(defaults.workspace); +}; + +CriteriaUserField.prototype.createVariablePicker = function () { + var vp = new UserPicker({ + relatedField: this, + processId: this.process + }); + return vp; +}; + +CriteriaUserField.prototype.setControls = function () { + if (this.controls.length) { + return this; + } + if (this.renderType === 'text') { + this.controls.push(new PMUI.control.TextControl()); + } else { + this.controls.push(new PMUI.control.TextAreaControl({style: {cssProperties: {resize: 'vertical'}}})); + } + return this; +}; + +CriteriaUserField.prototype.createCallBack = function () { + var that = this, oldValue, newValue, init = 0; + return { + success: function (variable) { + init = that.controls[0].html.selectionStart; + prevText = that.controls[0].html.value.substr(0, init); + lastText = that.controls[0].html.value.substr(that.controls[0].html.selectionEnd, that.controls[0].html.value.length); + newValue = variable.username; + + that.setValue(newValue); + that.user_uid = variable.uid; + that.controls[0].html.selectionEnd = init + variable.username.length; + } + }; +}; + +CriteriaUserField.prototype.createHTML = function () { + var button, that = this; + PMUI.field.TextField.prototype.createHTML.call(this); + + button = new PMUI.ui.Button({ + id: 'buttonCriteriaUserField', + text: '...', + handler: function () { + that.createVariablePicker().open(that.createCallBack()); + }, + style: { + cssProperties: { + background: '#2d3e50', + fontSize: 18, + paddingLeft: '15px', + paddingRight: '15px', + borderRadius: '4px', + verticalAlign: 'top' + } + } + }); + + this.buttonHTML = button; + $(this.helper.html).before(button.getHTML()) + this.buttonHTML.style.addProperties({"margin-left": "10px"}); + this.buttonHTML.html.tabIndex = -1; + + if (this.rows != null) + this.controls[0].setHeight(this.rows); + button.defineEvents(); + + return this.html; +}; + +// Overwrite original init function for FormItemFactory +PMUI.form.FormItemFactory.prototype.init = function () { + var defaults = { + products: { + "criteria": CriteriaUserField, + "field": PMUI.form.Field, + "panel": PMUI.form.FormPanel, + "text": PMUI.field.TextField, + "password": PMUI.field.PasswordField, + "dropdown": PMUI.field.DropDownListField, + "radio": PMUI.field.RadioButtonGroupField, + "checkbox": PMUI.field.CheckBoxGroupField, + "textarea": PMUI.field.TextAreaField, + "datetime": PMUI.field.DateTimeField, + "optionsSelector": PMUI.field.OptionsSelectorField, + "buttonField": PMUI.field.ButtonField, + "annotation": PMUI.field.TextAnnotationField + }, + defaultProduct: "panel" + }; + this.setProducts(defaults.products) + .setDefaultProduct(defaults.defaultProduct); +}; + +/** + * Class representing a Web Entry + * @param relatedShape + * @constructor + */ +var WebEntry = function (relatedShape) { + this.relatedShape = null; + this.groupType = null; + this.groupLabel = null; + this.stepsType = null; + this.actUid = null; + this.evenUid = null; + this.weeUid = null; + this.stepsAssigned = null; + this.elementAccordionOpen = null; + this.configWebEntry = null; + this.isNewWebEntry = null; + this.windowWebEntry = null; + this.windowAlternative = null; + this.tabForm = null; + this.tabProperties = null; + this.tabLink = null; + this.confirmWindow = null; + this.tabPanelWindow = null; + this.suggestUser = null; + this.stepsAssignTree = null; + this.stepsAssignAccordion = null; + this.labelsPanel = null; + this.userGuest = {}; + WebEntry.prototype.initialize.call(this, relatedShape); +}; +/** + * A module representing a Web Entry + **/ +WebEntry.prototype = { + /** + * Sets the actUid + * @param {string} actUid + */ + setActUid: function (actUid) { + this.actUid = actUid; + return this; + }, + + /** + * Sets the evenUid + * @param {string} evenUid + */ + setEvnUid: function (evenUid) { + this.evenUid = evenUid; + return this; + }, + + /** + * Sets the weeUid + * @param {string} weeUid + */ + setWeeUid: function (weeUid) { + this.weeUid = weeUid; + return this; + }, + + /** + * Sets the configWebEntry + * @param {object} configWebEntry + */ + setConfigWebEntry: function (configWebEntry) { + this.configWebEntry = configWebEntry; + return this; + }, + + /** + * Sets the isNewWebEntry + * @param {boolean} isNewWebEntry + */ + setIsNewWebEntry: function (isNewWebEntry) { + this.isNewWebEntry = isNewWebEntry; + return this; + }, + + /** + * Sets the windowWebEntry + * @param {object} windowWebEntry + */ + setWindowWebEntry: function (windowWebEntry) { + this.windowWebEntry = windowWebEntry; + return this; + }, + + /** + * Sets the windowAlternative + * @param {object} windowAlternative + */ + setWindowAlternative: function (windowAlternative) { + this.windowAlternative = windowAlternative; + return this; + }, + + /** + * Sets the relatedShape + * @param {object} relatedShape + */ + setRelatedShape: function (relatedShape) { + this.relatedShape = relatedShape; + return this; + }, + + /** + * Sets the tabForm + * @param {object} tabForm + */ + setTabForm: function (tabForm) { + this.tabForm = tabForm; + return this; + }, + + /** + * Sets the tabProperties + * @param {object} tabProperties + */ + setTabProperty: function (tabProperties) { + this.tabProperties = tabProperties; + return this; + }, + + /** + * Sets the tabLink + * @param {object} tabLink + */ + setTabLink: function (tabLink) { + this.tabLink = tabLink; + return this; + }, + + /** + * Sets the confirmWindow + * @param {object} confirmWindow + */ + setConfirmWin: function (confirmWindow) { + this.confirmWindow = confirmWindow; + return this; + }, + + /** + * Sets the tabPanelWindow + * @param {object} tabPanelWindow + */ + setTabPanelWindow: function (tabPanelWindow) { + this.tabPanelWindow = tabPanelWindow; + return this; + }, + + /** + * Sets the suggestUser + * @param {object} suggestUser + */ + setSuggestUser: function (suggestUser) { + this.suggestUser = suggestUser; + return this; + }, + + /** + * Sets the stepsAssignTree + * @param {object} stepsAssignTree + */ + setStepsTree: function (stepsAssignTree) { + this.stepsAssignTree = stepsAssignTree; + return this; + }, + + /** + * Sets the stepsAssignAccordion + * @param {object} stepsAssignAccordion + */ + setStepsAccordion: function (stepsAssignAccordion) { + this.stepsAssignAccordion = stepsAssignAccordion; + return this; + }, + + /** + * Sets the labelsPanel + * @param {object} labelsPanel + */ + setLabelPanel: function (labelsPanel) { + this.labelsPanel = labelsPanel; + return this; + }, + + /** + * Sets the userGuest + * @param userGuest + */ + setUserGuest: function (userGuest) { + this.userGuest = userGuest; + return this; + }, + + /** + * Get the userGuest + * @returns {Object} userGuest + */ + getUserGuest: function () { + return this.userGuest || {}; + }, + + /** + * Get the actUid value + * @returns {null|*|string} The actUid value + */ + getActUid: function () { + return this.actUid || ""; + }, + + /** + * Get the isNewWebEntry value + * @returns {null|*|boolean} The isNewWebEntry value + */ + getRelatedShape: function () { + return this.relatedShape || []; + }, + + /** + * Get the evenUid value + * @returns {null|*|string} The evenUid value + */ + getEvnUid: function () { + return this.evenUid || ""; + }, + + /** + * Get the weeUid value + * @returns {null|*|string} The weeUid value + */ + getWeeUid: function () { + return this.weeUid || ""; + }, + + /** + * Get the configWebEntry value + * @returns {*|null|Array} The configWebEntry value + */ + getConfigWebEntry: function () { + return this.configWebEntry || []; + }, + + /** + * Get the isNewWebEntry value + * @returns {null|*|boolean} The isNewWebEntry value + */ + getIsNewWebEntry: function () { + return this.isNewWebEntry || false; + }, + + /** + * Get the windowWebEntry value + * @returns {null|*} The windowWebEntry value + */ + getWindowWebEntry: function () { + return this.windowWebEntry || null; + }, + + /** + * Get the windowAlternative value + * @returns {*|null} The windowAlternative value + */ + getWindowAlternative: function () { + return this.windowAlternative || null; + }, + + /** + * Get the tabForm value + * @returns {*|null} The tabForm value + */ + getTabForm: function () { + return this.tabForm || null; + }, + + /** + * Get the tabProperties value + * @returns {null|*} The tabProperties value + */ + getTabProperty: function () { + return this.tabProperties || null; + }, + + /** + * Get the tablink value + * @returns {null|*} The tablink value + */ + getTabLink: function () { + return this.tabLink || null; + }, + + /** + * Get the confirmWindow value + * @returns {null|*} The confirmWindow value + */ + getConfirmWin: function () { + return this.confirmWindow || null; + }, + + /** + * Get the tabPanelWindow + * @returns {*|null} + */ + getTabPanelWindow: function () { + return this.tabPanelWindow || null; + }, + + /** + * get the suggestUser value + * @returns {*|null} The suggestUser value + */ + getSuggestUser: function () { + return this.suggestUser || null; + }, + + /** + * Sets the stepsAssignTree + * @returns {*|null} + */ + getStepsTree: function () { + return this.stepsAssignTree || null; + }, + + /** + * Get the stepsAssignAccordion value + * @returns {*|null} The stepsAssignAccordion value + */ + getStepsAccordion: function () { + return this.stepsAssignAccordion || null; + }, + + /** + * get the labelsPanel value + * @returns {null|*} The labelsPanel value + */ + getLabelPanel: function () { + return this.labelsPanel || null; + }, + + /** + * initialize App + * @param relatedShape + */ + initialize: function (relatedShape) { + this.groupType = [ + 'DYNAFORM', 'INPUT_DOCUMENT', + 'OUTPUT_DOCUMENT', 'EXTERNAL' + ]; + this.groupLabel = [ + 'Dynaform (s)'.translate(), 'Input Document (s)'.translate(), + 'OutPut Document (s)'.translate(), 'External (s)'.translate() + ]; + this.stepsType = { + 'DYNAFORM': 'Dynaform'.translate(), + 'INPUT_DOCUMENT': 'Input Document'.translate(), + 'OUTPUT_DOCUMENT': 'Output Document'.translate(), + 'EXTERNAL': 'External'.translate() + }; + + this.setRelatedShape(relatedShape) + .setEvnUid(relatedShape.evn_uid); + + if (this.getRelatedShape().getPorts().getFirst()) { + this.setActUid(this.getRelatedShape().getPorts().getFirst().getConnection().getDestPort().getParent() + .act_uid); + } + if (__env.USER_GUEST) { + $.extend(true, this.userGuest, __env.USER_GUEST); + } + this.stepsAssigned = new PMUI.util.ArrayList(); + this.elementAccordionOpen = new PMUI.util.ArrayList(); + }, + + /** + * Render form + * @returns {WebEntry} + */ + render: function () { + this.getWindow().addItem(this.getTabPanel()); + this.getWindow().open(); + this.getWindow().showFooter(); + this.initializeData(); + return this; + }, + + /** + * Populate Web Entry data + */ + initializeData: function () { + //Pupulate web entry data + this.getInstanceWebEntryData(); + this.setWebEntryConfiguration(); + this.initializeAccordionAndTreepanelData(); + }, + + /** + * Populate accordion and treepanel data + */ + initializeAccordionAndTreepanelData: function () { + var that = this; + //clear global array stepsAssigned + this.stepsAssigned.clear(); + //get accordion data + this.getAccordionData( + function (xhr, response) { + //populate data accordion tabForms + that.loadAccordionItems(response); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + //get getTreePanelData data + this.getTreePanelData( + function (xhr, response) { + //populate data treePanel tabForms + that.loadTreePanelData(response); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + this.addEventSortableInAccordionElements(); + this.addEventSortableInTreePanelElements(); + }, + + /** + * Get all dynaforms + * Execute restClient(GET/project/dynaforms) + * @param successCallback + * @param failureCallback + */ + getDynaforms: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'dynaforms', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get users + * Execute restClient(GET/users/uid_usr) + * @param uidUser + * @param successCallback + * @param failureCallback + */ + getUserData: function (uidUser, successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'users/' + uidUser, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).setBaseEndPoint("").executeRestClient(); + }, + + /** + * Get WebEntry Configuration + * Execute restClient(GET/web-entry-event/event/) + * Execute restClient(POST/web-entry-event/) + * @param successCallback + * @returns {Array} + */ + getWebEntryConfiguration: function (successCallback) { + var that = this, + restProxy = new PMRestClient({ + endpoint: 'web-entry-event/event/' + that.getEvnUid(), + typeRequest: "get", + functionSuccess: function (xhr, response) { + successCallback(response, false); + that.initializeSomeVariables(response, false); + }, + functionFailure: function (xhr, response) { + restProxy = new PMRestClient({ + endpoint: 'web-entry-event', + typeRequest: "post", + data: { + act_uid: that.getActUid(), + evn_uid: that.getEvnUid(), + wee_title: that.getEvnUid(), + we_type: "MULTIPLE", + we_authentication: "LOGIN_REQUIRED", + we_callback: "PROCESSMAKER", + we_callback_url: "", + we_show_in_new_case: "0", + usr_uid: that.getUserGuest().uid || '' + }, + functionSuccess: function (xhr, response) { + successCallback(response, true); + that.initializeSomeVariables(response, true); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + } + }); + restProxy.executeRestClient(); + return this; + }, + + /** + * Update data Web Entry Configuration + * Execute restClient(PUT/web-entry-event/weeuid) + * @param data + * @param successCallback + * @param failureCallback + * @returns {PMRestClient} + */ + updateWebEntryConfiguration: function (data, successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + this.weeUid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get Accordion Data (Tab Forms) + * Execute restClient(GET/steps, GET/step/triggers) + * @returns {Array} + */ + getAccordionData: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/steps', + method: 'GET' + }, { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/step/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).executeRestClient(); + }, + + /** + * Get TreePanel Data (TabForm) + * Execute restClient(GET/available-steps GET/triggers) + * @returns {Array} + */ + getTreePanelData: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/available-steps', + method: 'GET' + }, { + url: 'triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get steps Availables (TreePanel) + * Execute restClient(GET/available-steps) + * @param successCallback + * @param failureCallback + * @returns {Array} + */ + getStepAvailables: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/available-steps', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Load Skin and Languages + * Execute restClient(GET/system/languages GET/system/skins) + * @returns {Array} + */ + getSkinLanguage: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'system/languages', + method: 'GET' + }, { + url: 'system/skins', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).setBaseEndPoint("").executeRestClient(); + }, + + /** + * Delete the WebEntry configuration. + * @param successCallback + * @param failureCallback + */ + deleteWebEntryConfiguration: function (successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + this.weeUid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Generate webEntry Link + * @param weeUid + * @param successCallback + * @param failureCallback + */ + generateLink: function (weeUid, successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + weeUid + '/generate-link', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Creates an instance of the WebEntry class + * @returns {null} + */ + getInstanceWebEntryData: function () { + this.getWebEntryConfiguration( + function (webEntryEvent, isNew) { + if (isNew) { + webEntryEvent.we_type = 'SINGLE'; + webEntryEvent.we_authentication = 'ANONYMOUS'; + webEntryEvent.wee_url = ''; + webEntryEvent.wee_title = ''; + } + } + ); + return this; + }, + + /** + * Get Main Container Window + * @returns {PMUI.ui.Window} + */ + getWindow: function () { + if (this.getWindowWebEntry() === null) { + this.setWindowWebEntry(this.buildWindow()); + } + return this.getWindowWebEntry(); + }, + + /** + * Build Window Container + * @returns {PMUI.ui.Window} + */ + buildWindow: function () { + var that = this; + return new PMUI.ui.Window({ + id: 'windowWebEntry', + title: 'Web Entry'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + onBeforeClose: function () { + if (that.isNewWebEntry) { + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } else { + that.getWindow().close(); + } + that.getWindow().close(); + }, + buttonPanelPosition: 'bottom', + buttonsPosition: 'right', + buttons: [ + { + id: 'windowWebEntryButtonDelete', + text: 'Delete'.translate(), + handler: function () { + that.handlerDeleteWebEntry(); + }, + buttonType: "error" + }, + { + id: 'windowWebEntryButtonCancel', + text: 'Cancel'.translate(), + handler: function () { + if (that.isNewWebEntry) { + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } else { + that.getWindow().close(); + } + }, + buttonType: "error" + }, + { + id: 'windowWebEntryButtonSave', + text: 'Save'.translate(), + handler: function (e) { + that.checkUserGuest('saveConfig'); + }, + buttonType: 'success' + } + ] + }); + }, + + /** + * Return Second Window Container + * @returns {PMUI.ui.Window} + */ + getWindowAlternativeForm: function () { + if (this.getWindowAlternative() === null) { + this.setWindowAlternative(this.buildWindowAlternative()); + } + return this.getWindowAlternative(); + }, + + /** + * Build Second Window Container + * @returns {PMUI.ui.Window} + */ + buildWindowAlternative: function () { + return new PMUI.ui.Window({ + visibleFooter: true, + title: 'Trigger'.translate(), + footerAlign: 'right', + footerItems: [{ + text: "@@", + id: "secondaryWindow-criteria", + style: { + cssProperties: { + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + }, + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-cancel', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-save', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + } + }] + }); + }, + + /** + * Get TabPanel Container + * @returns {TabPanel} + */ + getTabPanel: function () { + if (this.getTabPanelWindow() === null) { + this.setTabPanelWindow(this.buildPanelWindow()); + } + return this.getTabPanelWindow(); + }, + + /** + * Build TabPanel (TabForms, TabProperties, TabLink) + * @returns {PMUI.panel.TabPanel} + */ + buildPanelWindow: function () { + return new PMUI.panel.TabPanel({ + id: 'windowWebEntryTabPanel', + width: DEFAULT_WINDOW_WIDTH - 50, + items: [ + { + id: 'tabForms', + title: 'Forms'.translate(), + panel: this.getTabForms() + }, + { + id: 'tabProperties', + title: 'Properties'.translate(), + panel: this.getTabProperties() + }, + { + id: 'tabLink', + title: 'Link'.translate(), + panel: this.getTabLinkForm() + } + ], + style: { + cssProperties: { + 'margin-left': '10px' + } + }, + itemsPosition: { + position: 'left' + } + }); + }, + + /** + * Get Panel TabForms + * @returns {Panel} + */ + getTabForms: function () { + if (this.getTabForm() === null) { + this.setTabForm(this.buildTabForms()); + } + return this.getTabForm(); + }, + + /** + * Build Tab Forms + * @returns {PMUI.core.Panel} + */ + buildTabForms: function () { + var that = this, + singleDynaform, + stepsMainContainer; + + singleDynaform = new PMUI.form.Form({ + id: 'singleDynaform', + width: DEFAULT_WINDOW_WIDTH - 220, + height: 180, + name: 'singleDynaform', + visibleHeader: false, + items: [ + { + id: 'singleDynaformRadio', + pmType: 'radio', + labelVisible: false, + value: 'SINGLE', + name: 'options', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'singleDynaform', + label: 'Single Dynaform'.translate(), + value: 'SINGLE', + selected: true + } + ], + onChange: function (newVal, oldVal) { + that.weeFormModeChange(newVal, oldVal); + }, + labelWidth: '0%' + }, + { + id: 'weeSelectDynaform', + name: 'tabFormsDropdownDyanform', + pmType: 'dropdown', + label: 'Dynaform'.translate(), + helper: 'Select Dynaform use in case.'.translate(), + required: true, + controlsWidth: 400, + labelWidth: '25%', + style: { + cssProperties: { + 'padding-left': '100px' + } + }, + options: [ + { + label: 'Select Dynaform'.translate(), + value: '' + } + ] + + }, + { + id: 'multipleStepsRadio', + pmType: 'radio', + labelVisible: false, + value: '', + name: 'options', + required: false, + controlPositioning: 'vertical', + maxDirectionOptions: 4, + options: [ + { + id: 'multipleSteps', + label: 'Multiple Steps'.translate(), + value: 'MULTIPLE' + } + ], + onChange: function (newVal, oldVal) { + that.weeFormModeChange(newVal, oldVal); + }, + labelWidth: '0%' + + } + ] + }); + + stepsMainContainer = new PMUI.core.Panel({ + id: 'stepsMainContainer', + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH - 220, + items: [ + that.getStepsAssignTree(), + that.getStepsAssignAccordion() + ] + }); + + return new PMUI.core.Panel({ + id: 'mainContainer', + layout: 'vbox', + width: DEFAULT_WINDOW_WIDTH - 220, + items: [ + singleDynaform, + that.getLabelsPanel(), + stepsMainContainer + ] + }); + }, + + /** + * Get Panel TabProperties + * @returns {Panel} + */ + getTabProperties: function () { + if (this.getTabProperty() === null) { + this.setTabProperty(this.buildTabProperties()); + } + return this.getTabProperty(); + }, + + /** + * Build TabProperties + * @returns {PMUI.core.Panel} + */ + buildTabProperties: function () { + var that = this, + propertiesForm; + + propertiesForm = new PMUI.form.Form({ + id: 'idTabFormProperties', + width: DEFAULT_WINDOW_WIDTH - 220, + visibleHeader: false, + items: [ + { + id: 'tabPropertiesWebEntryTitle', + pmType: 'text', + name: 'tabPropertiesWebEntryTitle', + valueType: 'string', + label: 'Web Entry Title'.translate(), + placeholder: 'Enter a title displayed on web entry window (if applies)'.translate(), + helper: 'Enter a title displayed on web entry window (if applies).'.translate(), + required: false, + controlsWidth: 458, + labelWidth: '23%' + }, + { + id: 'tabPropRadioAuthentication', + pmType: 'radio', + labelVisible: true, + label: 'Authentication'.translate(), + value: 'ANONYMOUS', + name: 'authentication', + required: true, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'tabPropertiesOptionRadioAnonymous', + label: 'Anonymous'.translate(), + value: 'ANONYMOUS', + selected: false + } + ], + onChange: function (newVal, oldVal) { + that.anonimusProcedure(newVal, oldVal); + }, + labelWidth: '23%' + }, + { + id: 'tabPropertiesRequireUserLogin', + pmType: 'radio', + labelVisible: false, + value: 'LOGIN_REQUIRED', + required: false, + name: 'authentication', + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'tabPropertiesRadioRequireUserLogin', + label: 'Require user login'.translate(), + value: 'LOGIN_REQUIRED', + selected: false + } + ], + onChange: function (newVal, oldVal) { + that.loginRequired(newVal, oldVal); + }, + labelWidth: '23%' + }, + { + id: 'tabPropertiesHideLoogedInformationBar', + pmType: 'checkbox', + name: 'tabPropertiesHideLoogedInformationBar', + labelVisible: false, + disabled: true, + options: [ + { + id: 'hideLoogedInformationBar', + label: 'Hide Logged Information Bar'.translate(), + value: '1', + selected: false + } + ], + style: { + cssProperties: { + 'padding-left': '50px' + } + } + }, + { + id: 'tabPropertiesRadioCallback', + pmType: 'radio', + labelVisible: true, + label: 'Callback Action'.translate(), + value: 'PROCESSMAKER', + required: true, + disabled: false, + controlPositioning: 'vertical', + labelPosition: 'left', + helper: 'Callback Action...'.translate(), + maxDirectionOptions: 4, + options: [ + { + id: 'redirectPM', + label: 'Redirect to ProcessMaker predefined response page'.translate(), + value: 'PROCESSMAKER', + selected: true + }, + { + id: 'redirectURL', + label: 'Redirect to custom URL'.translate(), + value: 'CUSTOM' + }, + { + id: 'redirectCustom', + label: 'Redirect to custom URL and clear login info'.translate(), + value: 'CUSTOM_CLEAR' + } + ], + onChange: function (newVal, oldVal) { + that.callbackActionChange(newVal, oldVal); + + }, + labelWidth: '23%' + }, + new CriteriaField({ + id: 'criteriaFieldCustomUrl', + pmType: 'text', + name: 'criteriaFieldCustomUrl', + label: 'Custom URL'.translate(), + placeholder: 'Enter a valid URL to be redirected when entry will be completed'.translate(), + labelWidth: '23%', + controlsWidth: 455, + required: true, + disabled: true + }), + { + id: 'showInNewCase', + pmType: 'checkbox', + name: 'showInNewCase', + label: 'Show task in New Case'.translate(), + labelVisible: true, + options: [ + { + id: 'showTaskInNewCase', + value: 'showCase', + selected: false + } + ], + onChange: function (newValue, oldValue) { + this.setValue(newValue); + } + } + ] + }); + + $(propertiesForm.getItem('tabPropRadioAuthentication').getHTML()) + .append($(that.getSuggestField().createHTML())); + + return propertiesForm; + }, + + /** + * Get Panel TabLink + * @returns {Panel} + */ + getTabLinkForm: function () { + if (this.getTabLink() === null) { + this.setTabLink(this.buildTabLink()); + } + return this.getTabLink(); + }, + + /** + * Build TabLink + * @returns {PMUI.core.Panel} + */ + buildTabLink: function () { + var that = this, + tfromLink; + + tfromLink = new PMUI.form.Form({ + id: 'idTabFormLink', + width: DEFAULT_WINDOW_WIDTH - 220, + visibleHeader: false, + items: [ + { + id: 'tabLinkRadioGeneration', + pmType: 'radio', + labelVisible: true, + label: 'Link Generation'.translate(), + value: 'DEFAULT', + name: 'options', + required: true, + controlPositioning: 'vertical', + labelPosition: 'left', + helper: 'Link Generation'.translate(), + controlsWidth: 485, + labelWidth: '24.5%', + maxDirectionOptions: 3, + options: [ + { + id: 'generateLinkDefaultValues', + label: 'Generate link using workspace default values (skin, language)'.translate(), + value: 'DEFAULT', + selected: 'true' + }, + { + id: 'advancedLinkGeneration', + label: 'Advanced link generation'.translate(), + value: 'ADVANCED' + } + ], + onChange: function (newVal) { + that.linkGenerationOnChange(newVal); + }, + labelWidth: '18%' + }, + { + id: 'tabLinkDropdownSkin', + name: 'tabLinkDropdownSkin', + pmType: 'dropdown', + label: 'Skin'.translate(), + helper: 'Select a Skin.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: '24.5%', + onChange: function () { + that.setLinkText(tfromLink, ''); + }, + options: [ + { + label: 'Select a Skin'.translate(), + value: '' + } + ] + }, + { + id: 'tabLinkDropdownLanguage', + name: 'tabLinkDropdownLanguage', + pmType: 'dropdown', + label: 'Language'.translate(), + helper: 'Select a language.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: '24.5%', + onChange: function () { + that.setLinkText(tfromLink, ''); + }, + options: [ + { + label: 'Select a language'.translate(), + value: '' + } + ] + }, + { + id: 'tablinkTextCustomDomain', + pmType: 'text', + name: 'tablinkTextCustomDomain', + valueType: 'string', + label: 'Custom Hostname'.translate(), + placeholder: 'https://example.com:8080'.translate(), + helper: 'Protocol and Hostname, port is optional.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: "24.5%", + validators: [ + { + pmType: "regexp", + criteria: /^(https?:\/\/)?(((\d{1,3}\.){3}\d{1,3})|(([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?))(:\d+)?$/i, + errorMessage: 'Enter a Protocol and Hostname valid value.'.translate() + } + ], + onChange: function () { + that.setLinkText(tfromLink, ''); + } + }, + { + id: 'panelLinkForm', + pmType: 'panel', + layout: 'hbox', + required: true, + width: '155px', + style: { + cssProperties: { + 'margin-left': '-10px', + 'margin-top': '-10px' + } + }, + items: [ + { + pmType: 'annotation', + text: 'Web Entry URL:'.translate(), + id: 'webEntryLinkLabel', + required: true, + name: 'webEntryLinkLabel' + }, + { + pmType: 'annotation', + id: 'webEntryLink', + name: 'webEntryLink', + text: '', + required: true, + textType: 1, + style: { + cssProperties: { + 'margin-left': '-173px' + } + } + } + ] + }, + new PMUI.field.ButtonField({ + id: 'buttonFieldGenerateLink', + pmType: 'buttonField', + value: 'Generate Link'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 180, + proportion: 0.6, + handler: function (field) { + that.checkUserGuest('generateLink'); + }, + buttonType: 'success', + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '10px', + 'padding-right': '0px', + 'padding-bottom': '1px', + 'padding-left': '130px' + } + } + }) + ] + }); + + tfromLink.getItem('buttonFieldGenerateLink').getControl(0).button.setButtonType('success'); + + return tfromLink; + }, + + /** + * Get MessageWindow Container + * @returns {PMUI.ui.MessageWindow} + */ + getConfirmWindow: function () { + if (this.getConfirmWin() === null) { + this.setConfirmWin(this.buildConfirmWindow()); + } + return this.getConfirmWin(); + }, + + /** + * Build MessageWindow + * @returns {PMUI.ui.MessageWindow} + */ + buildConfirmWindow: function () { + return new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: '', + message: '', + footerItems: [ + { + id: 'confirmWindow-footer-no', + text: 'No'.translate(), + visible: true, + buttonType: 'error' + }, { + id: 'confirmWindow-footer-yes', + text: 'Yes'.translate(), + visible: true, + buttonType: 'success' + } + ], + visibleFooter: true + }); + }, + + /** + * Handler button for delete web entry config + */ + handlerDeleteWebEntry: function () { + var that = this, + confirmWindow, + yesButton, + noButton; + confirmWindow = that.getConfirmWindow() + .setMessage('Are you sure you want to delete the Web Entry configuration?'.translate()); + yesButton = that.getConfirmWindow().footer.getItem('confirmWindow-footer-yes'); + yesButton.setHandler(function () { + confirmWindow.close(); + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + noButton = that.getConfirmWindow().footer.getItem('confirmWindow-footer-no'); + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + that.getConfirmWindow().open(); + return this; + }, + + /** + * Handler button for save web entry config + * @param method + */ + checkUserGuest: function (method) { + var title = 'Web Entry Anonymous Authentication'.translate(), + message = ('Current selected user to act as anonymous will be replaced by the Guest user. ' + + 'This action cannot be undone. Do you want to proceed?').translate(); + + //Validate the data before saving the configuration or generate the link + if (this.isValidWebEntryData(method)) { + (method === 'saveConfig') ? this.handlerSaveButton(message, title) : this.handlerGenerateLinkButton(message, title); + } + return this; + }, + + /** + * Check userGuestUID and save Config + * @param message + * @param title + * @returns {WebEntry} + */ + handlerSaveButton: function (message, title) { + var that = this, + messageWindow = this.getConfirmWindow(); + //Validation is done to be compatible with older versions of webEntry (Now exist guest-type user). + if (this.getUserGuest().uid && this.getSuggestField().value !== this.getUserGuest().uid) { + messageWindow.setMessage(message); + messageWindow.setTitle(title); + + //handler for cancel button + messageWindow.footer.getItem('confirmWindow-footer-no').setHandler(function () { + messageWindow.close(); + }); + + //handler for yes button + messageWindow.footer.getItem('confirmWindow-footer-yes').setHandler(function () { + messageWindow.close(); + that.getSuggestField().set('value', that.getUserGuest().uid); + that.saveWebEntryConfiguration( + function () { + that.getWindow().close(); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + messageWindow.open(); + } else { + //For new configurations we save the configuration without any GUEST user validation. + this.saveWebEntryConfiguration( + function () { + that.getWindow().close(); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } + return this; + }, + + /** + * Check userGuestUID and generate webEntry Link + * @param message + * @param title + * @returns {WebEntry} + */ + handlerGenerateLinkButton: function (message, title) { + var that = this, + formLink = this.getTabLinkForm(), + messageWindow = this.getConfirmWindow(); + //Validation is done to be compatible with older versions of webEntry (Now exist guest-type user). + if (this.getUserGuest().uid && this.getSuggestField().value !== this.getUserGuest().uid) { + messageWindow.setMessage(message); + messageWindow.setTitle(title); + + //handler for cancel button + messageWindow.footer.getItem('confirmWindow-footer-no').setHandler(function () { + messageWindow.close(); + }); + //handler for yes button + + messageWindow.footer.getItem('confirmWindow-footer-yes').setHandler(function () { + messageWindow.close(); + that.getSuggestField().set('value', that.getUserGuest().uid); + that.setLinkText(formLink, ''); + //save Web Entry Configuration + that.saveWebEntryConfiguration( + function (xhr, response) { + that.getConfigWebEntry().usr_uid = response.usr_uid || that.getConfigWebEntry().usr_uid; + //generate webEntry Link + that.generateLink( + that.getWeeUid(), + function (xhr, response) { + that.setLinkText(formLink, (response.link) ? response.link : ''); + that.initializeAccordionAndTreepanelData(); + that.getSuggestField().html.find("input") + .val(that.getUserGuest().firstname + " " + "(" + that.getUserGuest().username + ")"); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + messageWindow.open(); + } else { + //For new configurations we generate the webEntry Link without any GUEST user validation. + this.saveWebEntryConfiguration( + function () { + that.generateLink( + that.getWeeUid(), + function (xhr, response) { + that.setLinkText(formLink, (response.link) ? response.link : ''); + that.initializeAccordionAndTreepanelData(); + }, + function (xhr, response) { + that.setLinkText(formLink, ''); + PMDesigner.msgWinError(response.error.message); + } + ); + }, + function (xhr, response) { + that.setLinkText(formLink, ''); + PMDesigner.msgWinError(response.error.message); + } + ); + } + return this; + }, + + /** + * Get Steps AssignAccordion + * @returns {PMUI.panel.AccordionPanel} + */ + getStepsAssignAccordion: function () { + if (this.getStepsAccordion() === null) { + this.setStepsAccordion(this.buildStepsAssignAccordion()); + } + return this.getStepsAccordion(); + }, + + /** + * Build Steps Assign Accordion + * @returns {PMUI.panel.AccordionPanel} + */ + buildStepsAssignAccordion: function () { + var that = this; + return new PMUI.panel.AccordionPanel({ + id: 'stepsAssignAccordion', + multipleSelection: true, + hiddenTitle: true, + proportion: 1.5, + style: { + cssProperties: { + margin: '0px 0px 0px 0px' + }, + cssClasses: ['mafe-border-panel'] + }, + listeners: { + select: function (accordionItem, event) { + var buttonExpand, buttonCollapse, itemsAccod; + itemsAccod = that.getStepsAssignAccordion().items; + if (accordionItem.collapsed) { + if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { + that.elementAccordionOpen.remove(accordionItem); + } + } else { + if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { + that.elementAccordionOpen.insert(accordionItem); + } + } + buttonCollapse = that.getLabelsPanel().getItem('collapse-button'); + buttonExpand = that.getLabelsPanel().getItem('expand-button'); + if (that.elementAccordionOpen.getSize() === 0) { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(true); + } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { + buttonExpand.setDisabled(true); + buttonCollapse.setDisabled(false); + } else { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(false); + } + } + } + }); + }, + + /** + * Get steps AssignTree + * @returns {PMUI.core.Panel} + */ + getStepsAssignTree: function () { + if (this.getStepsTree() === null) { + this.setStepsTree(this.buildStepsAssignTree()); + } + return this.getStepsTree(); + }, + + /** + * Build steps AssignTree + * @returns {PMUI.panel.TreePanel} + */ + buildStepsAssignTree: function () { + return new PMUI.panel.TreePanel({ + id: 'stepsAssignTree', + proportion: 0.5, + height: 475, + filterable: true, + autoBind: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nodeDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true, + collapsed: false, + itemsDataBind: 'items', + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + behavior: 'drag' + }, + style: { + cssProperties: { + margin: '0px 0px 0px 0px', + float: 'left', + overflow: 'auto' + }, + cssClasses: ['mafe-border-panel'] + } + }); + }, + + /** + * Get Label Panel + * @returns {PMUI.core.Panel} + */ + getLabelsPanel: function () { + if (this.getLabelPanel() === null) { + this.setLabelPanel(this.buildLabelPanel()); + } + return this.getLabelPanel(); + }, + + /** + * Build Label Panel + * @returns {PMUI.core.Panel} + */ + buildLabelPanel: function () { + var that = this; + return new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH - 220, + layout: "hbox", + items: [ + new PMUI.field.TextAnnotationField({ + text: 'Available Elements'.translate(), + proportion: 1.12, + text_Align: 'center' + }), + new PMUI.field.TextAnnotationField({ + text: 'Assigned Elements (Drop here)'.translate(), + proportion: 1.3, + text_Align: 'center' + }), + new PMUI.ui.Button({ + buttonType: 'link', + text: 'Expand all'.translate(), + id: 'expand-button', + proportion: 1.2, + handler: function () { + that.expandAndCollapseHandler('collapse-button', 'expand-button'); + } + }), + new PMUI.ui.Button({ + buttonType: 'link', + text: 'Collapse all'.translate(), + id: 'collapse-button', + proportion: 1.1, + disabled: true, + handler: function () { + that.expandAndCollapseHandler('expand-button', 'collapse-button'); + } + }) + ] + }); + }, + + /** + * Get SuggestField Control + * @returns {SuggestField} + */ + getSuggestField: function () { + if (this.getSuggestUser() === null) { + this.setSuggestUser(this.createSugesstField()); + } + return this.getSuggestUser(); + }, + + /** + * Create Field Suggest (User) + * @returns {SuggestField} + */ + createSugesstField: function () { + return new SuggestField({ + id: 'idSuggestUser', + label: 'Users'.translate(), + width: 450, + placeholder: 'Suggest users'.translate(), + required: true, + disabled: true, + helper: 'When the form is submitted a new case is created with this user account.'.translate(), + dynamicLoad: { + data: [{ + key: 'usr_uid', + label: ['usr_firstname', 'usr_lastname', '(', 'usr_username', ')'] + }], + keys: { + url: HTTP_SERVER_HOSTNAME + '/api/1.0/' + WORKSPACE, + accessToken: credentials.access_token, + endpoints: [{ + method: 'GET', + url: 'users' + }] + } + } + }); + }, + + /** + * Generate Web Entry Link + * @param formLink + * @param linkText + */ + setLinkText: function (formLink, linkText) { + formLink.getItem('panelLinkForm').getItem('webEntryLink') + .setText('' + linkText + ''); + return this; + }, + + /** + * Initialize Some Variables for web Entry (weeUId, actUid, evnUid, response, isNewWebEntry) + * @param response + * @param newWebEntry + */ + initializeSomeVariables: function (response, newWebEntry) { + this.setWeeUid(response.wee_uid) + .setActUid(response.act_uid) + .setEvnUid(response.evn_uid) + .setConfigWebEntry(response) + .setIsNewWebEntry(newWebEntry); + return this; + }, + + /** + * Collapse and Expand Accordion Handler + * @param enableItem + * @param disableItem + */ + expandAndCollapseHandler: function (enableItem, disableItem) { + var items, + i, + item; + items = this.getStepsAssignAccordion().getItems(); + this.getLabelsPanel().getItem(enableItem).setDisabled(false); + this.getLabelsPanel().getItem(disableItem).setDisabled(true); + if (enableItem === 'collapse-button') { + this.elementAccordionOpen.clear(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + item.expand(); + this.elementAccordionOpen.insert(item); + } + } else { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + this.elementAccordionOpen.remove(item); + item.collapse(); + } + } + }, + + /** + * Disable MultipleSteps or Single Dynaform (tabForms) + * @returns {disableMultipleSteps} + */ + weeFormModeChange: function (newVal, oldVal) { + if (newVal === 'SINGLE') { + this.disableMultipleSteps('SINGLE'); + } else { + this.disableSingleDynaform('MULTIPLE'); + this.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform').hideMessage(); + this.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform') + .getControl(0).style.removeClasses(['error']); + } + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Disable MultipleSteps (tabForms) + * @param singleMultiple + * @returns {WebEntry} + */ + disableMultipleSteps: function (singleMultiple) { + var singleDyna = this.getTabForms().getItem('singleDynaform'); + singleDyna.getItem('multipleStepsRadio').setValue(''); + singleDyna.getItem('weeSelectDynaform').enable(); + singleDyna.getItem('weeSelectDynaform').setRequired(true); + singleDyna.getItem('singleDynaformRadio').setValue(singleMultiple); + singleDyna.getItem('singleDynaformRadio').getControl(0).select(); + //Hide step panel + this.getLabelsPanel().setVisible(false); + this.getTabForms().getItem('stepsMainContainer').setVisible(false); + return this; + }, + + /** + * Disable Form SingleDynaform (tabForms) + * @param singleMultiple + * @returns {WebEntry} + */ + disableSingleDynaform: function (singleMultiple) { + var singleDyna = this.getTabForms().getItem('singleDynaform'); + singleDyna.getItem('singleDynaformRadio').setValue(''); + singleDyna.getItem('weeSelectDynaform').disable(); + singleDyna.getItem('weeSelectDynaform').setRequired(false); + singleDyna.getItem('multipleStepsRadio').setValue(singleMultiple); + singleDyna.getItem('multipleStepsRadio').getControl(0).select(); + //Show step panel + this.getLabelsPanel().setVisible(true); + this.getTabForms().getItem('stepsMainContainer').setVisible(true); + return this; + }, + + /** + * Change handler + * @param newValue + * @param oldValue + * @returns {loginRequired} + */ + anonimusProcedure: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(), + //The Callback Actions (PROCESSMAKER is 0, CUSTOM is 1, and CUSTOM_CLEAR is 2) + callbackAction = 2; + propertiesForm.getItem('tabPropertiesRequireUserLogin').setValue('[]'); + propertiesForm.getItem('tabPropertiesHideLoogedInformationBar').disable(); + propertiesForm.getItem('tabPropRadioAuthentication').setRequired(true); + this.getSuggestField().setRequired(true); + this.getSuggestField().hideMessageRequired(); + propertiesForm.getItem('tabPropertiesRadioCallback').disableOption(callbackAction); + if (propertiesForm.getItem('tabPropertiesRadioCallback').getValue() === 'CUSTOM_CLEAR') { + propertiesForm.getItem('tabPropertiesRadioCallback').getControl(callbackAction).deselect(); + propertiesForm.getItem('tabPropertiesRadioCallback').setValue(''); + } + propertiesForm.getItem('criteriaFieldCustomUrl').disable(); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.disable(); + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Change chandler + * @param newValue + * @param oldValue + * @returns {loginRequired} + */ + loginRequired: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(), + //The Callback Actions (PROCESSMAKER is 0, CUSTOM is 1, and CUSTOM_CLEAR is 2) + callbackAction = 2; + propertiesForm.getItem('tabPropRadioAuthentication').setValue('[]'); + propertiesForm.getItem('tabPropRadioAuthentication').setRequired(false); + + this.getSuggestField().setRequired(false); + this.getSuggestField().hideMessageRequired(); + propertiesForm.getItem('tabPropertiesHideLoogedInformationBar').enable(); + propertiesForm.getItem('tabPropertiesRadioCallback').enableOption(callbackAction); + this.callbackActionChange(propertiesForm.getItem('tabPropertiesRadioCallback').getValue(), ''); + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Change handler + * @param newValue + * @param oldValue + * @returns {callbackActionChange} + */ + callbackActionChange: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(); + propertiesForm.getItem("tabPropertiesRadioCallback").setValue(newValue); + switch (newValue) { + case 'PROCESSMAKER': + propertiesForm.getItem('criteriaFieldCustomUrl').disable(); + propertiesForm.getItem('criteriaFieldCustomUrl').setRequired(false); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.disable(); + break; + case 'CUSTOM': + case 'CUSTOM_CLEAR': + propertiesForm.getItem('criteriaFieldCustomUrl').enable(); + propertiesForm.getItem('criteriaFieldCustomUrl').setRequired(true); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.enable(); + break; + } + return this; + }, + + /** + * Change handler + * @param newValue + * @returns {linkGenerationOnChange} + */ + linkGenerationOnChange: function (newValue) { + var required, + skin, + language, + domain, + tfromLink; + tfromLink = this.getTabLinkForm(); + required = newValue === 'ADVANCED'; + skin = tfromLink.getItem('tabLinkDropdownSkin'); + language = tfromLink.getItem('tabLinkDropdownLanguage'); + domain = tfromLink.getItem('tablinkTextCustomDomain'); + this.setLinkText(tfromLink, ''); + skin.setRequired(required); + language.setRequired(required); + domain.setRequired(required); + if (required) { + skin.enable(); + language.enable(); + domain.enable(); + } else { + skin.disable(); + domain.hideMessage(); + language.disable(); + domain.disable(); + domain.getControl(0).style.removeClasses(['error']); + } + return this; + }, + + /** + * Save webEntry Configuration + * @param successCallback + * @param failureCallback + */ + saveWebEntryConfiguration: function (successCallback, failureCallback) { + var data, + //tabs window web entry + tabProperties = this.getTabPanel().getItem('tabProperties'), + tabLink = this.getTabPanel().getItem('tabLink'), + //form tabs + dataTabSingleDyn = this.getTabForms().getItem('singleDynaform'), + dataTabProperties = tabProperties.getPanel('idTabProperties'), + dataTabLink = tabLink.getPanel('idTabLink'); + + //Prepare Data + data = this.prepareData(dataTabSingleDyn, dataTabProperties, dataTabLink); + //Save web Entry configuration + this.updateWebEntryConfiguration(data, successCallback, failureCallback); + return this; + }, + + /** + * Validate Web Entry Data + * @param method + */ + isValidWebEntryData: function (method) { + var valid = true, + //tabs window web entry + tabForm = this.getTabPanel().getItem('tabForms'), + tabProperties = this.getTabPanel().getItem('tabProperties'), + tabLink = this.getTabPanel().getItem('tabLink'), + //form tabs + dataTabSingleDyn = this.getTabForms().getItem('singleDynaform'), + dataTabProperties = tabProperties.getPanel('idTabProperties'), + dataTabLink = tabLink.getPanel('idTabLink'), + //selected tab + selectedTab = null; + + // validate form tab + if (dataTabSingleDyn instanceof PMUI.form.Form) { + valid = valid && dataTabSingleDyn.isValid(); + selectedTab = !valid && !selectedTab ? tabForm : selectedTab; + } + //validate property tab + if (dataTabProperties instanceof PMUI.form.Form) { + valid = valid && dataTabProperties.isValid(); + selectedTab = !valid && !selectedTab ? tabProperties : selectedTab; + } + //validate suggestField + if (!this.getSuggestField().isValid()) { + this.getSuggestField().showMessageRequired(); + valid = valid && this.getSuggestField().isValid(); + selectedTab = !valid && !selectedTab ? tabProperties : selectedTab; + } + //validate link Tab + if (dataTabLink instanceof PMUI.form.Form) { + valid = valid && dataTabLink.isValid(); + selectedTab = !valid && !selectedTab ? tabLink : selectedTab; + } + if (!valid) { + selectedTab.select(); + } + //validate Link Generate Button + if (!$(dataTabLink.getItem('panelLinkForm').getItem('webEntryLink').text).attr('href') && + method !== 'generateLink') { + PMDesigner.msgFlash('Please press the \"Generate Link\" button.'.translate(), + this.getWindow(), 'error', 3000, 5); + valid = false; + tabLink.select(); + } + return valid; + }, + + /** + * Prepare Data + * @param dataTabSingleDyn + * @param dataTabProperties + * @param dataTabLink + */ + prepareData : function (dataTabSingleDyn, dataTabProperties, dataTabLink) { + var data = {}; + data['act_uid'] = this.getActUid(); + data['evn_uid'] = this.getEvnUid(); + data['wee_title'] = this.getEvnUid(); + data['we_type'] = (dataTabSingleDyn.getItem('singleDynaformRadio').getValue()) ? 'SINGLE' : 'MULTIPLE'; + data['dyn_uid'] = (data['we_type'] === 'SINGLE') ? dataTabSingleDyn.getItem('weeSelectDynaform') + .getValue() : ''; + data['we_custom_title'] = dataTabProperties.getItem('tabPropertiesWebEntryTitle').getValue(); + data['we_authentication'] = dataTabProperties.getItem('tabPropRadioAuthentication').getValue() === '[]' ? + 'LOGIN_REQUIRED' : 'ANONYMOUS'; + data['usr_uid'] = this.getSuggestField().value; + data['we_hide_information_bar'] = dataTabProperties.getItem('tabPropertiesHideLoogedInformationBar') + .getValue() === '[]' ? '0' : '1'; + data['we_callback'] = dataTabProperties.getItem('tabPropertiesRadioCallback').getValue(); + data['we_callback_url'] = (data['we_callback'] !== 'PROCESSMAKER') ? + dataTabProperties.getItem('criteriaFieldCustomUrl').getValue() : ''; + data['we_link_generation'] = dataTabLink.getItem('tabLinkRadioGeneration').getValue(); + data['we_link_skin'] = dataTabLink.getItem('tabLinkDropdownSkin').getValue(); + data['we_link_language'] = dataTabLink.getItem('tabLinkDropdownLanguage').getValue(); + data['we_link_domain'] = (data['we_link_generation'] === 'ADVANCED') ? + dataTabLink.getItem('tablinkTextCustomDomain').getValue() : ''; + data['we_show_in_new_case'] = (dataTabProperties.getItem('showInNewCase').getValue() === '["showCase"]') ? 1 : 0; + return data; + }, + + /** + * Populate all tabPanels (TabForms, TabProperties, TabLink) with data config + * return void + */ + setWebEntryConfiguration: function () { + this.setConfigDataTabForms(); + this.setConfigDataTabProperties(); + this.setConfigDataTabLink(); + this.getWindow().getItem('windowWebEntryTabPanel').getItem('tabForms').select(); + return this; + }, + + /** + * Load and populate Dynaforms Items + * @returns {*} + */ + setConfigDataTabForms: function () { + var that = this, + i, + data, + options = [], + dynaformsControl, + dynaforms = []; + + //execute Rest (get Dynaforms) + this.getDynaforms( + function (xhr, response) { + dynaforms = response[0].response; + //get Controls tab-Forms + dynaformsControl = that.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform'); + + //Set data Dropdown Single Dynaform + for (i = 0; i < dynaforms.length; i += 1) { + data = {}; + data.label = dynaforms[i]['dyn_title']; + data.value = dynaforms[i]['dyn_uid']; + if (that.getConfigWebEntry().dyn_uid === data.value && + that.getConfigWebEntry().evn_uid === that.getRelatedShape()['evn_uid']) { + data.selected = true; + } + options.push(data); + } + dynaformsControl.setOptions(options); + + //set Disable/Enable single or multiple steps + (that.getConfigWebEntry().we_type === 'SINGLE') ? + that.disableMultipleSteps(that.getConfigWebEntry().we_type) : + that.disableSingleDynaform(that.getConfigWebEntry().we_type); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + + /** + * TabProperties Panel + * Assigns values to tabProperties fields + */ + setConfigDataTabProperties: function () { + var that = this, + webEntryTitle, + radioAuthentication, + radioRequiredLogin, + informationBar, + radioCollback, + customUrl, + user, + showInNewCase; + + //get Controls Tab-Properties + this.getTabPanel().getItem('tabProperties').select(); + webEntryTitle = this.getTabProperties().getItem('tabPropertiesWebEntryTitle'); + radioAuthentication = this.getTabProperties().getItem('tabPropRadioAuthentication'); + radioRequiredLogin = this.getTabProperties().getItem('tabPropertiesRequireUserLogin'); + radioCollback = this.getTabProperties().getItem('tabPropertiesRadioCallback'); + customUrl = this.getTabProperties().getItem('criteriaFieldCustomUrl'); + informationBar = this.getTabProperties().getItem('tabPropertiesHideLoogedInformationBar'); + showInNewCase = this.getTabProperties().getItem('showInNewCase'); + + //set webentry Title + webEntryTitle.setValue(this.getConfigWebEntry().we_custom_title); + + //Loggin required or Anonymous + radioCollback.setValue(this.getConfigWebEntry().we_callback); + if (this.getConfigWebEntry().we_authentication === 'LOGIN_REQUIRED') { + radioRequiredLogin.getControl(0).select(); + radioRequiredLogin.setValue(this.getConfigWebEntry().we_authentication); + this.loginRequired(); + } else { + radioAuthentication.getControl(0).select(); + radioAuthentication.setValue(this.getConfigWebEntry().we_authentication); + this.anonimusProcedure(); + } + + //set value suggest user + this.getSuggestField().html.find('input').val(''); + this.getConfigWebEntry().usr_uid = this.getConfigWebEntry().usr_uid || this.getUserGuest().uid; + if (this.getConfigWebEntry().usr_uid) { + this.getUserData( + this.getConfigWebEntry().usr_uid, + function (xhr, response) { + user = response[0].response; + that.getSuggestField().html.find("input").val(user.usr_firstname + " " + + user.usr_lastname + " " + "(" + user.usr_username + ")"); + that.getSuggestField().set("value", user.usr_uid); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } + + //set Hide Logged Information Bar + if (this.getConfigWebEntry().we_hide_information_bar === '1') { + informationBar.setValue('["1"]'); + informationBar.getControl(0).select(); + } else { + informationBar.setValue('[]'); + informationBar.getControl(0).deselect(); + } + + //set Callback Action + switch (this.getConfigWebEntry().we_callback) { + case 'PROCESSMAKER': + radioCollback.getControl(0).select(); + break; + case 'CUSTOM': + radioCollback.getControl(1).select(); + break; + case 'CUSTOM_CLEAR': + radioCollback.getControl(2).select(); + break; + } + + //set custom URL + customUrl.setValue(this.getConfigWebEntry().we_callback_url); + + //set show task in new case + if (this.getConfigWebEntry().we_show_in_new_case === '1'){ + showInNewCase.setValue('["showCase"]'); + }else{ + showInNewCase.setValue('[]'); + } + + //customize suggest styles + this.getSuggestField().inputField[0].style.width = '280px'; + this.getSuggestField().inputLabel[0].parentElement.style.width = '120px'; + this.getSuggestField().inputLabel[0].parentElement.style.marginLeft = '220px'; + }, + + /** + * TabLink Panel + * Assigns values to tabLink fields + */ + setConfigDataTabLink: function () { + var that = this, + options = [], + customDomain, + radioGeneration, + languages = [], + skins = [], + dropDownLanguages, + dropDownSkins, + data, + i; + + //execute Rest (Get languages and Skins) + this.getSkinLanguage( + function (xhr, response) { + languages = response[0].response.data; + skins = response[1].response.data; + //get controls Tab-link + that.getTabPanel().getItem('tabLink').select(); + radioGeneration = that.getTabLinkForm().getItem('tabLinkRadioGeneration'); + dropDownSkins = that.getTabLinkForm().getItem('tabLinkDropdownSkin'); + dropDownLanguages = that.getTabLinkForm().getItem('tabLinkDropdownLanguage'); + customDomain = that.getTabLinkForm().getItem('tablinkTextCustomDomain'); + + //set Link generation (Default or Advanced) + radioGeneration.setValue(that.getConfigWebEntry().we_link_generation); + (that.getConfigWebEntry().we_link_generation === 'DEFAULT') ? radioGeneration.getControl(0).select() : + radioGeneration.getControl(1).select(); + + //set Languages Dropdown + if (jQuery.isArray(languages)) { + for (i = 0; i < languages.length; i += 1) { + data = {}; + data.label = languages[i].LANG_NAME; + data.value = languages[i].LANG_ID; + if (languages[i].LANG_ID === that.getConfigWebEntry().we_link_language) { + data.selected = true; + } + options.push(data); + } + dropDownLanguages.setOptions(options); + } + //set Skins Dropdown + if (jQuery.isArray(skins)) { + options = []; + for (i = 0; i < skins.length; i += 1) { + data = {}; + data.label = skins[i].SKIN_NAME; + data.value = skins[i].SKIN_FOLDER_ID; + if (that.getConfigWebEntry().we_link_skin === skins[i].SKIN_FOLDER_ID) { + data.selected = true; + } + options.push(data); + } + dropDownSkins.setOptions(options); + } + + //set Custom Domain + customDomain.setValue(that.getConfigWebEntry().we_link_domain); + //Enable or Disable (Skin, Language, CustomDomain) + that.linkGenerationOnChange(that.getConfigWebEntry().we_link_generation); + //set Link text + that.setLinkText(that.getTabLinkForm(), that.getConfigWebEntry().wee_url); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + + /** + * Load and populate Accordion Data Items + * @param response + */ + loadAccordionItems: function (response) { + var firstResp = [], + secondResp = [], + i, + item, + assigmentConfig, + firstRes = 0, + secondRes = 1; + this.getStepsAssignAccordion().clearItems(); + if (jQuery.isArray(response) && response.length) { + if (typeof response[firstRes] === "object") { + firstResp = response[firstRes].response ? response[firstRes].response : []; + } + if (typeof response[secondRes] === "object") { + secondResp = response[secondRes].response ? response[secondRes].response : []; + } + } + if (firstResp.length) { + for (i = 0; i < firstResp.length; i += 1) { + item = this.createAccordionItem(firstResp[i], true, true); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = firstResp[i]; + this.customAccordionItemButtons(item.html, firstResp[i], item); + } + } + assigmentConfig = { + step_type_obj: "Assignment".translate(), + triggers: secondResp, + st_type: "ASSIGNMENT", + obj_title: "Assignment".translate(), + step_uid_obj: "Assignment" + }; + item = this.createAccordionItem(assigmentConfig); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = assigmentConfig; + assigmentConfig = { + step_type_obj: "Routing".translate(), + triggers: secondResp, + obj_title: "Routing".translate(), + st_type: 'ROUTING', + step_uid_obj: "Routing" + }; + item = this.createAccordionItem(assigmentConfig); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = assigmentConfig; + this.getStepsAssignAccordion().defineEvents(); + }, + + /** + * Create Accordion + * @param data + * @returns {PMUI.item.AccordionItem} + */ + createAccordionItem: function (data) { + var that = this, + gridBefore, + gridAfter, + beforeTitle, + afterTitle, + i, + textLabel; + if (this.stepsType[data.step_type_obj]) { + textLabel = this.stepsType[data.step_type_obj]; + } else { + textLabel = data.step_type_obj; + } + beforeTitle = new PMUI.field.TextAnnotationField({ + text: 'Before'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left' + }); + afterTitle = new PMUI.field.TextAnnotationField({ + text: 'After'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left', + visible: data.st_type === "ASSIGNMENT" ? false : true + }); + + gridBefore = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + st_type: 'BEFORE', + step_uid: data.step_uid, + visibleFooter: false, + width: '96%', + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: "st_position", + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 210 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-delete'] + }, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + }], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + }, + onDragStart: function (grid, row) { + var items; + items = grid.getItems(); + if (jQuery.isArray(items)) { + if (items.length === 1) { + grid.showEmptyCell(); + } + } + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridBefore.st_type = 'BEFORE'; + } else if (data.st_type === "ROUTING") { + gridBefore.st_type = "BEFORE_ROUTING"; + } else { + gridBefore.st_type = "BEFORE_ASSIGNMENT"; + } + gridBefore.step_uid = data.step_uid; + gridBefore.clearItems(); + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridBefore.st_type === data.triggers[i].st_type) { + gridBefore.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + gridAfter = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + visibleFooter: false, + width: '96%', + visible: data.st_type === "ASSIGNMENT" ? false : true, + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: 'st_position', + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 210 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-delete'] + }, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + }], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + }, + onDragStart: function (grid, row) { + var items; + items = grid.getItems(); + if (jQuery.isArray(items)) { + if (items.length === 1) { + grid.showEmptyCell(); + } + } + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridAfter.st_type = 'AFTER'; + } else if (data.st_type == "ROUTING") { + gridAfter.st_type = "AFTER_ROUTING"; + } else { + gridAfter.st_type = "AFTER_ASSIGNMENT"; + } + gridAfter.step_uid = data.step_uid; + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridAfter.st_type === data.triggers[i].st_type) { + gridAfter.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + var accordionItem = new PMUI.item.AccordionItem({ + id: 'id' + data.step_uid_obj, + dataStep: data, + closeable: true, + body: new PMUI.core.Panel({ + layout: 'vbox', + items: [ + beforeTitle, + gridBefore, + afterTitle, + gridAfter + ] + }) + }); + if (this.stepsType[data.step_type_obj]) { + accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + + this.stepsType[data.step_type_obj] + ')'); + this.stepsAssigned.insert(accordionItem); + } else { + accordionItem.setTitle((this.getStepsAssignAccordion().items.getSize() + 1) + ". " + data.obj_title); + } + return accordionItem; + }, + + /** + * This method is executed when a row is drop in another grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @param draggableItem + * @returns {*} + */ + receiveRowItem: function (receiveData, grid, index, draggableItem) { + var receiveParent = draggableItem.getParent(), + message, + restClient, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: this.getWindow() + }); + index = receiveParent.items.indexOf(draggableItem); + receiveParent.items.remove(draggableItem); + receiveParent.addItem(draggableItem, index); + message.show(); + return false; + } + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger' : 'activity/' + + that.getConfigWebEntry().tas_uid + '/step/' + grid.step_uid + '/trigger', + method: 'POST', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + } + }, { + url: receiveParent.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger/' + receiveData.obj_uid + + '/' + that.getStepType(receiveParent.st_type) : + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + receiveParent.step_uid + + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), + method: 'DELETE' + }] + }, + functionSuccess: function (xhr, response) { + var data; + data = receiveData; + if (data.hasOwnProperty("st_type")) { + data.st_type = grid.st_type; + grid.addDataItem(receiveData, index); + } + receiveParent.removeItem(draggableItem); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.getWindow(), + messageError: [ + 'An unexpected error while assigning the trigger, please try again later.'.translate() + ], + messageSuccess: [ + 'Trigger assigned successfully.'.translate() + ] + }); + restClient.executeRestClient(); + return this; + }, + + /** + * This method is executed when a row is sorted in the grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the new index position row + * @returns {stepsTask} + */ + sortableRowHandler: function (receiveData, grid, index) { + return new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + this.getConfigWebEntry().tas_uid + "/step/trigger/" + receiveData.tri_uid : 'activity/' + + this.getConfigWebEntry().tas_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, + typeRequest: 'update', + data: { + st_type: receiveData.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: this.getWindow(), + messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger assigned successfully.'.translate() + }).executeRestClient(); + }, + + /** + * Return the not items config. + * @returns {{obj_title: *, obj_uid: string, id: string}} + */ + notItemConfig: function () { + var config = { + obj_title: 'N/A'.translate(), + obj_uid: '', + id: "notItem" + }; + return config; + }, + + /** + * Get the steps assigned by a search criterion + * @param criteria, search filter, after running the endpoint getAccordionData method + * @returns {Array}, response with criteria + */ + getStepsAssignedByCriteria: function (criteria) { + var allAssigned = [], + i, + elements, + j, + resp, + data, + respon = []; + + this.getAccordionData( + function (xhr, response) { + allAssigned = response; + if (jQuery.isArray(allAssigned)) { + for (i = 0; i < allAssigned.length; i += 1) { + resp = allAssigned[i]; + if (typeof resp === "object") { + elements = resp.response ? resp.response : []; + for (j = 0; j < elements.length; j += 1) { + data = elements[j]; + if (typeof data === "object") { + if (data.step_type_obj && data.step_type_obj === criteria) { + respon.push(data); + } + } + } + } + } + } + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + return respon; + }, + + /** + * Opens the properties of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ + propertiesStepShow: function (step) { + var that = this, + form, + saveButton, + cancelButton, + restClient, + criteriaButton; + this.setWindowAlternative(null); + this.getWindowAlternativeForm().setWidth(520); + this.getWindowAlternativeForm().setHeight(370); + this.getWindowAlternativeForm().setTitle('Step Properties'.translate()); + form = new PMUI.form.Form({ + id: 'stepsEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + { + id: 'step_mode', + pmType: 'radio', + label: 'Mode'.translate(), + value: '', + visible: step.step_type_obj === "DYNAFORM" ? true : false, + name: 'step_mode', + options: [{ + id: 'modeEdit', + label: 'Edit'.translate(), + value: 'EDIT', + selected: true + }, { + id: 'modeView', + label: 'View'.translate(), + value: 'VIEW' + }] + }, + new CriteriaField({ + id: 'step_condition', + pmType: 'textarea', + name: 'step_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea' + }) + ] + }); + this.getWindowAlternativeForm().addItem(form); + + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + form.getField('step_mode').setValue(response.step_mode); + form.getField('step_condition').setValue(response.step_condition); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient; + if (form.isValid()) { + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'update', + data: form.getData(), + functionSuccess: function () { + that.getWindowAlternativeForm().close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems update the Step Trigger, please try again.'.translate() + }); + restClient.executeRestClient(); + } + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.handler = null; + criteriaButton.setVisible(false); + } + this.getWindowAlternativeForm().open(); + }, + + /** + * Opens the step of the selected step with the current settings + * @param step, is the data of selected step + * @param accordioItem + * @chainable + */ + editStepShow: function (step, accordioItem) { + var that = this, + inputDocument; + switch (step.step_type_obj) { + case 'DYNAFORM': + var restProxy = new PMRestClient({ + endpoint: 'dynaform/' + step.step_uid_obj, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var old = PMUI.activeCanvas, + formDesigner; + PMUI.activeCanvas = false; + formDesigner = PMDesigner.dynaformDesigner(response); + formDesigner.onHide = function () { + var assignedDynaform, + i, + data, + title; + assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); + if (jQuery.isArray(assignedDynaform)) { + for (i = 0; i < assignedDynaform.length; i += 1) { + data = assignedDynaform[i]; + if (typeof data === "object") { + if (data.step_uid === step.step_uid) { + title = data.step_position + ". " + data.obj_title; + title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; + accordioItem.setTitle(title); + accordioItem.dataItem = data; + } + } + } + } + PMUI.activeCanvas = old; + }; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + break; + case 'OUTPUT_DOCUMENT': + PMDesigner.output(); + PMDesigner.output.showTiny(step.step_uid_obj); + break; + case 'INPUT_DOCUMENT': + inputDocument = new InputDocument({ + onUpdateInputDocumentHandler: function (data, inputDoc) { + var position, title; + position = accordioItem.dataItem.step_position; + title = position + ". " + data.inp_doc_title; + title = title + ' (' + this.stepsType["INPUT_DOCUMENT"] + ')'; + accordioItem.dataItem.obj_title = data.inp_doc_title; + accordioItem.setTitle(title); + inputDoc.winMainInputDocument.close(); + } + }); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); + break; + } + }, + + /** + * Edit the selected trigger condition + * @param stepID, It is the id of the step to upgrade + * @param triggerID, is the id of the trigger to update + * @param stepType, It is the kind of step to update + * @param row, PMUI.grid.GridPanelRow, is the row affected + */ + editCondition: function (stepID, triggerID, stepType, row) { + var that = this, + saveButton, + cancelButton, + criteriaButton, + form, + dataRow; + dataRow = row.getData(); + this.setWindowAlternative(null); + this.getWindowAlternativeForm().setWidth(500); + this.getWindowAlternativeForm().setHeight(350); + this.getWindowAlternativeForm().setTitle('Condition Trigger'.translate()); + this.getWindowAlternativeForm().setTitle("Trigger".translate()); + form = new PMUI.form.Form({ + id: 'idFormEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + new CriteriaField({ + id: 'st_condition', + pmType: 'textarea', + name: 'st_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea', + value: dataRow.st_condition + }) + ] + }); + this.getWindowAlternativeForm().addItem(form); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var data, + restClient; + data = form.getData(); + data.st_type = stepType; + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + + ((typeof (stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, + typeRequest: 'update', + data: data, + messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + functionSuccess: function (xhr, response) { + dataRow.st_condition = data.st_condition; + row.setData(dataRow); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + that.getWindowAlternativeForm().close(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(false); + criteriaButton.handler = null; + } + this.getWindowAlternativeForm().open(); + }, + + /** + * This method is executed when editing a "trigger" in a row of the grid. + * secondary window opens with the current configuration of the trigger + * @param trigger, is the return value when is update 'trigger' action in the enpoint + * @param triggerID, is the id of the trigger to update + * @chainable + */ + editTrigger: function (trigger, triggerID) { + var that = this, + codeMirror, + saveButton, + cancelButton, + criteriaButton; + this.setWindowAlternative(null); + codeMirror = new PMCodeMirror({ + id: "codeMirror" + }); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + codeMirror.setValue(trigger); + this.getWindowAlternativeForm().setWidth(DEFAULT_WINDOW_WIDTH); + this.getWindowAlternativeForm().setHeight(DEFAULT_WINDOW_HEIGHT); + this.getWindowAlternativeForm().setTitle("Trigger".translate()); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + triggerID, + typeRequest: 'update', + data: { + tri_param: '', + tri_webbot: codeMirror.getValue() + }, + messageError: 'There are problems updating the trigger, please try again.'.translate(), + messageSuccess: 'Trigger updated correctly'.translate(), + flashContainer: that.getWindow(), + functionSuccess: function () { + that.getWindowAlternativeForm().close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(true); + criteriaButton.setHandler(function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var cursorPos, + codemirror; + codemirror = codeMirror.cm; + cursorPos = codemirror.getCursor(); + codemirror.replaceSelection(variable); + codemirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }); + } + this.getWindowAlternativeForm().open(); + this.getWindowAlternativeForm().addItem(codeMirror); + codeMirror.cm.setSize(this.getWindowAlternativeForm().getWidth(), 380); + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + codeMirror.cm.refresh(); + }, + + /** + * Returns the type of step, for the execution of "endpoint" + * @param st_type, this a step type, the accepted parameters are: + * - BEFORE_ASSIGNMENT + * - BEFORE_ROUTING + * - AFTER_ROUTING + * - BEFORE + * - AFTER + * @returns {string} + */ + getStepType: function (st_type) { + var value; + switch (st_type) { + case 'BEFORE_ASSIGNMENT': + value = 'before-assignment'; + break; + case 'BEFORE_ROUTING': + value = 'before-routing'; + break; + case 'AFTER_ROUTING': + value = 'after-routing'; + break; + case 'BEFORE': + value = 'before'; + break; + case 'AFTER': + value = 'after'; + break; + default: + value = ''; + break; + } + return value; + }, + + /** + * Checks whether a trigger is already assigned in a grid + * @param grid, is instanceof PMUI.grid.Grid, in conducting the search + * @param tri_uid, search parameter in the rows of the grid + * @returns {boolean} + */ + isTriggerAssigned: function (grid, tri_uid) { + var data, i, exist = false; + data = grid.getData(); + if (grid && jQuery.isArray(data)) { + for (i = 0; i < data.length; i += 1) { + if (data[i].tri_uid === tri_uid) { + exist = true; + break; + } + } + } + return exist; + }, + + /** + * This method eliminates the list of triggers trigger an assigned step + * @param row, the row affected or selected + * @param grid, It is affected or grid to remove selected row + */ + removeTrigger: function (row, grid) { + var that = this, + message = 'Do you want to remove the trigger "', + messageData = row.getData().tri_title ? row.getData().tri_title : "", + yesButton, + noButton, + restClient; + message = message + messageData + '"?'; + this.getConfirmWindow().setMessage(message.translate()); + yesButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-yes"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger/' + row.getData().tri_uid + '/' + + that.getStepType(row.getData().st_type) : 'activity/' + that.getConfigWebEntry().tas_uid + + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + + '/' + that.getStepType(row.getData().st_type), + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + that.getConfirmWindow().close(); + that.updateIndexToGrid(grid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.getWindow(), + messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger removed successfully'.translate() + }); + restClient.executeRestClient(); + }); + } + noButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-no"); + if (noButton) { + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + } + this.getConfirmWindow().open(); + }, + + /** + * Updates indexes of elements selected grid + * @param grid, It is affected or grid to remove selected row + * @returns {stepsTask} + */ + updateIndexToGrid: function (grid) { + var cell, rows, i, row; + if (grid) { + rows = grid.getItems(); + if (jQuery.isArray(rows)) { + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + cell = row.cells.find("columnData"); + if (cell) { + cell.setContent(i + 1); + } + } + } + } + return this; + }, + + /** + * Add custom buttons on the head of an element of stepsAssignAccordion + * are three buttons + * properties + * edit + * remove + * @param html, is the html of the header accordion item + * @param step, the data of the step selected + * @param accordionItem + */ + customAccordionItemButtons: function (html, step, accordionItem) { + var that = this, + propertiesStep, + editStep, + removeStep, + $html, + containerButtons, + title; + if (html) { + $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); + title = step.obj_title + ' (' + step.step_type_obj + ')'; + $html.find(".pmui-accordion-item-title").get(0).title = title; + containerButtons = $('
'); + containerButtons.addClass("propertiesTask-accordionItem"); + propertiesStep = $('' + 'Properties'.translate() + ''); + propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + editStep = $('' + 'Edit'.translate() + ''); + editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + removeStep = $('' + 'Remove'.translate() + ''); + removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); + + propertiesStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.propertiesStepShow(step); + return false; + }); + + editStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.editStepShow(step, accordionItem); + return false; + }); + + removeStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.removeStepShow(step); + return false; + }); + containerButtons.append(propertiesStep); + containerButtons.append(editStep); + containerButtons.append(removeStep); + $html.append(containerButtons); + } + }, + + /** + * Add tooltip in treeNode elements + * @returns {stepsTask} + */ + updateIndexPosition: function (treeNode) { + var items, + i, + item, + $item, + text, + data; + if (treeNode && treeNode.html) { + items = treeNode.getItems(); + if (jQuery.isArray(items)) { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + if (item.html) { + $item = $(item.html); + data = item.getData(); + text = $item.find("a").get(0); + text.title = data.obj_title; + } + } + } + } + return this; + }, + + /** + * This method loads the data to stepsAssignTree + * @param response, the answer is an array containing all the elements + * that will be loaded into the step stepsAssignTree + * @chainable + */ + loadTreePanelData: function (response) { + var data, + i, + j, + type, + label, + items = [], + dataTree = [], + treeNode; + data = response[1].response; + + dataTree.push({ + obj_title: 'Trigger (s)'.translate(), + items: [this.notItemConfig()] + }); + + for (i = 0; i < data.length; i += 1) { + items.push({ + obj_title: data[i]['tri_title'], + obj_type: data[i]['tri_type'], + obj_uid: data[i]['tri_uid'] + }); + } + + if (items.length) { + dataTree.shift(); + dataTree.push({ + obj_title: 'Trigger (s)'.translate(), + items: items, + id: "TRIGGER" + }); + } + + data = response[0].response; + type = this.groupType; + label = this.groupLabel; + items = []; + for (i = 0; i < type.length; i += 1) { + items = []; + for (j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [this.notItemConfig()], + behavior: '', + id: type[i] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items, + behavior: 'drag', + id: type[i] + }); + } + } + this.getStepsAssignTree().clearItems(); + for (i = 0; i < dataTree.length; i += 1) { + this.getStepsAssignTree().addDataItem(dataTree[i]); + treeNode = this.getStepsAssignTree().getItem(i); + treeNode.setID(dataTree[i].id); + this.updateIndexPosition(treeNode); + } + return this; + }, + + /** + * It is an extension to add the "sortable" event "stepsAssignTree". + * when choosing a node treePanel and you want to add to the accordion or the grid + * @chainable + */ + addEventSortableInTreePanelElements: function () { + var that = this, + items = this.getStepsAssignTree().getItems(), + connect, + i, + sw, + nodeItems; + for (i = 0; i < items.length; i += 1) { + nodeItems = items[i].getItems(); + if (nodeItems.length && nodeItems[0].getData().obj_type) { + sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; + connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; + $(items[i].html).find('ul').find('>li').draggable({ + appendTo: document.body, + revert: "invalid", + helper: "clone".translate(), + cursor: "move", + zIndex: 1000, + connectToSortable: connect, + start: function (e) { + var i, nodeTag, node, nodeData, accordionItems, item; + nodeTag = e.target; + node = PMUI.getPMUIObject(nodeTag); + nodeData = node.getData(); + accordionItems = that.getStepsAssignAccordion().getItems(); + $(that.getStepsAssignAccordion().body).hide(); + if (nodeData.obj_type !== "SCRIPT") { + for (i = 0; i < accordionItems.length; i += 1) { + item = accordionItems[i]; + item.collapse(); + } + } + $(that.getStepsAssignAccordion().body).show(); + }, + stop: function () { + var i = 0, + max; + if (that.elementAccordionOpen) { + max = that.elementAccordionOpen.getSize(); + for (i = 0; i < max; i += 1) { + that.elementAccordionOpen.get(i).expand(); + } + } + } + }); + } else { + $(nodeItems[0].html).draggable("disable"); + } + } + }, + + /** + * It is an extension to add the "sortable" event "stepAssignAccordion". + * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. + * @chainable + */ + addEventSortableInAccordionElements: function () { + var that = this, + tagContainer, + newIndex, + index, + treeNodeObject, + treeNodeData; + if (this.getStepsAssignAccordion() && this.getStepsAssignAccordion().html) { + tagContainer = this.getStepsAssignAccordion().body; + $(tagContainer).sortable({ + items: '>div:not(#idAssignment,#idRouting)', + placeholder: 'steps-placeholder', + receive: function (event, ui) { + var item = ui ? ui.item : null; + if (item && item instanceof jQuery && item.length) { + treeNodeObject = PMUI.getPMUIObject(item.get(0)); + treeNodeData = treeNodeObject.getData(); + } + }, + stop: function (event, ui) { + var itemClone = ui ? ui.item : null, + accordionItems, + accordionItem, + dataEdited, + restClientMultipart, + restClient; + var newIndex = ui.item.index(); + accordionItems = that.getStepsAssignAccordion().getItems(); + if (itemClone && itemClone instanceof jQuery && itemClone.length) { + if (treeNodeObject) { + itemClone.remove(); + if (newIndex + 1 > accordionItems.length) { + newIndex = that.stepsAssigned.getSize(); + } + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step', + typeRequest: 'post', + data: { + step_type_obj: treeNodeData.obj_type, + step_uid_obj: treeNodeData.obj_uid, + step_condition: '', + step_position: newIndex + 1, + step_mode: 'EDIT' + }, + functionSuccess: function (xhr, response) { + var item, buttonAfected, treeNode; + that.getStepsAssignTree().removeItem(treeNodeObject); + treeNode = that.getStepsAssignTree().items.find("id", response.step_type_obj); + if (treeNode.items.getSize() === 0) { + treeNode.addDataItem(that.notItemConfig()); + } + response.obj_description = ''; + response.obj_title = treeNodeData.obj_title; + response.triggers = []; + item = that.createAccordionItem(response, true, true); + item.dataItem = response; + if (that.getStepsAssignAccordion().items.getSize() === 2) { + that.getStepsAssignAccordion().addItem(item, 0); + } else { + that.getStepsAssignAccordion().addItem(item, newIndex); + } + that.getStepsAssignAccordion().defineEvents(); + that.customAccordionItemButtons(item.html, response, item); + that.updateItemIndexToAccordion(); + that.addEventSortableInAccordionElements(); + that.addEventSortableInTreePanelElements(); + buttonAfected = that.getLabelsPanel().getItem("expand-button"); + buttonAfected.setDisabled(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while assigning the step, please try again later.' + .translate(), + messageSuccess: 'Step assigned successfully.'.translate(), + flashContainer: that.getStepsAssignAccordion().getParent() + }); + restClient.executeRestClient(); + } else { + accordionItem = PMUI.getPMUIObject(ui.item.get(0)); + index = that.getStepsAssignAccordion().items.indexOf(accordionItem); + if (newIndex !== index) { + that.getStepsAssignAccordion().items.remove(accordionItem); + that.getStepsAssignAccordion().items.insertAt(accordionItem, newIndex); + dataEdited = { + step_position: newIndex + 1, + step_uid: accordionItem.dataItem.step_uid, + step_type_obj: accordionItem.dataItem.step_type_obj, + step_uid_obj: accordionItem.dataItem.step_uid_obj + }; + restClientMultipart = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + + accordionItem.dataItem.step_uid, + typeRequest: 'update', + data: dataEdited, + functionSuccess: function (xhr, response) { + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while editing the step, please try again later.' + .translate(), + messageSuccess: 'Step editing successfully.'.translate(), + flashContainer: that.getWindow() + }); + restClientMultipart.executeRestClient(); + } + } + } + }, + start: function (e, ui) { + newIndex = ui.item.index(); + } + }); + } + }, + + /** + * Updates indexes of elements assigned + * @returns {stepsTask} + */ + updateItemIndexToAccordion: function () { + var title, + i, + item, + dataItem, + items = this.getStepsAssignAccordion().items, + position, + max; + max = items.getSize(); + for (i = 0; i < max; i += 1) { + item = items.get(i); + position = items.indexOf(item); + dataItem = item.dataItem; + title = (position + 1) + ". " + dataItem.obj_title; + if (this.stepsType[dataItem.step_type_obj]) { + title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; + } + item.dataItem.step_position = i + 1; + item.setTitle(title); + } + return this; + }, + + /** + * The window opens for confirmation of the removal step + * @param step, the current step to remove + * @chainable + */ + removeStepShow: function (step) { + var that = this, + title, + yesButton, + noButton, + restClient; + if (this.stepsType[step.step_type_obj] !== undefined) { + title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); + this.getConfirmWindow().setTitle(title); + } else { + this.getConfirmWindow().setTitle("Step " + step.step_type_obj.capitalize()); + } + this.getConfirmWindow().setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); + yesButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-yes"); + noButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-no"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.removingStepTask(step, response); + that.getConfirmWindow().close(); + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), + messageSuccess: 'Step removed successfully'.translate(), + flashContainer: that.getWindow().getParent() + }); + restClient.executeRestClient(); + }); + } + if (noButton) { + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + } + this.getConfirmWindow().open(); + }, + + /** + * Get the steps is not assigned by a criterion + * @param criteria, It is the filter criteria search + * @param stepAvailable, all steps Unassigned + * @returns {Array}, filtered items + */ + getAvailablesStepsByCriteria: function (criteria, stepAvailable) { + var items = [], + i; + if (jQuery.isArray(stepAvailable)) { + for (i = 0; i < stepAvailable.length; i += 1) { + if (stepAvailable[i].obj_type === criteria) { + items.push(stepAvailable[i]); + } + } + } + return items; + }, + + /** + * Eliminates the step of step Assign Accordion + * @param step, the current step to remove + * @param response, data from the endpoint + */ + removingStepTask: function (step, response) { + var stepObject, + stepAvailable, + treeNodeObject, + stepAvailables, + i, + itemsTreeNode = [], + items = []; + stepObject = this.getStepsAssignAccordion().getItem("id" + step.step_uid_obj); + this.elementAccordionOpen.remove(stepObject); + this.stepsAssigned.remove(stepObject); + this.getStepsAssignAccordion().removeItem(stepObject); + if (stepObject) { + this.getStepAvailables( + function (xhr, response) { + stepAvailable = response[0] ? response[0].response : []; + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); + for (i = 0; i < stepAvailables.length; i += 1) { + items.push({ + obj_title: stepAvailables[i]['obj_title'], + obj_type: stepAvailables[i]['obj_type'], + obj_uid: stepAvailables[i]['obj_uid'] + }); + } + treeNodeObject = this.getStepsAssignTree().getItem(step.step_type_obj); + itemsTreeNode = treeNodeObject.getItems(); + for (i = 0; i < itemsTreeNode.length; i += 1) { + treeNodeObject.removeItem(itemsTreeNode[i]); + } + treeNodeObject.clearItems(); + treeNodeObject.setDataItems(items); + this.updateIndexPosition(treeNodeObject); + this.addEventSortableInTreePanelElements(); + this.addEventSortableInAccordionElements(); + } + }, + + /** + * This method is executed when an element stepsAssignTree, is assigned in a grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @returns {stepsTask} + */ + receiveTreeNodeItem: function (receiveData, grid, index) { + var restClient, + message, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: this.getWindow() + }); + message.show(); + return; + } + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger' : 'activity/' + + that.getConfigWebEntry().tas_uid + '/step/' + grid.step_uid + '/trigger', + typeRequest: 'post', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: '', + st_position: index + 1 + }, + functionSuccess: function (xhr, response) { + grid.addDataItem({ + st_condition: '', + st_position: index + 1, + st_type: grid.st_type, + tri_description: '', + tri_title: receiveData.obj_title, + tri_uid: receiveData.obj_uid, + obj_title: receiveData.obj_title, + obj_uid: receiveData.obj_uid + }, index); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return this; + } +}; +var PMMessageType = function (options) { + var that = this; + this.msgt_uid = null; + this.edit = false; + this.editRow = null; + this.dirtyAcceptedValue = false; + this.fieldInfo = null; + this.onSave = new Function(); + this.onEdit = new Function(); + this.requiredMessage = null; + this.clickedClose = true; + this.previousMessageValue = null; + this.buttonCreate = new PMUI.ui.Button({ + id: 'buttonCreate', + text: "Create".translate(), + height: '36px', + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + that.showForm(); + } + }); + + this.buttonFieldAdd = new PMUI.field.ButtonField({ + id: 'buttonFieldAdd', + pmType: 'buttonField', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.6, + handler: function (field) { + that.addAcceptedValue(); + }, + buttonType: "success", + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '37px', + 'padding-right': '1px', + 'padding-bottom': '1px', + 'padding-left': '1px' + } + } + }); + this.buttonFieldAdd.getControl().button.setButtonType("success"); + + this.buttonFieldCancel = new PMUI.field.ButtonField({ + id: 'buttonFieldCancel', + pmType: 'buttonField', + value: 'Cancel'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.6, + handler: function (field) { + that.cancelAcceptedValue(); + }, + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '37px', + 'padding-right': '1px', + 'padding-bottom': '1px', + 'padding-left': '1px' + } + } + }); + this.buttonFieldCancel.getControl().button.setButtonType("error"); + + this.frmMessageType = new PMUI.form.Form({ + id: 'frmMessageType', + width: 'auto', + title: '', + visibleHeader: false, + items: [ + { + id: 'txtMessageTypeName', + name: 'txtMessageTypeName', + pmType: 'text', + label: "Name".translate(), + placeholder: "Name".translate(), + value: '', + required: true, + valueType: 'string', + maxLength: 60, + controlsWidth: 460 + }, + { + id: "frmAcceptedValues", + pmType: 'panel', + legend: "Message Field".translate(), + fieldset: true, + layout: 'hbox', + items: [ + { + pmType: "text", + name: "txtMessageTypeVariableName", + label: "Message Field Name".translate(), + labelWidth: "100%", + controlsWidth: "400px", + proportion: 2.5, + valueType: "string", + maxLength: 255, + required: true, + labelPosition: "top", + validators: [ + { + pmType: "regexp", + criteria: /^[a-zA-Z_]+[0-9a-zA-Z_]+$/, + errorMessage: "A valid variable starts with a letter or underscore, followed by any number of letters, numbers, or underscores.".translate() + } + ] + }, + that.buttonFieldCancel, + that.buttonFieldAdd + ] + } + ] + }); + + this.frmMessageType.getData = function () { + var data = getData2PMUI(that.frmMessageType.html); + return data; + }; + + this.gridMessages = new PMUI.grid.GridPanel({ + id: 'gridMessages', + pageSize: 10, + width: '96%', + style: { + cssClasses: ['mafe-gridPanel'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: "msgtName", + title: "Name".translate(), + dataType: "string", + columnData: "msgt_name", + alignmentCell: "left", + width: "330px", + sortable: true + }, { + id: 'msgtEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: '60px', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + that.showFormEdit(row.getData()); + } + }, { + id: 'msgtDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: '70px', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + that.del(row.getData(), row, grid); + } + } + ], + dataItems: null + }); + + this.gridAcceptedValues = new PMUI.grid.GridPanel({ + id: 'gridAcceptedValues', + pageSize: 5, + height: 240, + style: {cssClasses: ['mafe-gridPanel']}, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + filterable: false, + tableContainerHeight: 200, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [ + { + id: "msgtv_name", + title: "Message Field Name".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 180, + sortable: true + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.editAcceptedValue(row); + } + }, + { + id: "btnDelete", + dataType: "button", + title: "", + buttonLabel: function (row, data) { + return "Delete".translate(); + }, + width: 75, + buttonStyle: {cssClasses: ["mafe-button-delete"]}, + onButtonClick: function (row, grid) { + that.deleteAcceptedValue(row); + } + } + ], + dataItems: null + }); + + this.isDirtyFrmMessageType = function () { + $("input,select,textarea").blur(); + if (this.frmMessageType.isVisible()) { + if (this.frmMessageType.isDirty() || this.dirtyAcceptedValue) { + var message_window = new PMUI.ui.MessageWindow({ + id: 'messageWindowCancel', + width: 490, + title: "Message Types".translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'messageWindowNo', + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: 'messageWindowYes', + text: 'Yes'.translate(), + handler: function () { + that.requiredMessage.hide(); + if (that.clickedClose) { + that.winMessageType.close(); + } + message_window.close(); + that.showGrid(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if (this.clickedClose) { + this.winMessageType.close(); + } else { + this.showGrid(); + this.requiredMessage.hide(); + } + } + } else { + this.winMessageType.close(); + } + }; + this.winMessageType = new PMUI.ui.Window({ + id: 'winMessageType', + title: '', + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonsPosition: 'right', + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFrmMessageType(); + }, + footerItems: [ + new PMUI.ui.Button({ + id: 'winMessageTypeCancel', + text: 'Cancel'.translate(), + handler: function () { + that.clickedClose = false; + that.isDirtyFrmMessageType(); + }, + buttonType: 'error' + }), + new PMUI.ui.Button({ + id: 'winMessageTypeSave', + text: "Save".translate(), + handler: function () { + that.frmAcceptedValues.getItems("fields").forEach(function (i) { + i.disable(); + }); + if (that.edit) { + that.updateMessageType(); + } else { + that.createMessageType(); + } + that.frmAcceptedValues.getItems("fields").forEach(function (i) { + i.enable(); + }); + }, + buttonType: 'success' + }) + ], + buttonPanelPosition: 'bottom' + }); + PMMessageType.prototype.init.call(this); +}; + +PMMessageType.prototype.init = function () { + var that = this; + + that.buttonCreate.defineEvents(); + that.winMessageType.addItem(that.gridMessages); + that.winMessageType.addItem(that.frmMessageType); + that.winMessageType.addItem(that.gridAcceptedValues); + that.winMessageType.hideFooter(); + that.winMessageType.open(); + that.requiredMessage = $(document.getElementById("requiredMessage")); + + this.buttonFieldAdd.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + this.buttonFieldCancel.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + that.requiredMessage.css({float: "none"}); + that.winMessageType.footer.html.style.textAlign = 'right'; + + that.frmAcceptedValues = PMUI.getPMUIObject($('#frmAcceptedValues').css({'width': '690px'}).get(0)); + $('#gridMessages .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + + //$(that.frmAcceptedValues.getHTML()).find("#requiredMessage").empty(); + that.requiredMessage.hide(); + //that.winMessageType.body.appendChild(that.requiredMessage[0]); + that.gridMessages.dom.toolbar.appendChild(that.buttonCreate.getHTML()); + that.showGrid(); + + validateKeysField(that.frmMessageType.getField('txtMessageTypeName').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + that.resetFrmAcceptedValues(); +}; + +PMMessageType.prototype.createMessageType = function () { + var that = this, + data; + + if (!this.frmMessageType.isValid()) { + return; + } + if (that.gridAcceptedValues.getData().length == 0) { + PMDesigner.msgFlash('Add at least one variable.'.translate(), winMessageType, 'error', 3000, 5); + return; + } + + data = this.frmMessageType.getData(); + data.msgt_name = data.txtMessageTypeName; + data.msgt_variables = that.getDataAcceptedValues(); + + // This returned data is not necessary at sendind, so it is deleted + delete data.txtMessageTypeVariableName; + delete data.buttonFieldCancel; + delete data.buttonFieldAdd; + + (new PMRestClient({ + endpoint: 'message-type', + typeRequest: 'post', + functionSuccess: function (xhr, response) { + if (that.onSave(xhr, response) === false) { + that.msgt_uid = null; + return; + } + that.showGrid(); + that.load(); + that.msgt_uid = null; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: ' ', + data: data, + messageSuccess: "Message Type Saved successfully.".translate(), + flashContainer: that.panel + + })).executeRestClient(); +}; + +PMMessageType.prototype.updateMessageType = function () { + var that = this, + data; + if (!this.frmMessageType.isValid()) { + return; + } + if (that.gridAcceptedValues.getData().length == 0) { + if (!this.frmAcceptedValues.isValid()) { + return; + } else { + PMDesigner.msgFlash('Add at least one variable.'.translate(), winMessageType, 'error', 3000, 5); + return; + } + } + + data = this.frmMessageType.getData(); + data.msgt_name = data.txtMessageTypeName; + data.msgt_variables = that.getDataAcceptedValues(); + + (new PMRestClient({ + endpoint: "message-type/" + that.msgt_uid, + typeRequest: "update", + data: data, + + functionSuccess: function (xhr, response) { + if (that.onEdit(xhr, response, data) === false) { + that.msgt_uid = null; + return; + } + + that.showGrid(); + that.load(); + that.msgt_uid = null; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: ' ', + messageSuccess: "Message Type edited successfully.".translate(), + flashContainer: that.panel + })).executeRestClient(); +}; + +PMMessageType.prototype.deleteMessage = function (msgt_uid) { + var that = this; + + (new PMRestClient({ + endpoint: 'message-type/' + msgt_uid, + typeRequest: 'remove', + + functionSuccess: function (xhr, response) { + that.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: 'Working...'.translate(), + messageSuccess: 'Message Type Deleted successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; + +PMMessageType.prototype.load = function () { + var that = this, restProxy; + + restProxy = new PMRestClient({ + endpoint: 'message-types', + typeRequest: 'get', + + functionSuccess: function (xhr, response) { + that.gridMessages.setDataItems(response); + that.gridMessages.sort('msgt_name', 'asc'); + + $(that.gridMessages.dom.toolbar).find("input").val(""); + that.gridMessages.clearFilter(); + document.getElementById("requiredMessage").style.marginTop = "16px"; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +PMMessageType.prototype.del = function (data, row, grid) { + var that = this, + confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDel', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Message Types".translate(), + message: "Do you want to delete this Message Type?".translate(), + footerItems: [ + { + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.deleteMessage(data.msgt_uid, row); + }, + buttonType: "success" + } + ] + }); + + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMMessageType.prototype.showGrid = function () { + var that = this; + that.frmMessageType.setVisible(false); + that.frmAcceptedValues.setVisible(false); + that.gridAcceptedValues.setVisible(false); + $(that.gridMessages.dom.toolbar).find("input").val(""); + that.gridMessages.clearFilter(); + that.gridMessages.setVisible(true); + that.winMessageType.setTitle("Message Types".translate()); + that.winMessageType.hideFooter(); +}; + +PMMessageType.prototype.showForm = function () { + var that = this; + this.requiredMessage.show(); + that.edit = false; + that.dirtyAcceptedValue = false; + that.frmMessageType.setVisible(true); + that.frmAcceptedValues.setVisible(true); + that.gridAcceptedValues.setVisible(true); + that.gridMessages.setVisible(false); + that.winMessageType.setTitle("Create Message Type".translate()); + that.winMessageType.showFooter(); + that.frmMessageType.reset(); + that.frmMessageType.setFocus(); + that.changeViewFieldType(); + that.resetFrmAcceptedValues(); + that.gridAcceptedValues.clearItems(); + that.buttonFieldCancel.setVisible(false); +}; + +PMMessageType.prototype.showFormEdit = function (data) { + var that = this; + that.showForm(); + that.msgt_uid = data.msgt_uid; + that.edit = true; + + that.winMessageType.setTitle('Edit Message Type'.translate()); + that.frmMessageType.getField('txtMessageTypeName').setValue(data.msgt_name); + + that.setDataAcceptedValues(data.msgt_variables); + document.getElementById("requiredMessage").style.marginTop = "16px"; +}; + +PMMessageType.prototype.changeViewFieldType = function () { + var that = this, sw = true; + + that.frmAcceptedValues.setVisible(true); + that.gridAcceptedValues.setVisible(true); + + validateKeysField(that.frmAcceptedValues.getField('txtMessageTypeVariableName').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + + if (this.fieldInfo === null) { + this.fieldInfo = document.createTextNode(''); + } +}; + +PMMessageType.prototype.addAcceptedValue = function () { + var that = this, + value = $.trim(that.frmAcceptedValues.getField('txtMessageTypeVariableName').getValue()), + message; + + // if the form (form field's RegEx) is invalid, add a Message Field will not be allowed. + if (!that.frmAcceptedValues.isValid()) { + return; + } + + if (that.previousMessageValue !== value && that.isAcceptedValueAdded(value)) { + message = new PMUI.ui.FlashMessage({ + message: "The variable Name already exists.".translate(), + duration: 3000, + severity: 'error', + appendTo: that.winMessageType.footer + }); + message.show(); + return; + } else if (!value) { + message = new PMUI.ui.FlashMessage({ + message: "Please, specify a name for the Message Field.".translate(), + duration: 3000, + severity: 'error', + appendTo: that.winMessageType.footer + }); + return message.show(); + } + that.previousMessageValue = null; + if (that.editRow === null) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + msgtv_name: value + } + })); + } else { + that.editRow.setData({ + msgtv_name: value + }); + } + + that.dirtyAcceptedValue = true; + that.cancelAcceptedValue(); +}; + +PMMessageType.prototype.editAcceptedValue = function (row) { + var that = this, data; + that.editRow = row; + data = row.getData(); + + that.previousMessageValue = data.msgtv_name; + that.frmAcceptedValues.getField('txtMessageTypeVariableName').setValue(data.msgtv_name); + that.buttonFieldAdd.setValue('Save'.translate()); + that.buttonFieldCancel.setVisible(true); +}; + +PMMessageType.prototype.deleteAcceptedValue = function (row) { + var that = this, + confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Message Type".translate(), + message: "Are you sure you want to delete the \"variable\"?".translate(), + footerItems: [ + { + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.gridAcceptedValues.removeItem(row); + that.dirtyAcceptedValue = true; + }, + buttonType: "success" + } + ] + }); + + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMMessageType.prototype.getDataAcceptedValues = function () { + var that = this, data = [], i; + + if (that.gridAcceptedValues.visible) { + data = that.gridAcceptedValues.getData(); + + for (i = 0; i < data.length; i += 1) { + delete data[i].key; + delete data[i].type; + } + } + return data; +}; + +PMMessageType.prototype.setDataAcceptedValues = function (stringJsonData) { + var that = this, i, data; + if (!stringJsonData) { + return; + } + + data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + + if (that.gridAcceptedValues.visible) { + for (i = 0; i < data.length; i += 1) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + msgtv_name: data[i].msgtv_name, + msgtv_default_value: data[i].msgtv_default_value + } + })); + } + } +}; + +PMMessageType.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that.buttonFieldAdd.setValue("Create".translate()); + that.buttonFieldCancel.setVisible(false); + that.resetFrmAcceptedValues(); +}; +/** + * Validate if the value is present in the data collection. + * @param value + * @returns {boolean} + */ +PMMessageType.prototype.isAcceptedValueAdded = function (value) { + var that = this, i, + data = that.gridAcceptedValues.getData(); + + for (i = 0; i < data.length; i += 1) { + if (data[i].msgtv_name === value) { + return true; + } + } + return false; +}; +/** + * Resets the fields from the form's panel for accepted values. + */ +PMMessageType.prototype.resetFrmAcceptedValues = function () { + this.frmAcceptedValues.getItems('fields').forEach(function (i) { + i.setValue(""); + }); +}; + +PMDesigner.messageType = function () { + var pmvariables = new PMMessageType(); + pmvariables.load(); +}; + +PMDesigner.messageType.create = function () { + var pmvariables = new PMMessageType(); + pmvariables.showForm(); + pmvariables.load(); +}; + +var MessageEventDefinition = function (bpmnEvent) { + var that = this, + msgNameField, + variableSelector; + + this.bpmnEvent = bpmnEvent; + this.arrayMessageType = []; + this.messageEventDefinitionOption = ""; + this.messageEventDefinitionUid = ""; + this.editRow = null; + this.eventType = bpmnEvent.evn_behavior; + this.gridCurrent = null; + this.editMessageForm = null; + this.dirtyGrid = false; + this.myTitle = ""; + + variableSelector = new CriteriaField({ + id: "txtMessageTypeVariableDefaultValue", + name: "txtMessageTypeVariableDefaultValue", + valueType: "string", + label: that.bpmnEvent.evn_marker == "MESSAGECATCH" ? "Store value in".translate() : "Get value from".translate(), + maxLength: 200, + labelWidth: "50%", + controlsWidth: 300, + proportion: 3.4, + required: false + }); + + msgNameField = { + pmType: "text", + id: "txtMessageTypeVariableName", + name: "txtMessageTypeVariableName", + label: (that.bpmnEvent.evn_marker === "MESSAGECATCH" ? "Value" : "Name").translate(), + labelWidth: "40%", + controlsWidth: 200, + proportion: 2.5, + valueType: "string", + maxLength: 255, + readOnly: true, + required: false + }; + + this.cboMessageType = new PMUI.field.DropDownListField({ + id: "cboMessageType", + name: "cboMessageType", + label: "Message Type".translate(), + options: [], + required: true, + controlsWidth: 150, + onChange: function (newValue, prevValue) { + var messageTypeData = that.getMessageTypeByIndex(that.cboMessageType.getValue()); + if (messageTypeData != null) { + that.gridCurrent.setDataItems(messageTypeData.msgt_variables); + + that._resetEditMessageForm(); + } + } + }); + + this.isDirtyFormMessageEvent = function () { + if (that.frmMessageEventDefinition1.isDirty() || that.dirtyGrid) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageType", + width: 490, + title: that.myTitle.translate(), + windowMessageType: "warning", + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.winMessageEventDefinition.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.winMessageEventDefinition.close(); + } + }; + + this.txtCorrelationValue = new CriteriaField({ + id: "txtCorrelationValue", + name: "txtCorrelationValue", + valueType: "string", + label: "Correlation Value".translate(), + maxLength: 200, + value: "", + controlsWidth: 380 + }); + + this.btnSaveVariable = new PMUI.field.ButtonField({ + id: "btnSaveVariable", + pmType: "buttonField", + value: 'Save'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.8, + handler: function (field) { + that.addVariableInGrdPnlVariable3(); + that.dirtyGrid = true; + }, + buttonType: "success" + }); + + this.btnCancelVariable = new PMUI.field.ButtonField({ + id: "btnCancelVariable", + pmType: "buttonField", + value: "Cancel".translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 55, + proportion: 0.6, + + handler: function (field) { + that.cancelAcceptedValue(); + }, + buttonType: "error" + }); + + this.frmMessageEventDefinition1 = new PMUI.form.Form({ + id: "frmMessageEventDefinition1", + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + visibleHeader: false, + items: [ + that.cboMessageType, + that.txtCorrelationValue, + { + id: "edit-panel", + pmType: "panel", + legend: "Message content".translate(), + fieldset: true, + layout: "hbox", + items: [ + that.bpmnEvent.evn_marker === "MESSAGECATCH" ? variableSelector : msgNameField, + that.bpmnEvent.evn_marker === "MESSAGECATCH" ? msgNameField : variableSelector, + that.btnCancelVariable, + that.btnSaveVariable + ] + } + ], + style: { + cssProperties: { + marginBottom: '15px' + } + } + }); + + this.editMessageForm = this.frmMessageEventDefinition1.getItem("edit-panel"); + + this.grdPnlVariable3 = new PMUI.grid.GridPanel({ + id: "grdPnlVariable3", + pageSize: 5, + style: {cssClasses: ["mafe-gridPanel"]}, + emptyMessage: "No records found".translate(), + filterable: false, + + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ""; + }, + columns: [ + { + id: "msgtv_name", + title: "Name".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 180 + }, + { + id: "msgtv_default_value", + title: "Get value from".translate(), + columnData: "msgtv_default_value", + dataType: "string", + alignmentCell: "left", + width: 300 + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.setValueMessageEventDefinition(row); + } + } + ], + + dataItems: null + }); + + this.grdPnlReceive = new PMUI.grid.GridPanel({ + id: "grdPnlVariable3", + pageSize: 5, + style: {cssClasses: ["mafe-gridPanel"]}, + emptyMessage: "No records found".translate(), + filterable: false, + tableContainerHeight: 204, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ""; + }, + + columns: [ + { + id: "msgtv_default_value", + title: "Store value in".translate(), + columnData: "msgtv_default_value", + dataType: "string", + alignmentCell: "left", + width: 200 + }, + { + id: "msgtv_name", + title: "Name Value".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 280 + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.setValueMessageEventDefinition(row); + } + } + ], + dataItems: null + }); + + this.gridCurrent = this.grdPnlVariable3; + + MessageEventDefinition.prototype.init.call(this); +}; + +MessageEventDefinition.prototype.init = function () { + var that = this; + + that.createWindow(); + that.winMessageEventDefinition.addItem(that.frmMessageEventDefinition1); + that.winMessageEventDefinition.addItem(that.gridCurrent); + + that.winMessageEventDefinition.open(); + this.editMessageForm.setVisible(false); + this.applyStylesPost(); + + that.load(); + document.getElementById("requiredMessage").style.marginTop = "15px"; +}; + +MessageEventDefinition.prototype.applyStylesPost = function () { + var that = this; + that.btnSaveVariable.controls[0].addCSSClasses(["pmui pmui-button pmui-success"]); + that.btnCancelVariable.controls[0].addCSSClasses(["pmui pmui-button pmui-error"]); + that.btnSaveVariable.controls[0].html.style.padding = "5px"; + $(that.btnCancelVariable.controls[0].html).css({ + padding: "5px", + width: "auto" + }); +}; + +MessageEventDefinition.prototype.createWindow = function () { + var that = this; + + if (that.bpmnEvent.evn_marker === "MESSAGECATCH") { + that.myTitle = (that.bpmnEvent.evn_type === "START" ? "Start Message Event" : "Intermediate Receive Message Event").translate(); + that.gridCurrent = this.grdPnlReceive; + } else if (that.bpmnEvent.evn_marker === "MESSAGETHROW") { + that.myTitle = (that.bpmnEvent.evn_type == "END" ? "End Message Event" : "Intermediate Send Message Event").translate(); + that.gridCurrent = this.grdPnlVariable3; + } + + that.winMessageEventDefinition = new PMUI.ui.Window({ + id: "winMessageEventDefinition", + title: that.myTitle.translate(), + + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + modal: true, + onBeforeClose: function () { + that.isDirtyFormMessageEvent(); + }, + footerItems: [ + { + pmType: "button", + buttonType: "error", + text: "Cancel".translate(), + handler: function () { + that.isDirtyFormMessageEvent(); + } + }, + { + pmType: "button", + buttonType: "success", + text: "Save".translate(), + + handler: function () { + var correlationValueAux, data; + if (!that.frmMessageEventDefinition1.isValid()) { + return; + } + correlationValueAux = that.frmMessageEventDefinition1.getData(); + data = { + evn_uid: that.bpmnEvent.evn_uid, + msgt_uid: that.cboMessageType.getValue(), + msged_variables: that.getVariablesByArray(that.grdPnlVariable3GetData()), + msged_correlation: correlationValueAux.txtCorrelationValue + }; + + switch (that.messageEventDefinitionOption) { + case "POST": + that.messageEventDefintionPostRestProxy(data); + + that.gridCurrent.clearItems(); + that.winMessageEventDefinition.close(); + break; + case "PUT": + that.messageEventDefintionPutRestProxy(data, that.messageEventDefinitionUid); + that.gridCurrent.clearItems(); + that.winMessageEventDefinition.close(); + break; + } + } + } + ], + + footerAlign: "right", + visibleFooter: true, + closable: true, + buttonPanelPosition: "bottom" + }); +}; + +MessageEventDefinition.prototype.getMessageTypeByIndex = function (messageTypeUid) { + var that = this, + i, + messageTypeData = null; + + if (that.arrayMessageType.length > 0) { + for (i = 0; i <= that.arrayMessageType.length - 1; i += 1) { + if (that.arrayMessageType[i].msgt_uid == messageTypeUid) { + messageTypeData = that.arrayMessageType[i]; + break; + } + } + } + return messageTypeData; +}; + +MessageEventDefinition.prototype.getVariablesByArray = function (arrayVariables) { + var variables = {}, i; + + for (i = 0; i <= arrayVariables.length - 1; i += 1) { + variables[arrayVariables[i].msgtv_name] = arrayVariables[i].msgtv_default_value; + } + + return variables; +}; + +MessageEventDefinition.prototype.getVariablesByObject = function (objectVariable) { + var that = this, + key, aux, + arrayData = []; + + for (key in objectVariable) { + aux = {}; + aux["msgtv_name"] = key; + aux["msgtv_default_value"] = objectVariable[key]; + arrayData.push(aux); + } + return arrayData; +}; + +MessageEventDefinition.prototype.load = function () { + var that = this, restProxy; + + that.messageEventDefinitionUid = ""; + that.messageEventDefinitionOption = ""; + + restProxy = new PMRestClient({ + typeRequest: "get", + endpoint: "message-event-definitions", + + functionSuccess: function (xhr, response) { + var dataResponse = response, + i, + arrayMessageEventDefinition = dataResponse, + arrayMessageEventDefinitionData = {}; + + for (i = 0; i <= arrayMessageEventDefinition.length - 1; i += 1) { + if (arrayMessageEventDefinition[i].evn_uid == that.bpmnEvent.evn_uid) { + that.messageEventDefinitionUid = arrayMessageEventDefinition[i].msged_uid + arrayMessageEventDefinitionData = arrayMessageEventDefinition[i]; + break; + } + } + + that.cboMessageTypeSetOptionsRestProxy(that.cboMessageType, (typeof(arrayMessageEventDefinitionData.msgt_uid) != "undefined") ? arrayMessageEventDefinitionData.msgt_uid : ""); + + if (that.messageEventDefinitionUid == "") { + //POST + that.messageEventDefinitionOption = "POST"; + + that.editMessageForm.getField("txtMessageTypeVariableName").setValue(""); + that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").setValue(""); + } else { + //PUT + that.messageEventDefinitionOption = "PUT"; + + that.gridCurrent.setDataItems(that.getVariablesByObject(arrayMessageEventDefinitionData.msged_variables)); + that.frmMessageEventDefinition1.getField("txtCorrelationValue").setValue(arrayMessageEventDefinitionData.msged_correlation); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.setValueMessageEventDefinition = function (row) { + var that = this, data; + + that.editRow = row; + data = row.getData(); + + that.editMessageForm.getField("txtMessageTypeVariableName").setValue(data.msgtv_name); + that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").setValue(data.msgtv_default_value); + + that.editMessageForm.setVisible(true); +}; + +MessageEventDefinition.prototype.addVariableInGrdPnlVariable3 = function () { + var that = this, + data = { + msgtv_name: that.editMessageForm.getField("txtMessageTypeVariableName").getValue(), + msgtv_default_value: that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").getValue() + }; + + if (that.editRow == null) { + that.gridCurrent.addItem(new PMUI.grid.GridPanelRow({ + data: data + })); + } else { + that.editRow.setData(data); + } + + that.cancelAcceptedValue(); +}; + +MessageEventDefinition.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that._resetEditMessageForm(); + that.editMessageForm.setVisible(false); +}; + +MessageEventDefinition.prototype.grdPnlVariable3GetData = function () { + var that = this, + i, + data = []; + + if (that.gridCurrent.visible) { + data = that.gridCurrent.getData(); + + for (i = 0; i <= data.length - 1; i += 1) { + delete data[i].key; + delete data[i].type; + } + } + return data; +}; + +MessageEventDefinition.prototype.cboMessageTypeSetOptionsRestProxy = function (cboMessageType, messageTypeUidSelected) { + var that = this, restProxy, iAux; + + cboMessageType.clearOptions(); + iAux = 0; + restProxy = new PMRestClient({ + typeRequest: "get", + endpoint: "message-types", + + functionSuccess: function (xhr, response) { + var dataResponse = response, messageTypeData, i, arrayOptions, iAux; + that.arrayMessageType = dataResponse; + arrayOptions = []; + for (i = 0; i <= dataResponse.length - 1; i += 1) { + if (dataResponse[i].msgt_uid == messageTypeUidSelected) { + iAux = i; + } + + arrayOptions.push( + { + value: dataResponse[i].msgt_uid, + label: dataResponse[i].msgt_name + } + ); + } + + if (arrayOptions.length > 0) { + cboMessageType.setOptions(arrayOptions); + + if (messageTypeUidSelected == "") { + //POST + cboMessageType.setValue(arrayOptions[0].value); + messageTypeData = that.getMessageTypeByIndex(arrayOptions[0].value); + + if (messageTypeData != null) { + that.gridCurrent.setDataItems(messageTypeData.msgt_variables); + } + } else { + //PUT + cboMessageType.setValue(arrayOptions[iAux].value); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.messageEventDefintionPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "message-event-definition", + typeRequest: "post", + data: data, + + functionSuccess: function (xhr, response) { + var dataResponse = response; + PMDesigner.msgFlash('The property event was saved successfully.'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.messageEventDefintionPutRestProxy = function (data, messageEventDefinitionUid) { + var restProxy = new PMRestClient({ + endpoint: "message-event-definition/" + messageEventDefinitionUid, + typeRequest: "update", + data: data, + + functionSuccess: function (xhr, response) { + var dataResponse = response; + PMDesigner.msgFlash('The property event was saved successfully.'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; +/** + * Reset the fields from the form's Edit panel. + * @returns {MessageEventDefinition} + * @private + */ +MessageEventDefinition.prototype._resetEditMessageForm = function () { + if (this.editMessageForm) { + this.editMessageForm.getItems().map(function (i) { + i.setValue(""); + }); + } + return this; +}; + +/** + * @class IntroHelper + * Handle Intro helper + * + * @constructor + * Creates a new instance of the class + * @param {Object} options + */ +var IntroHelper = function (options) { + this.steps = []; + this.onExit = null; + this.introjs = null; + IntroHelper.prototype.initObject.call(this, options); +}; +IntroHelper.prototype.type = 'IntroHelper'; + +IntroHelper.prototype.initObject = function (options) { + var defaults = { + steps: [], + skipLabel: "Skip", + onExit : new Function() + }; + $.extend(true, defaults, options); + this.setSteps(defaults.steps); + + this.setSkipLabel(defaults.skipLabel); + this.setNextLabel(defaults.nextLabel); + this.setPrevLabel(defaults.prevLabel); + this.setDoneLabel(defaults.doneLabel); + this.setOnExit(defaults.onExit); +}; + +IntroHelper.prototype.setSteps = function (steps) { + this.steps = steps; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; +IntroHelper.prototype.setNextLabel = function (label) { + this.nextLabel = label; + return this; +}; + +IntroHelper.prototype.setPrevLabel = function (label) { + this.prevLabel = label; + return this; +}; + +IntroHelper.prototype.setDoneLabel = function (label) { + this.doneLabel = label; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; + +IntroHelper.prototype.setOnExit = function (callback) { + if (callback && typeof callback == "function") { + this.onExit = callback; + } + return this; +}; + +IntroHelper.prototype.startIntro = function () { + var that = this; + this.introjs = introJs(); + this.introjs.setOptions({ + steps: this.steps, + skipLabel: this.skipLabel, + nextLabel: this.nextLabel, + prevLabel: this.prevLabel, + doneLabel: this.doneLabel + }); + this.introjs.onexit(function () { + that.onExit(); + }); + + this.introjs.start(); +}; +(function () { + PMDesigner.scriptTaskProperties = function (activity) { + var that = this, + taskUid, + taskType, + triggerSelectedData, + oldValue, + uidProj, + scrtas_uid, + buttonCancel, + restClientNewScriptTask, + restClientUpdateScriptTask, + restClientNewTrigger, + restClientUpdateTrigger, + $ctrlSpaceMessage, + triggerEngine, + getListTrigger, + getScriptTask, + formScriptTask, + buttonSave, + domSettings, + scriptTaskPropertiesWindow, + triggerUid; + + taskUid = activity.getID(); + taskType = activity.getTaskType(); + taskType = "TRIGGER"; + oldValue = ""; + uidProj = PMDesigner.project.id; + scrtas_uid = ""; + triggerUid = ""; + $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelScriptButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + scriptTaskPropertiesWindow.isDirtyFormScript(); + } + }); + + restClientNewScriptTask = function (triggerUid) { + var restClient = new PMRestClient({ + endpoint: 'script-task', + typeRequest: 'post', + data: { + scrtas_obj_uid: triggerUid, + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function () { + scriptTaskPropertiesWindow.close(); + PMDesigner.msgFlash('Script Task saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateScriptTask = function (triggerUid) { + var restClient = new PMRestClient({ + endpoint: 'script-task/' + formScriptTask.getItems()[0].items.get(4).getValue(), + typeRequest: 'update', + data: { + scrtas_obj_uid: triggerUid, /*trigger uid*/ + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function () { + scriptTaskPropertiesWindow.close(); + PMDesigner.msgFlash('Script Task saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientNewTrigger = function (dataToSend, newScriptTask) { + var restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + triggerUid = response.tri_uid; + if (triggerUid != "" && typeof triggerUid != "undefinied") { + if (newScriptTask) { + restClientNewScriptTask(triggerUid); + } else { + restClientUpdateScriptTask(triggerUid); + } + } + }, + functionFailure: function (xhr, response) { + var msg = response.error.message, + arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateTrigger = function (newScriptTask) { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + formScriptTask.getItems()[0].items.get(1).getValue(), + typeRequest: 'update', + data: { + scrtas_obj_uid: formScriptTask.getItems()[0].items.get(1).getValue(), + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function (xhr, response) { + triggerUid = response.tri_uid; + if (newScriptTask) { + restClientNewScriptTask(formScriptTask.getItems()[0].items.get(1).getValue()); + } else { + restClientUpdateScriptTask(formScriptTask.getItems()[0].items.get(1).getValue()); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + buttonSave = new PMUI.ui.Button({ + id: 'saveScriptButton', + text: "Save".translate(), + handler: function (event) { + var newScriptTask, dataToSend; + if (formScriptTask.isValid()) { + if (formScriptTask.getItems()[0].items.get(4).getValue() === "") { /*new*/ + newScriptTask = true; + if (formScriptTask.getItems()[0].items.get(1).getValue() != "") { + restClientUpdateTrigger(newScriptTask); + } else { + dataToSend = { + tri_title: formScriptTask.getItems()[0].items.get(2).getValue(), + tri_description: "", + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + tri_param: "" + }; + restClientNewTrigger(dataToSend, newScriptTask); + } + } else { + newScriptTask = false; + if (formScriptTask.getItems()[0].items.get(1).getValue() !== "") { + restClientUpdateTrigger(newScriptTask); + } else { + dataToSend = { + tri_title: formScriptTask.getItems()[0].items.get(2).getValue(), + tri_description: "", + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + tri_param: "" + }; + restClientNewTrigger(dataToSend, newScriptTask); + } + } + } + }, + buttonType: 'success' + }); + + scriptTaskPropertiesWindow = new PMUI.ui.Window({ + id: "scriptTaskPropertiesWindow", + title: "Script Task Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formScriptTask.getItems()[1].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '208px', + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + } + } + }, + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + scriptTaskPropertiesWindow.isDirtyFormScript(); + } + }); + + scriptTaskPropertiesWindow.isDirtyFormScript = function () { + var that = this, + message_window, + title = "Script Task".translate(); + if (oldValue !== formScriptTask.getItems()[1].controls[0].cm.getValue()) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: title, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + + triggerEngine = new PMUI.field.DropDownListField({ + id: "triggerEngine", + name: "triggerEngine", + label: "Title".translate(), + options: null, + controlsWidth: 400, + required: true, + onChange: function (newValue, prevValue) { + var uidTri = newValue, i; + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid == uidTri) { + formScriptTask.getItems()[1].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + } + } + } + }); + + getListTrigger = function (triggerEngine) { + var restClient = new PMRestClient({ + endpoint: 'triggers', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var arrayOptions = [], i; + triggerSelectedData = response; + arrayOptions[0] = { + label: "- Select a trigger -".translate(), + value: "", + disabled: true, + selected: true + }; + for (i = 0; i <= triggerSelectedData.length - 1; i += 1) { + arrayOptions.push( + { + value: triggerSelectedData[i].tri_uid, + label: triggerSelectedData[i].tri_title + } + ); + } + triggerEngine.setOptions(arrayOptions); + triggerEngine.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + + getScriptTask = function () { + var restClient = new PMRestClient({ + endpoint: 'script-task/activity/' + taskUid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var i; + if (typeof response == "object") { + triggerUid = response.scrtas_obj_uid; + if (triggerUid != "" && typeof triggerUid != "undefinied") { + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid == triggerUid) { + formScriptTask.getItems()[1].controls[0].setValue(triggerSelectedData[i].tri_webbot); + oldValue = triggerSelectedData[i].tri_webbot; + formScriptTask.getItems()[0].items.get(4).setValue(response.scrtas_uid); + formScriptTask.getItems()[0].items.get(1).setValue(triggerUid); + } + } + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + formScriptTask = new PMUI.form.Form({ + id: "formScriptTask", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formScriptTask", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "taskUid", + pmType: "text", + label: "ID".translate(), + value: taskUid, + name: "taskUid", + readOnly: true, + visible: false, + valueType: 'string' + }, + triggerEngine, + { + id: "newScript", + pmType: "text", + label: "Title".translate(), + controlsWidth: 400, + value: "", + name: "newScript", + required: false, + visible: false, + valueType: 'string' + }, + { + id: "taskType", + pmType: "text", + value: taskType, + name: "taskType", + visible: false, + valueType: 'string' + }, + { + id: "scrtas_uid", + pmType: "text", + value: scrtas_uid, + name: "scrtas_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + that.cd = new PMCodeMirrorField({ + labelWidth: '23.8%' + }); + that.cd.setLabel("Code".translate()); + formScriptTask.addItem(that.cd); + formScriptTask.getItems()[1].setName('code'); + formScriptTask.getItems()[1].setID('code'); + formScriptTask.getItems()[1].setHeight(300); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + + getListTrigger(triggerEngine); + getScriptTask(); + /*end form*/ + + domSettings = function () { + var codeMirrorControl, requiredMessage, titleAdd, titleBack; + codeMirrorControl = formScriptTask.getItems()[1].controls[0].cm; + formScriptTask.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(650, 255); //CodeMirror Size + $("#code").find(".CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); + codeMirrorControl.refresh(); + } + requiredMessage = $(document.getElementById("requiredMessage")); + scriptTaskPropertiesWindow.body.appendChild(requiredMessage[0]); + requiredMessage[0].style['marginTop'] = '65px'; + + scriptTaskPropertiesWindow.footer.html.style.textAlign = 'right'; + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + + titleAdd = "Add new".translate(); + titleBack = "Back to list".translate(); + + $("#triggerEngine").find("select").after('  '); + $("#newScript").find("input").after('  '); + $("#titleAdd, #titleBack").tooltip(); + }; + + scriptTaskPropertiesWindow.addItem(formScriptTask); + scriptTaskPropertiesWindow.open(); + scriptTaskPropertiesWindow.showFooter(); + domSettings(); + + $(".showHideScript").on("click", function () { + if (formScriptTask.getItems()[0].items.get(1).isVisible()) { + formScriptTask.getItems()[0].items.get(1).setVisible(false); + } else { + formScriptTask.getItems()[0].items.get(1).setVisible(true); + formScriptTask.getItems()[0].items.get(1).setValue(""); + formScriptTask.getItems()[0].items.get(2).setRequired(false); + formScriptTask.getItems()[0].items.get(1).setRequired(true); + $(formScriptTask.getItems()[0].items.get(1).html).find("select").focus(); + } + + if (!formScriptTask.getItems()[0].items.get(2).isVisible()) { + formScriptTask.getItems()[0].items.get(2).setVisible(true); + formScriptTask.getItems()[0].items.get(1).setRequired(false); + formScriptTask.getItems()[0].items.get(1).setValue(""); + formScriptTask.getItems()[0].items.get(2).setRequired(true); + formScriptTask.getItems()[0].items.get(2).setValue(""); + $(formScriptTask.getItems()[0].items.get(2).html).find("input").focus(); + } else { + formScriptTask.getItems()[0].items.get(2).setVisible(false); + } + formScriptTask.getItems()[1].controls[0].cm.setValue(""); + oldValue = ""; + + }); + + }; +}()); + +(function () { + PMDesigner.timerEventProperties = function (activity) { + var that = this, + evnUid = activity.getID(), + activityType = activity.getEventMarker(), + uidProj = PMDesigner.project.id, + oldValues, + tmrevn_uid = "", + dataTimer = "", + buttonCancel, + restClientNewTimerEvent, + buttonSave, + restClientUpdateTimerEvent, + timerEventPropertiesWindow, + showHourlyItems, + showDailyItems, + showMonthlyItems, + showOneDateTimeItems, + showEveryItems, + showWaitForItems, + showWaitUntilItems, + varshowHourlyItems, + endDate, + oneDateTime, + daysGroup, + monthsGroup, + radioGroup, + dateTimeVariablePicker, + formTimerEvent, + getFormData, + getTimerEventData, + validateItems, + domSettings, + eventType = activity.getEventType(), + regexDay = new RegExp(/^(((0|1|2)?[0-9])|(3[01]))$/), + regexHour = new RegExp(/^(((0|1)?[0-9])|(2[0-4]))$/), + regexMinute = new RegExp(/^([0-5]?[0-9])$/); + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelTimmerButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + formTimerEvent.getField('startDate').controls[0].hideCalendar(); + formTimerEvent.getField('endDate').controls[0].hideCalendar(); + formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); + formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); + timerEventPropertiesWindow.isDirtyFormScript(); + } + }); + + restClientNewTimerEvent = function (dataToSave) { + var restClient = new PMRestClient({ + endpoint: 'timer-event', + typeRequest: 'post', + data: dataToSave, + functionSuccess: function (xhr, response) { + timerEventPropertiesWindow.close(); + PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateTimerEvent = function (dataToSave) { + var restClient = new PMRestClient({ + endpoint: 'timer-event/' + formTimerEvent.getField("tmrevn_uid").getValue(), + typeRequest: 'update', + data: dataToSave, + functionSuccess: function (xhr, response) { + timerEventPropertiesWindow.close(); + PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + buttonSave = new PMUI.ui.Button({ + id: 'saveTimmerButton', + text: "Save".translate(), + handler: function (event) { + var i, + opt, + formData; + + formTimerEvent.getField("hourType").setValue(getData2PMUI(formTimerEvent.html).hourType); + formTimerEvent.getField("minuteType").setValue(getData2PMUI(formTimerEvent.html).minuteType); + formTimerEvent.getField("dayType").setValue(getData2PMUI(formTimerEvent.html).dayType); + if (formTimerEvent.isValid()) { + opt = formTimerEvent.getField("radioGroup").getValue(); + formData = formTimerEvent.getData(); + switch (opt) { + case "1": /*hourly*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "HOURLY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "2": /*daily*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "DAILY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), + tmrevn_configuration_data: JSON.parse(formData.daysGroup).map(function (n) { + return Number(n); + }) + }; + break; + case "3": /*monthly*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "MONTHLY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), + tmrevn_configuration_data: JSON.parse(formData.monthsGroup).map(function (n) { + return Number(n); + }) + }; + break; + case "4": /*one-date-time*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "ONE-DATE-TIME", + tmrevn_next_run_date: $("#oneDateTime").find("input:eq(0)").val() + }; + for (var i in ENABLED_FEATURES) { + if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { + dataTimer.tmrevn_next_run_date = convertDatetimeToIso8601(dataTimer.tmrevn_next_run_date); + } + } + break; + case "5": /*every*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "EVERY", + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "6": /*wait for*/ + if ((formData.dayType === '' || formData.dayType === '00' || formData.dayType === '0') && + (formData.hourType === '' || formData.hourType === '00' || formData.hourType === '0') && + (formData.minuteType === '' || formData.minuteType === '00' || formData.minuteType === '0')) { + PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); + return; + } else { + if (!regexDay.test(formData.dayType) || !regexHour.test(formData.hourType) || !regexMinute.test(formData.minuteType)) { + PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); + return; + } + } + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "WAIT-FOR", + tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "7": /*wait until specified date time*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "WAIT-UNTIL-SPECIFIED-DATE-TIME", + tmrevn_configuration_data: $("#dateTimeVariablePicker").find("input:eq(0)").val() + }; + break; + } + if (formTimerEvent.getField("tmrevn_uid").getValue() == "") { + restClientNewTimerEvent(dataTimer); + } else { + restClientUpdateTimerEvent(dataTimer); + } + } + }, + buttonType: 'success' + }); + + timerEventPropertiesWindow = new PMUI.ui.Window({ + id: "timerEventPropertiesWindow", + title: "Timer Event Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + formTimerEvent.getField('startDate').controls[0].hideCalendar(); + formTimerEvent.getField('endDate').controls[0].hideCalendar(); + formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); + formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); + timerEventPropertiesWindow.isDirtyFormScript(); + } + }); + + timerEventPropertiesWindow.isDirtyFormScript = function () { + var that = this, + title = "Timer Event".translate(), + newValues = getFormData($("#formTimerEvent")); + if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: title, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + showHourlyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showDailyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(true); + formTimerEvent.getField('daysGroup').setRequired(true); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showMonthlyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(true); + formTimerEvent.getField('monthsGroup').setRequired(true); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showOneDateTimeItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('startDate').setRequired(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(true); + formTimerEvent.getField('oneDateTime').setRequired(true); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(false); + }; + + showEveryItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('startDate').setRequired(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + /*intermediate*/ + showWaitForItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getField('dateTimeVariablePicker').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + }; + + showWaitUntilItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(true); + formTimerEvent.getField('dateTimeVariablePicker').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); + }; + + radioGroup = new PMUI.field.RadioButtonGroupField({ + id: 'radioGroup', + controlPositioning: 'horizontal', + maxDirectionOptions: 7, + options: [ + { + label: "Hourly".translate(), + value: "1" + }, + { + label: "Daily".translate(), + value: "2" + }, + { + label: "Monthly".translate(), + value: "3" + }, + { + label: "One date/time".translate(), + value: "4" + }, + { + label: "Every".translate(), + value: "5" + }, + { + label: "Wait for".translate(), + value: "6" + }, + { + label: "Wait until specified date/time".translate(), + value: "7" + } + + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "1": + showHourlyItems(); + break; + case "2": + showDailyItems(); + break; + case "3": + showMonthlyItems(); + break; + case "4": + showOneDateTimeItems(); + break; + case "5": + showEveryItems(); + break; + case "6": + showWaitForItems(); + break; + case "7": + showWaitUntilItems(); + break; + } + }, + value: "1" + }); + + startDate = new PMUI.field.DateTimeField({ + id: 'startDate', + label: 'Start date'.translate(), + datetime: false, + dateFormat: 'yy-mm-dd', + firstDay: 1, + controlsWidth: 100, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + endDate = new PMUI.field.DateTimeField({ + id: 'endDate', + label: "End date".translate(), + value: '', + disabled: true, + datetime: false, + dateFormat: 'yy-mm-dd', + firstDay: 1, + controlsWidth: 100, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + oneDateTime = new PMUI.field.DateTimeField({ + id: 'oneDateTime', + label: 'Date time'.translate(), + datetime: true, + dateFormat: 'yy-mm-dd HH:ii:ss', + firstDay: 1, + controlsWidth: 150, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + daysGroup = new PMUI.field.CheckBoxGroupField({ + label: "Days".translate(), + id: 'daysGroup', + controlPositioning: 'vertical', + maxDirectionOptions: 3, + required: true, + options: [ + { + label: 'Monday'.translate(), + value: 1, + name: 'monday', + selected: true + }, + { + label: 'Tuesday'.translate(), + value: 2, + name: 'tuesday', + selected: true + }, + { + label: 'Wednesday'.translate(), + value: 3, + name: 'wednesday', + selected: true + }, + { + label: 'Thursday'.translate(), + value: 4, + name: 'thursday', + selected: true + }, + { + label: 'Friday'.translate(), + value: 5, + name: 'friday', + selected: true + }, + { + label: 'Saturday'.translate(), + value: 6, + name: 'saturday', + selected: true + }, + { + label: 'Sunday'.translate(), + value: 7, + name: 'sunday', + selected: true + } + ], + onChange: function (newVal, oldVal) { + + } + }); + + monthsGroup = new PMUI.field.CheckBoxGroupField({ + label: "Months".translate(), + id: 'monthsGroup', + controlPositioning: 'vertical', + maxDirectionOptions: 3, + required: true, + options: [ + { + label: 'January'.translate(), + value: 1, + name: 'january', + selected: true + }, + { + label: 'February'.translate(), + value: 2, + selected: true + }, + { + label: 'March'.translate(), + value: 3, + selected: true + }, + { + label: 'April'.translate(), + value: 4, + selected: true + }, + { + label: 'May'.translate(), + value: 5, + selected: true + }, + { + label: 'June'.translate(), + value: 6, + selected: true + }, + { + label: 'July'.translate(), + value: 7, + selected: true + }, + { + label: 'August'.translate(), + value: 8, + selected: true + }, + { + label: 'September'.translate(), + value: 9, + selected: true + }, + { + label: 'October'.translate(), + value: 10, + selected: true + }, + { + label: 'November'.translate(), + value: 11, + selected: true + }, + { + label: 'December'.translate(), + value: 12, + selected: true + } + ], + onChange: function (newVal, oldVal) { + + } + }); + + dateTimeVariablePicker = new PMUI.field.DateTimeField({ + id: 'dateTimeVariablePicker', + label: 'Date time'.translate(), + datetime: true, + dateFormat: 'yy-mm-dd HH:ii:ss', + firstDay: 1, + controlsWidth: 150, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + formTimerEvent = new PMUI.form.Form({ + id: "formTimerEvent", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formTimerEvent", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "evnUid", + pmType: "text", + value: evnUid, + name: "evnUid", + readOnly: true, + visible: false, + valueType: 'string' + }, + { + id: "activityType", + pmType: "text", + value: activityType, + name: "activityType", + readOnly: true, + visible: false, + valueType: 'string' + }, + radioGroup, + { + pmType: "panel", + id: "datesPanel", + layout: 'hbox', + items: [ + startDate, + { + pmType: "checkbox", + id: "endDateCheckbox", + label: "End date".translate(), + controlPositioning: 'vertical', + maxDirectionOptions: 2, + value: '', + options: [ + { + label: "End date:".translate(), + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + if (newVal[2] == "1") { + $('#endDate').find('input:eq(0)').removeProp("disabled"); + } else { + $('#endDate').find('input:eq(0)').val('').attr("disabled", "disabled"); + formTimerEvent.getField('endDate').setValue(''); + } + } + }, + endDate, + oneDateTime, + dateTimeVariablePicker + ] + }, + { + pmType: "panel", + id: "dayHourMonthPanel", + layout: 'hbox', + items: [ + { + id: "dayType", + label: "Day".translate(), + pmType: "text", + value: "", + name: "dayType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + }, + { + id: "hourType", + label: "Hour".translate(), + pmType: "text", + value: "", + name: "hourType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + }, + { + id: "minuteType", + label: "Minute".translate(), + pmType: "text", + value: "", + name: "minuteType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + } + ] + }, + daysGroup, + monthsGroup, + { + id: "tmrevn_uid", + pmType: "text", + value: tmrevn_uid, + name: "tmrevn_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + formTimerEvent.initialData = function () { + var formElements = this.getItems()[0], + datesPanelElements, + radioGroupValues = {'radioGroup': formElements.items.get(2).getValue()}; + oldValues.push(radioGroupValues); + datesPanelElements = formElements.items.get(3).getItems(); + + }; + + getFormData = function ($form) { + var unindexed_array = $form.serializeArray(), + indexed_array = {}; + + $.map(unindexed_array, function (n, i) { + indexed_array[n['name']] = n['value']; + }); + return indexed_array; + }; + + getTimerEventData = function () { + var restClient = new PMRestClient({ + endpoint: 'timer-event/event/' + formTimerEvent.getField("evnUid").getValue(), + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (typeof response === "object" && JSON.stringify(response).length > 2) { + var opt = response.tmrevn_option.toUpperCase(); + switch (opt) { + case "HOURLY": + $("#radioGroup").find("input:eq(0)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "DAILY": + $("#radioGroup").find("input:eq(1)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + formTimerEvent.getField("daysGroup").setValue(""); + formTimerEvent.getField("daysGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { + return n.toString(); + }))); + break; + case "MONTHLY": + $("#radioGroup").find("input:eq(2)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("dayType").setValue(response.tmrevn_day); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + formTimerEvent.getField("monthsGroup").setValue(""); + formTimerEvent.getField("monthsGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { + return n.toString(); + }))); + break; + case "ONE-DATE-TIME": + $("#radioGroup").find("input:eq(3)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + var d = response.tmrevn_next_run_date.replace(/-/g, "/"); + for (var i in ENABLED_FEATURES) { + if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { + d = response.tmrevn_next_run_date; + } + } + d = new Date(d); + formTimerEvent.getField("oneDateTime").setValue(d); + break; + case "EVERY": + $("#radioGroup").find("input:eq(4)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "WAIT-FOR": + $("#radioGroup").find("input:eq(5)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("dayType").setValue(response.tmrevn_day); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "WAIT-UNTIL-SPECIFIED-DATE-TIME": + $("#radioGroup").find("input:eq(6)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + var d = response.tmrevn_configuration_data.replace(/-/g, "/"); + d = new Date(d); + formTimerEvent.getField("dateTimeVariablePicker").setValue(d); + break; + } + } else { + if (eventType == "START") { + $("#radioGroup").find("input:eq(1)").trigger("click"); + } else { + $("#radioGroup").find("input:eq(5)").trigger("click"); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + /*end form*/ + + validateItems = function (itemId) { + var regexTest, + message, + valueItem, + regexTest; + + if (itemId === 'dayType') { + regexTest = regexDay; + message = "Error value: Day: 0 - 31".translate(); + } else if (itemId === 'hourType') { + regexTest = regexHour; + message = "Error value: Hour: 0 - 23".translate(); + } else if (itemId === 'minuteType') { + regexTest = regexMinute; + message = "Error value: Minute: 0 - 59".translate(); + } + + valueItem = $('#' + itemId).find('span input:eq(0)').val(); + + if (!regexTest.test(valueItem)) { + PMDesigner.msgFlash(message, timerEventPropertiesWindow, 'error', 3000, 5); + $('#' + itemId).find('span input:eq(0)').val(''); + return false; + } + }; + + domSettings = function () { + var requiredMessage = $(document.getElementById("requiredMessage")); + timerEventPropertiesWindow.body.appendChild(requiredMessage[0]); + requiredMessage[0].style['marginTop'] = '70px'; + + timerEventPropertiesWindow.footer.html.style.textAlign = 'right'; + + $('#hourType, #dayType, #minuteType').find('span input:eq(0)').bind('blur change', function () { + validateItems($(this).closest('div').attr('id')); + }); + + $("#dayType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "31"}); + $("#hourType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "23"}); + $("#minuteType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "59"}); + + $("#radioGroup").css({"text-align": "center", "margin-bottom": "20px"}).find("label:eq(0)").remove(); + $("#endDateCheckbox").css({"width": "170px", "top": "6px", "left": "28px"}).find("label:eq(0)").remove(); + $("#endDateCheckbox").find("table:eq(0)").css("border", "0px"); + $("#startDate").css("width", ""); + $("#endDate").css("width", "104px").find("label:eq(0)").remove(); + $("#oneDateTime").css("width", ""); + $("#datesPanel").css("text-align", "center").find("label").css({ + "width": "", + "float": "", + "text-align": "right" + }); + $("#dayHourMonthPanel").css("text-align", "center").find("label").css({"float": "", "width": "34.5%"}); + + $("#daysGroup").css("text-align", "center").find("label:eq(0)").remove(); + $("#monthsGroup").css("text-align", "center").find("label:eq(0)").remove(); + $("#daysGroup").find("input").each(function () { + $(this).attr("name", $(this).val()); + }); + + $("#dateTimeVariablePicker").css("width", ""); + + + if (eventType == "START") { + $(formTimerEvent.getField("radioGroup").controls[0].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[1].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[2].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[3].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[4].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[5].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[6].html).parent().hide(); + $("#radioGroup").find("input:eq(1)").trigger("click"); + } else { + $(formTimerEvent.getField("radioGroup").controls[0].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[1].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[2].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[3].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[4].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[5].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[6].html).parent().show(); + $("#radioGroup").find("input:eq(5)").trigger("click"); + } + }; + + timerEventPropertiesWindow.addItem(formTimerEvent); + timerEventPropertiesWindow.open(); + formTimerEvent.eventsDefined = false; + formTimerEvent.defineEvents(); + timerEventPropertiesWindow.showFooter(); + domSettings(); + getTimerEventData(); + oldValues = getFormData($("#formTimerEvent")); + }; +}()); + + +(function () { + PMDesigner.emailEventProperties = function (activity) { + var that = this, + buttonCancel, + buttonSave, + emailEventPropertiesWindow, + emailAcounts, + emailContent, + getEmailAccounts, + formEmailEvent, + emailWindowTinyMCE, + getFormData, + getEmailEventData, + domSettings, + activityId = activity.getID(), + activityType = activity.getEventMarker(), + uidProj = PMDesigner.project.id, + initTinyMCE = null, + oldValues, + emailEventId = "", + prf_uid = "", + ddSize = 21, + auxFromMail = {}, + defaultServerlabel = "Mail (PHP)".translate(), + triggerSelectedData; + /*options to display in drop down*/ + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelEmailEventsButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = false; + emailEventPropertiesWindow.isDirtyFormScript(); + } + }); + + buttonSave = new PMUI.ui.Button({ + id: 'saveEmailEventsButton', + text: "Save".translate(), + handler: function (event) { + PMDesigner.hideAllTinyEditorControls(); + var dataForm = formEmailEvent.getData(), + selectedAccount = formEmailEvent.getField('emailAcounts').getValue(); + if (formEmailEvent.isValid()) { + if (dataForm.emailEventId == "") { /*insert*/ + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'post', + messageError: '', + data: { + prf_filename: "emailEvent_" + new Date().getTime() + ".html", + prf_path: "templates", + prf_content: dataForm.filecontent + }, + functionSuccess: function (xhr, response) { + var restClient; + prf_uid = response.prf_uid; + if (prf_uid != "" && typeof prf_uid != "undefined") { + restClient = new PMRestClient({ + endpoint: 'email-event', + typeRequest: 'post', + data: { + evn_uid: activityId, + email_event_from: auxFromMail[selectedAccount] || '', + email_event_to: dataForm.ToEmail, + email_event_subject: dataForm.subjectEmail, + email_server_uid: dataForm.emailAcounts, + prf_uid: prf_uid + }, + functionSuccess: function () { + emailEventPropertiesWindow.close(); + PMDesigner.msgFlash('Email Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Email Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + + + } else { + (new PMRestClient({ + endpoint: 'file-manager/' + dataForm.prf_uid, + typeRequest: 'update', + messageError: '', + data: { + prf_content: tinyMCE.activeEditor.getContent() + }, + functionSuccess: function (xhr, response) { + var restClient; + prf_uid = response.prf_uid; + if (prf_uid != "" && typeof prf_uid != "undefined") { + restClient = new PMRestClient({ + endpoint: 'email-event/' + dataForm.emailEventId, + typeRequest: 'update', + data: { + evn_uid: activityId, + email_event_from: auxFromMail[selectedAccount] || '', + email_event_to: dataForm.ToEmail, + email_event_subject: dataForm.subjectEmail, + email_server_uid: dataForm.emailAcounts, + prf_uid: prf_uid + }, + functionSuccess: function () { + emailEventPropertiesWindow.close(); + PMDesigner.msgFlash('Email Event Edited correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems Edited the Email Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } + } + }, + buttonType: 'success' + }); + + emailEventPropertiesWindow = new PMUI.ui.Window({ + id: "emailEventPropertiesWindow", + title: "Email Event Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = true; + emailEventPropertiesWindow.isDirtyFormScript(); + } + }); + + emailEventPropertiesWindow.isDirtyFormScript = function () { + var that = this, + newValues, + message_window, + formData = formEmailEvent.getData(); + formData.filecontent = $(tinyMCE.activeEditor.getContent()).text().trim().length ? tinyMCE.activeEditor.getContent() : ""; + newValues = formData; + if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Email Event".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + emailAcounts = new PMUI.field.DropDownListField({ + id: "emailAcounts", + name: "emailAcounts", + label: "From".translate(), + options: null, + controlsWidth: 400, + required: false, + labelWidth: "15%", + onChange: function (newValue, prevValue) { + var uidTri = newValue, + oldValue, + i; + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid === uidTri) { + formScriptTask.getItems()[1].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + oldValue = triggerSelectedData[i].tri_webbot; + } + } + } + }); + emailContent = new PMUI.field.TextAreaField({ + id: 'filecontent', + name: 'filecontent', + label: 'Content'.translate(), + required: true, + value: '', + rows: 210, + labelWidth: "15%", + controlsWidth: 720, + onChange: function (currentValue, previousValue) { + }, + style: {cssClasses: ['mafe-textarea-resize']} + }); + getEmailAccounts = function (emailAcounts) { + var restClient = new PMRestClient({ + endpoint: 'email-event/accounts/emailServer', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var i, + arrayOptions; + triggerSelectedData = response; + arrayOptions = []; + arrayOptions[0] = { + label: "Default email account".translate(), + value: "", + disabled: false, + selected: true + }; + for (i = 0; i < triggerSelectedData.length ; i += 1) { + arrayOptions.push({ + value: triggerSelectedData[i].uid, + label: response[i].mess_engine === "MAIL" ? + triggerSelectedData[i].mess_from_name && triggerSelectedData[i].mess_from_name !== "" ? + triggerSelectedData[i].mess_from_name : defaultServerlabel : triggerSelectedData[i].mess_from_name && triggerSelectedData[i].mess_from_name !== "" ? + triggerSelectedData[i].mess_from_name + ' <' + triggerSelectedData[i].mess_account + '>' : ' <' + triggerSelectedData[i].mess_account + '>' + }); + auxFromMail[triggerSelectedData[i].uid] = triggerSelectedData[i].email; + } + emailAcounts.setOptions(arrayOptions); + emailAcounts.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + formEmailEvent = new PMUI.form.Form({ + id: "formEmailEvent", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formEmailEvent", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "activityId", + pmType: "text", + value: activityId, + name: "activityId", + visible: false, + valueType: 'string' + }, + { + id: "activityType", + pmType: "text", + value: activityType, + name: "activityType", + visible: false, + valueType: 'string' + }, + emailAcounts, + new CriteriaField({ + id: "ToEmail", + pmType: "text", + helper: "The email can be a string or a variable (@@myEmail), comma separated list of emails".translate(), + label: "To".translate(), + controlsWidth: 400, + value: "", + name: "ToEmail", + required: true, + visible: true, + labelWidth: "15%", + valueType: 'string' + }), + new CriteriaField({ + id: 'subjectEmail', + pmType: 'text', + label: "Subject".translate(), + controlsWidth: 400, + value: "", + name: "subjectEmail", + required: false, + visible: true, + labelWidth: "15%", + valueType: 'string' + }), + emailContent, + { + id: "emailEventId", + pmType: "text", + value: emailEventId, + name: "emailEventId", + visible: false, + valueType: 'string' + }, + { + id: "prf_uid", + pmType: "text", + value: prf_uid, + name: "prf_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + emailWindowTinyMCE = function () { + initTinyMCE = function () { + tinyMCE.activeEditor.domainURL = "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/"; + tinyMCE.activeEditor.processID = PMDesigner.project.id; + }; + formEmailEvent.getField('filecontent').getControls()[0].getHTML().className = 'tmceEditor'; + applyStyleWindowForm(emailEventPropertiesWindow); + tinyMCE.init({ + editor_selector: 'tmceEditor', + mode: 'specific_textareas', + directionality: 'ltr', + verify_html: false, + skin: 'o2k7', + theme: 'advanced', + skin_variant: 'silver', + relative_urls : false, + remove_script_host : false, + convert_urls: false, + plugins: 'advhr,advimage,advlink,advlist,autolink,autoresize,contextmenu,directionality,emotions,example,example_dependency,fullpage,fullscreen,iespell,inlinepopups,insertdatetime,layer,legacyoutput,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,style,tabfocus,table,template,visualblocks,visualchars,wordcount,xhtmlxtras,pmSimpleUploader,pmVariablePicker,style', + theme_advanced_buttons1: 'pmSimpleUploader,|,pmVariablePicker,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,cut,copy,paste', + theme_advanced_buttons2: 'bullist,numlist,|,outdent,indent,blockquote,|,tablecontrols,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor,styleprops', + theme_advanced_buttons3: 'hr,removeformat,visualaid,|,sub,sup,|,ltr,rtl,|,code', + popup_css: "/js/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialogTinyBpmn.css", + oninit: initTinyMCE, + onchange_callback: function (inst) { + formEmailEvent.getField('filecontent').setValue(tinyMCE.activeEditor.getContent({format: 'raw'})); + }, + handle_event_callback: function (e) { + }, + setup: function (ed) { + ed.onSetContent.add(function (ed, l) { + formEmailEvent.getField('filecontent').setValue(tinyMCE.activeEditor.getContent({format: 'raw'})); + }); + } + }); + }; + getFormData = function ($form) { + var unindexed_array = $form.serializeArray(), + indexed_array = {}; + + $.map(unindexed_array, function (n, i) { + indexed_array[n['name']] = n['value']; + }); + return indexed_array; + }; + getEmailEventData = function () { + var restClient = new PMRestClient({ + endpoint: 'email-event/' + activityId, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var valFrom; + if (typeof response === "object") { + emailEventId = response.email_event_uid; + if (emailEventId !== "" && typeof emailEventId !== "undefined") { + formEmailEvent.getField('emailEventId').setValue(response.email_event_uid); + // Set as selected the email server by uid + if (response.email_server_uid !== "" && typeof response.email_server_uid !== "undefined") { + formEmailEvent.getField('emailAcounts').setValue(response.email_server_uid); + } + formEmailEvent.getField('subjectEmail').setValue(response.email_event_subject); + formEmailEvent.getField('ToEmail').setValue(response.email_event_to); + + formEmailEvent.getField('prf_uid').setValue(response.prf_uid); + + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'get', + messageError: '', + data: { + path: "templates" + }, + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i += 1) { + if (response[i].prf_uid == formEmailEvent.getField('prf_uid').getValue()) { + formEmailEvent.getField('filecontent').setValue(response[i].prf_content); + if (!$(tinyMCE.activeEditor.getContent()).text().trim().length) { + tinyMCE.activeEditor.setContent(response[i].prf_content); + } + break; + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + getEmailAccounts(emailAcounts); + + /*end form*/ + + this.deleteEmailEventByEventUid = function () { + (new PMRestClient({ + endpoint: 'email-event/by-event/' + activityId, + typeRequest: 'remove', + messageError: '', + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + })).executeRestClient(); + return this; + }; + + domSettings = function () { + emailEventPropertiesWindow.footer.html.style.textAlign = 'right'; + $("#emailAcounts").find("select:eq(0)").css("height", "auto").attr({ + "onmousedown": "if(this.options.length>" + ddSize + "){this.size=" + ddSize + ";}", + "onchange": "this.size=0;", + "onblur": "this.size=0;" + }); + }; + emailEventPropertiesWindow.addItem(formEmailEvent); + emailEventPropertiesWindow.open(); + emailEventPropertiesWindow.showFooter(); + emailWindowTinyMCE(); + domSettings(); + getEmailEventData(); + oldValues = formEmailEvent.getData(); + }; +}()); + + +SaveAsForm = function (settings) { + Mafe.Form.call(this, settings); + SaveAsForm.prototype.init.call(this, settings); +}; +SaveAsForm.prototype = new Mafe.Form(); +SaveAsForm.prototype.init = function () { + var that = this; + that.onSave = new Function(); + that.onCancel = new Function(); + that.setID("SaveAsForm"); + that.setTitle("Save as".translate()); + that.setItems([{ + id: "prj_name", + name: "pro_title", + pmType: "text", + label: "Title".translate(), + placeholder: "Title".translate(), + maxLength: 100, + required: true + }, { + id: "prj_description", + pmType: "textarea", + name: "pro_description", + label: "Description".translate(), + placeholder: "Description".translate(), + rows: 200 + }, { + id: "pro_category", + name: "pro_category", + pmType: "dropdown", + label: "Category".translate(), + options: [ + {value: "", label: "No Category".translate()} + ] + } + ]); + that.setButtons([{ + id: "idCancel", + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + that.onCancel(); + } + }, { + id: "idSave", + text: "Save".translate(), + buttonType: "success", + handler: function () { + that.onSave(); + } + } + ]); + that.loadCategory(); +}; +SaveAsForm.prototype.loadCategory = function () { + var that = this, + titleProcess; + var a = new PMRestClient({ + typeRequest: "post", + multipart: true, + data: { + calls: [{ + url: "project/categories", + method: "GET" + }, { + url: "project/" + PMDesigner.project.projectId + "/process", + method: "GET" + } + ] + }, + functionSuccess: function (xhr, response) { + var i, dt, category = that.getField("pro_category"); + dt = response[0].response; + for (i = 0; i < dt.length; i++) { + category.addOption({ + value: dt[i].cat_uid, + label: dt[i].cat_name + }); + } + //load data + dt = response[1].response; + titleProcess = "Copy of".translate() + " [" + dt.pro_title + "]"; + that.getField("pro_title").setValue(titleProcess.substring(0, 100)); + that.getField("pro_description").setValue(dt.pro_description); + that.getField("pro_category").setValue(dt.pro_category); + }, + functionFailure: function (xhr, response) { + } + }); + a.setBaseEndPoint(""); + a.executeRestClient(); +}; + +SaveAs = function (settings) { + Mafe.Window.call(this, settings); + SaveAs.prototype.init.call(this, settings); +}; +SaveAs.prototype = new Mafe.Window(); +SaveAs.prototype.init = function () { + var that = this; + that.saveAsForm = new SaveAsForm(); + that.saveAsForm.onYesConfirmCancellation = function () { + that.close(); + }; + that.saveAsForm.onCancel = function () { + that.saveAsForm.loseChanges({title: that.title}); + }; + that.saveAsForm.onSave = function () { + that.saveAsForm.getField("pro_title").setReadOnly(true); + that.saveAsForm.getField("pro_description").setReadOnly(true); + PMUI.getPMUIObject($(that.saveAsForm.html).find("#idSave")[0]).setDisabled(true); + var a = new PMRestClient({ + typeRequest: "post", + multipart: true, + data: { + calls: [{ + url: "project/save-as", + method: "POST", + data: { + prj_uid: PMDesigner.project.projectId, + prj_name: that.saveAsForm.getField("pro_title").getValue(), + prj_description: that.saveAsForm.getField("pro_description").getValue(), + prj_category: that.saveAsForm.getField("pro_category").getValue() + } + } + ] + }, + functionSuccess: function (xhr, response) { + if (response[0].response.prj_uid) { + that.close(); + window.location.href = "designer?prj_uid=" + response[0].response.prj_uid; + } else { + that.saveAsForm.getField("pro_title").setReadOnly(false); + that.saveAsForm.getField("pro_description").setReadOnly(false); + PMUI.getPMUIObject($(that.saveAsForm.html).find("#idSave")[0]).setDisabled(false); + var field = that.saveAsForm.getField("pro_title"); + $(field.html).find(".pmui-textlabel").text(response[0].response); + field.showMessage(); + } + }, + functionFailure: function (xhr, response) { + } + }); + a.setBaseEndPoint(""); + a.executeRestClient(); + }; + + that.setTitle("Save as".translate()); + that.addItem(that.saveAsForm); +}; +(function () { + PMDesigner.granularProcessExport = function () { + var totalObjects = 0, + objectValues, + buttonSave, + objectsGroup, + loadObjects, + domSettings, + granularProcessExportForm, + granularProcessExportWindow, + buttonCancel = new PMUI.ui.Button({ + id: 'cancelButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + granularProcessExportWindow.close(); + } + }); + + buttonSave = new PMUI.ui.Button({ + id: 'saveButton', + text: "Export".translate(), + handler: function (event) { + var selectedObjects, + locationOrigin, + ws = enviromentVariables('WORKSPACE'), + formData = granularProcessExportForm.getData(); + selectedObjects = JSON.parse(formData.objectsGroup).map(function (n) { + return n; + }); + if (selectedObjects.length === 0) { + PMDesigner.msgFlash('At least one object should be selected in order to execute the action.'.translate(), document.body, 'error', 3000, 5); + return; + } + if (!window.location.origin) { + locationOrigin = window.location.protocol + "//" + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { + locationOrigin = HTTP_SERVER_HOSTNAME; + } else { + locationOrigin = window.location.origin; + } + location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + + "/export-granular?access_token=" + PMDesigner.project.keys.access_token + '&objects=' + + encodeURIComponent(JSON.stringify(selectedObjects)); + granularProcessExportWindow.close(); + }, + buttonType: 'success' + }); + + granularProcessExportWindow = new PMUI.ui.Window({ + id: "granularProcessExportWindow", + title: "Export Process Objects".translate(), + width: 350, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + granularProcessExportWindow.close(); + } + }); + + objectsGroup = new PMUI.field.CheckBoxGroupField({ + labelVisible: false, + id: 'objectsGroup', + controlPositioning: 'horizontal', + maxDirectionOptions: 1, + required: true, + options: [], + onChange: function (newVal, oldVal) { + if (totalObjects > JSON.parse(newVal).length) { + granularProcessExportForm.getField('checkAllId').setValue(0); + } + } + }); + + loadObjects = function () { + var objectsList, + restClient, + i; + restClient = new PMRestClient({ + endpoint: 'export/listObjects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var arrayIds = [], + i; + objectsList = JSON.parse(response); + for (i in objectsList.data) { + objectsGroup.addOption({ + label: objectsList.data[i].OBJECT_NAME, + name: objectsList.data[i].OBJECT_NAME, + selected: false, + value: objectsList.data[i].OBJECT_ID + }); + arrayIds.push(objectsList.data[i].OBJECT_ID.toString()); + } + totalObjects = objectsList.data.length; + objectValues = objectsGroup.getValueFromControls(); + objectValues = JSON.parse(objectValues).length ? objectValues : JSON.stringify(arrayIds); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems loading the process objects.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + loadObjects(); + + granularProcessExportForm = new PMUI.form.Form({ + id: "granularProcessExportForm", + border: true, + visibleHeader: false, + width: '340px', + name: "granularProcessExportForm", + title: "", + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + pmType: "checkbox", + id: "checkAllId", + labelVisible: false, + controlPositioning: 'vertical', + maxDirectionOptions: 2, + value: '', + options: [ + { + label: "Check All".translate(), + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + if (newVal[2] === "1") { + objectsGroup.setValueToControls(objectValues); + } else { + objectsGroup.setValueToControls(); + } + } + }, + objectsGroup + ] + } + ] + }); + + domSettings = function () { + $('#objectsGroup').find('label:eq(0)').remove(); + }; + + granularProcessExportWindow.addItem(granularProcessExportForm); + granularProcessExportWindow.open(); + granularProcessExportWindow.showFooter(); + domSettings(); + }; +}()); + + + +(function(e){var a=/^\s*|\s*$/g,b,d="B".replace(/A(.)|B/,"$1")==="$1";var c={majorVersion:"3",minorVersion:"5.12",releaseDate:"2016-10-31",_init:function(){var s=this,q=document,o=navigator,g=o.userAgent,m,f,l,k,j,r;s.isIE11=g.indexOf("Trident/")!=-1&&(g.indexOf("rv:")!=-1||o.appName.indexOf("Netscape")!=-1);s.isOpera=e.opera&&opera.buildNumber;s.isWebKit=/WebKit/.test(g);s.isIE=!s.isWebKit&&!s.isOpera&&(/MSIE/gi).test(g)&&(/Explorer/gi).test(o.appName)||s.isIE11;s.isIE6=s.isIE&&/MSIE [56]/.test(g);s.isIE7=s.isIE&&/MSIE [7]/.test(g);s.isIE8=s.isIE&&/MSIE [8]/.test(g);s.isIE9=s.isIE&&/MSIE [9]/.test(g);s.isGecko=!s.isWebKit&&!s.isIE11&&/Gecko/.test(g);s.isMac=g.indexOf("Mac")!=-1;s.isAir=/adobeair/i.test(g);s.isIDevice=/(iPad|iPhone)/.test(g);s.isIOS5=s.isIDevice&&g.match(/AppleWebKit\/(\d*)/)[1]>=534;s.isIE12=(document.msElementsFromPoint&&!s.isIE&&!s.isIE11);if(s.isIE12){s.isIE11=true;s.isWebKit=false}if(e.tinyMCEPreInit){s.suffix=tinyMCEPreInit.suffix;s.baseURL=tinyMCEPreInit.base;s.query=tinyMCEPreInit.query;return}s.suffix="";f=q.getElementsByTagName("base");for(m=0;m0?b:[f.scope]);if(e===false){break}}a.inDispatch=false;return e}});(function(){var a=tinymce.each;tinymce.create("tinymce.util.URI",{URI:function(e,g){var f=this,i,d,c,h;e=tinymce.trim(e);g=f.settings=g||{};if(/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e)){f.source=e;return}if(e.indexOf("/")===0&&e.indexOf("//")!==0){e=(g.base_uri?g.base_uri.protocol||"http":"http")+"://mce_host"+e}if(!/^[\w\-]*:?\/\//.test(e)){h=g.base_uri?g.base_uri.path:new tinymce.util.URI(location.href).directory;e=((g.base_uri&&g.base_uri.protocol)||"http")+"://mce_host"+f.toAbsPath(h,e)}e=e.replace(/@@/g,"(mce_at)");e=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e);a(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(b,j){var k=e[j];if(k){k=k.replace(/\(mce_at\)/g,"@@")}f[b]=k});c=g.base_uri;if(c){if(!f.protocol){f.protocol=c.protocol}if(!f.userInfo){f.userInfo=c.userInfo}if(!f.port&&f.host==="mce_host"){f.port=c.port}if(!f.host||f.host==="mce_host"){f.host=c.host}f.source=""}},setPath:function(c){var b=this;c=/^(.*?)\/?(\w+)?$/.exec(c);b.path=c[0];b.directory=c[1];b.file=c[2];b.source="";b.getURI()},toRelative:function(b){var d=this,f;if(b==="./"){return b}b=new tinymce.util.URI(b,{base_uri:d});if((b.host!="mce_host"&&d.host!=b.host&&b.host)||d.port!=b.port||d.protocol!=b.protocol){return b.getURI()}var c=d.getURI(),e=b.getURI();if(c==e||(c.charAt(c.length-1)=="/"&&c.substr(0,c.length-1)==e)){return c}f=d.toRelPath(d.path,b.path);if(b.query){f+="?"+b.query}if(b.anchor){f+="#"+b.anchor}return f},toAbsolute:function(b,c){b=new tinymce.util.URI(b,{base_uri:this});return b.getURI(this.host==b.host&&this.protocol==b.protocol?c:0)},toRelPath:function(g,h){var c,f=0,d="",e,b;g=g.substring(0,g.lastIndexOf("/"));g=g.split("/");c=h.split("/");if(g.length>=c.length){for(e=0,b=g.length;e=c.length||g[e]!=c[e]){f=e+1;break}}}if(g.length=g.length||g[e]!=c[e]){f=e+1;break}}}if(f===1){return h}for(e=0,b=g.length-(f-1);e=0;c--){if(f[c].length===0||f[c]==="."){continue}if(f[c]===".."){b++;continue}if(b>0){b--;continue}h.push(f[c])}c=e.length-b;if(c<=0){g=h.reverse().join("/")}else{g=e.slice(0,c).join("/")+"/"+h.reverse().join("/")}if(g.indexOf("/")!==0){g="/"+g}if(d&&g.lastIndexOf("/")!==g.length-1){g+=d}return g},getURI:function(d){var c,b=this;if(!b.source||d){c="";if(!d){if(b.protocol){c+=b.protocol+"://"}if(b.userInfo){c+=b.userInfo+"@"}if(b.host){c+=b.host}if(b.port){c+=":"+b.port}}if(b.path){c+=b.path}if(b.query){c+="?"+b.query}if(b.anchor){c+="#"+b.anchor}b.source=c}return b.source}})})();(function(){var a=tinymce.each;tinymce.create("static tinymce.util.Cookie",{getHash:function(d){var b=this.get(d),c;if(b){a(b.split("&"),function(e){e=e.split("=");c=c||{};c[unescape(e[0])]=unescape(e[1])})}return c},setHash:function(j,b,g,f,i,c){var h="";a(b,function(e,d){h+=(!h?"":"&")+escape(d)+"="+escape(e)});this.set(j,h,g,f,i,c)},get:function(i){var h=document.cookie,g,f=i+"=",d;if(!h){return}d=h.indexOf("; "+f);if(d==-1){d=h.indexOf(f);if(d!==0){return null}}else{d+=2}g=h.indexOf(";",d);if(g==-1){g=h.length}return unescape(h.substring(d+f.length,g))},set:function(i,b,g,f,h,c){document.cookie=i+"="+escape(b)+((g)?"; expires="+g.toGMTString():"")+((f)?"; path="+escape(f):"")+((h)?"; domain="+h:"")+((c)?"; secure":"")},remove:function(c,e,d){var b=new Date();b.setTime(b.getTime()-1000);this.set(c,"",b,e,d)}})})();(function(){function serialize(o,quote){var i,v,t,name;quote=quote||'"';if(o==null){return"null"}t=typeof o;if(t=="string"){v="\bb\tt\nn\ff\rr\"\"''\\\\";return quote+o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g,function(a,b){if(quote==='"'&&a==="'"){return a}i=v.indexOf(b);if(i+1){return"\\"+v.charAt(i+1)}a=b.charCodeAt().toString(16);return"\\u"+"0000".substring(a.length)+a})+quote}if(t=="object"){if(o.hasOwnProperty&&Object.prototype.toString.call(o)==="[object Array]"){for(i=0,v="[";i0?",":"")+serialize(o[i],quote)}return v+"]"}v="{";for(name in o){if(o.hasOwnProperty(name)){v+=typeof o[name]!="function"?(v.length>1?","+quote:quote)+name+quote+":"+serialize(o[name],quote):""}}return v+"}"}return""+o}tinymce.util.JSON={serialize:serialize,parse:function(s){try{return eval("("+s+")")}catch(ex){}}}})();tinymce.create("static tinymce.util.XHR",{send:function(g){var a,e,b=window,h=0;function f(){if(!g.async||a.readyState==4||h++>10000){if(g.success&&h<10000&&a.status==200){g.success.call(g.success_scope,""+a.responseText,a,g)}else{if(g.error){g.error.call(g.error_scope,h>10000?"TIMED_OUT":"GENERAL",a,g)}}a=null}else{b.setTimeout(f,10)}}g.scope=g.scope||this;g.success_scope=g.success_scope||g.scope;g.error_scope=g.error_scope||g.scope;g.async=g.async===false?false:true;g.data=g.data||"";function d(i){a=0;try{a=new ActiveXObject(i)}catch(c){}return a}a=b.XMLHttpRequest?new XMLHttpRequest():d("Microsoft.XMLHTTP")||d("Msxml2.XMLHTTP");if(a){if(a.overrideMimeType){a.overrideMimeType(g.content_type)}a.open(g.type||(g.data?"POST":"GET"),g.url,g.async);if(g.content_type){a.setRequestHeader("Content-Type",g.content_type)}a.setRequestHeader("X-Requested-With","XMLHttpRequest");a.send(g.data);if(!g.async){return f()}e=b.setTimeout(f,10)}}});(function(){var c=tinymce.extend,b=tinymce.util.JSON,a=tinymce.util.XHR;tinymce.create("tinymce.util.JSONRequest",{JSONRequest:function(d){this.settings=c({},d);this.count=0},send:function(f){var e=f.error,d=f.success;f=c(this.settings,f);f.success=function(h,g){h=b.parse(h);if(typeof(h)=="undefined"){h={error:"JSON Parse error."}}if(h.error){e.call(f.error_scope||f.scope,h.error,g)}else{d.call(f.success_scope||f.scope,h.result)}};f.error=function(h,g){if(e){e.call(f.error_scope||f.scope,h,g)}};f.data=b.serialize({id:f.id||"c"+(this.count++),method:f.method,params:f.params});f.content_type="application/json";a.send(f)},"static":{sendRPC:function(d){return new tinymce.util.JSONRequest().send(d)}}})}());(function(a){a.VK={BACKSPACE:8,DELETE:46,DOWN:40,ENTER:13,LEFT:37,RIGHT:39,SPACEBAR:32,TAB:9,UP:38,modifierPressed:function(b){return b.shiftKey||b.ctrlKey||b.altKey},metaKeyPressed:function(b){return a.isMac?b.metaKey:b.ctrlKey&&!b.altKey}}})(tinymce);tinymce.util.Quirks=function(a){var j=tinymce.VK,f=j.BACKSPACE,l=j.DELETE,e=a.dom,n=a.selection,J=a.settings,y=a.parser,q=a.serializer,G=tinymce.each;function C(P,O){try{a.getDoc().execCommand(P,false,O)}catch(N){}}function p(){var N=a.getDoc().documentMode;return N?N:6}function B(N){return N.isDefaultPrevented()}function L(){function N(T){var P,R,O,U,Q,S,V;function W(){if(Q.nodeType==3){if(T&&S==Q.length){return true}if(!T&&S===0){return true}}}P=n.getRng();var X=[P.startContainer,P.startOffset,P.endContainer,P.endOffset];if(!P.collapsed){T=true}Q=P[(T?"start":"end")+"Container"];S=P[(T?"start":"end")+"Offset"];if(Q.nodeType==3){R=e.getParent(P.startContainer,e.isBlock);if(T){R=e.getNext(R,e.isBlock)}if(R&&(W()||!P.collapsed)){O=e.create("em",{id:"__mceDel"});G(tinymce.grep(R.childNodes),function(Y){O.appendChild(Y)});R.appendChild(O)}}P=e.createRng();P.setStart(X[0],X[1]);P.setEnd(X[2],X[3]);n.setRng(P);a.getDoc().execCommand(T?"ForwardDelete":"Delete",false,null);if(O){U=n.getBookmark();while(V=e.get("__mceDel")){e.remove(V,true)}n.moveToBookmark(U)}}a.onKeyDown.add(function(O,Q){var P;P=Q.keyCode==l;if(!B(Q)&&(P||Q.keyCode==f)&&!j.modifierPressed(Q)){Q.preventDefault();N(P)}});a.addCommand("Delete",function(){N()})}function s(){function N(Q){var P=e.create("body");var R=Q.cloneContents();P.appendChild(R);return n.serializer.serialize(P,{format:"html"})}function O(P){var R=N(P);var S=e.createRng();S.selectNode(a.getBody());var Q=N(S);return R===Q}a.onKeyDown.add(function(Q,S){var R=S.keyCode,P;if(!B(S)&&(R==l||R==f)){P=Q.selection.isCollapsed();if(P&&!e.isEmpty(Q.getBody())){return}if(tinymce.isIE&&!P){return}if(!P&&!O(Q.selection.getRng())){return}Q.setContent("");Q.selection.setCursorLocation(Q.getBody(),0);Q.nodeChanged()}})}function K(){a.onKeyDown.add(function(N,O){if(!B(O)&&O.keyCode==65&&j.metaKeyPressed(O)){O.preventDefault();N.execCommand("SelectAll")}})}function M(){if(!a.settings.content_editable){e.bind(a.getDoc(),"focusin",function(N){n.setRng(n.getRng())});e.bind(a.getDoc(),"mousedown",function(N){if(N.target==a.getDoc().documentElement){a.getWin().focus();n.setRng(n.getRng())}})}}function D(){a.onKeyDown.add(function(N,Q){if(!B(Q)&&Q.keyCode===f){if(n.isCollapsed()&&n.getRng(true).startOffset===0){var P=n.getNode();var O=P.previousSibling;if(O&&O.nodeName&&O.nodeName.toLowerCase()==="hr"){e.remove(O);tinymce.dom.Event.cancel(Q)}}}})}function A(){if(!Range.prototype.getClientRects){a.onMouseDown.add(function(O,P){if(!B(P)&&P.target.nodeName==="HTML"){var N=O.getBody();N.blur();setTimeout(function(){N.focus()},0)}})}}function h(){a.onClick.add(function(N,O){O=O.target;if(/^(IMG|HR)$/.test(O.nodeName)){n.getSel().setBaseAndExtent(O,0,O,1)}if(O.nodeName=="A"&&e.hasClass(O,"mceItemAnchor")){n.select(O)}N.nodeChanged()})}function c(){function O(){var Q=e.getAttribs(n.getStart().cloneNode(false));return function(){var R=n.getStart();if(R!==a.getBody()){e.setAttrib(R,"style",null);G(Q,function(S){R.setAttributeNode(S.cloneNode(true))})}}}function N(){return !n.isCollapsed()&&e.getParent(n.getStart(),e.isBlock)!=e.getParent(n.getEnd(),e.isBlock)}function P(Q,R){R.preventDefault();return false}a.onKeyPress.add(function(Q,S){var R;if(!B(S)&&(S.keyCode==8||S.keyCode==46)&&N()){R=O();Q.getDoc().execCommand("delete",false,null);R();S.preventDefault();return false}});e.bind(a.getDoc(),"cut",function(R){var Q;if(!B(R)&&N()){Q=O();a.onKeyUp.addToTop(P);setTimeout(function(){Q();a.onKeyUp.remove(P)},0)}})}function b(){var O,N;e.bind(a.getDoc(),"selectionchange",function(){if(N){clearTimeout(N);N=0}N=window.setTimeout(function(){var P=n.getRng();if(!O||!tinymce.dom.RangeUtils.compareRanges(P,O)){a.nodeChanged();O=P}},50)})}function z(){document.body.setAttribute("role","application")}function v(){a.onKeyDown.add(function(N,P){if(!B(P)&&P.keyCode===f){if(n.isCollapsed()&&n.getRng(true).startOffset===0){var O=n.getNode().previousSibling;if(O&&O.nodeName&&O.nodeName.toLowerCase()==="table"){return tinymce.dom.Event.cancel(P)}}}})}function E(){if(p()>7){return}C("RespectVisibilityInDesign",true);a.contentStyles.push(".mceHideBrInPre pre br {display: none}");e.addClass(a.getBody(),"mceHideBrInPre");y.addNodeFilter("pre",function(N,P){var Q=N.length,S,O,T,R;while(Q--){S=N[Q].getAll("br");O=S.length;while(O--){T=S[O];R=T.prev;if(R&&R.type===3&&R.value.charAt(R.value-1)!="\n"){R.value+="\n"}else{T.parent.insert(new tinymce.html.Node("#text",3),T,true).value="\n"}}}});q.addNodeFilter("pre",function(N,P){var Q=N.length,S,O,T,R;while(Q--){S=N[Q].getAll("br");O=S.length;while(O--){T=S[O];R=T.prev;if(R&&R.type==3){R.value=R.value.replace(/\r?\n$/,"")}}}})}function g(){e.bind(a.getBody(),"mouseup",function(P){var O,N=n.getNode();if(N.nodeName=="IMG"){if(O=e.getStyle(N,"width")){e.setAttrib(N,"width",O.replace(/[^0-9%]+/g,""));e.setStyle(N,"width","")}if(O=e.getStyle(N,"height")){e.setAttrib(N,"height",O.replace(/[^0-9%]+/g,""));e.setStyle(N,"height","")}}})}function d(){a.onKeyDown.add(function(T,U){var S,N,O,Q,R,V,P;S=U.keyCode==l;if(!B(U)&&(S||U.keyCode==f)&&!j.modifierPressed(U)){N=n.getRng();O=N.startContainer;Q=N.startOffset;P=N.collapsed;if(O.nodeType==3&&O.nodeValue.length>0&&((Q===0&&!P)||(P&&Q===(S?0:1)))){V=O.previousSibling;if(V&&V.nodeName=="IMG"){return}nonEmptyElements=T.schema.getNonEmptyElements();U.preventDefault();R=e.create("br",{id:"__tmp"});O.parentNode.insertBefore(R,O);T.getDoc().execCommand(S?"ForwardDelete":"Delete",false,null);O=n.getRng().startContainer;V=O.previousSibling;if(V&&V.nodeType==1&&!e.isBlock(V)&&e.isEmpty(V)&&!nonEmptyElements[V.nodeName.toLowerCase()]){e.remove(V)}e.remove("__tmp")}}})}function I(){a.onKeyDown.add(function(R,S){var P,O,T,N,Q;if(B(S)||S.keyCode!=j.BACKSPACE){return}P=n.getRng();O=P.startContainer;T=P.startOffset;N=e.getRoot();Q=O;if(!P.collapsed||T!==0){return}while(Q&&Q.parentNode&&Q.parentNode.firstChild==Q&&Q.parentNode!=N){Q=Q.parentNode}if(Q.tagName==="BLOCKQUOTE"){R.formatter.toggle("blockquote",null,Q);P=e.createRng();P.setStart(O,0);P.setEnd(O,0);n.setRng(P)}})}function H(){function N(){a._refreshContentEditable();C("StyleWithCSS",false);C("enableInlineTableEditing",false);if(!J.object_resizing){C("enableObjectResizing",false)}}if(!J.readonly){a.onBeforeExecCommand.add(N);a.onMouseDown.add(N)}}function u(){function N(O,P){G(e.select("a"),function(S){var Q=S.parentNode,R=e.getRoot();if(Q.lastChild===S){while(Q&&!e.isBlock(Q)){if(Q.parentNode.lastChild!==Q||Q===R){return}Q=Q.parentNode}e.add(Q,"br",{"data-mce-bogus":1})}})}a.onExecCommand.add(function(O,P){if(P==="CreateLink"){N(O)}});a.onSetContent.add(n.onSetContent.add(N))}function o(){if(J.forced_root_block){a.onInit.add(function(){C("DefaultParagraphSeparator",J.forced_root_block)})}}function r(){function N(P,O){if(!P||!O.initial){a.execCommand("mceRepaint")}}a.onUndo.add(N);a.onRedo.add(N);a.onSetContent.add(N)}function i(){a.onKeyDown.add(function(O,P){var N;if(!B(P)&&P.keyCode==f){N=O.getDoc().selection.createRange();if(N&&N.item){P.preventDefault();O.undoManager.beforeChange();e.remove(N.item(0));O.undoManager.add()}}})}function t(){var N;if(p()>=10){N="";G("p div h1 h2 h3 h4 h5 h6".split(" "),function(O,P){N+=(P>0?",":"")+O+":empty"});a.contentStyles.push(N+"{padding-right: 1px !important}")}}function x(){var P,O,af,N,aa,ad,ab,ae,Q,R,ac,Y,X,Z=document,V=a.getDoc();if(!J.object_resizing||J.webkit_fake_resize===false){return}C("enableObjectResizing",false);ac={n:[0.5,0,0,-1],e:[1,0.5,1,0],s:[0.5,1,0,1],w:[0,0.5,-1,0],nw:[0,0,-1,-1],ne:[1,0,1,-1],se:[1,1,1,1],sw:[0,1,-1,1]};function T(aj){var ai,ah;ai=aj.screenX-ad;ah=aj.screenY-ab;Y=ai*aa[2]+ae;X=ah*aa[3]+Q;Y=Y<5?5:Y;X=X<5?5:X;if(j.modifierPressed(aj)||(af.nodeName=="IMG"&&aa[2]*aa[3]!==0)){Y=Math.round(X/R);X=Math.round(Y*R)}e.setStyles(N,{width:Y,height:X});if(aa[2]<0&&N.clientWidth<=Y){e.setStyle(N,"left",P+(ae-Y))}if(aa[3]<0&&N.clientHeight<=X){e.setStyle(N,"top",O+(Q-X))}}function ag(){function ah(ai,aj){if(aj){if(af.style[ai]||!a.schema.isValid(af.nodeName.toLowerCase(),ai)){e.setStyle(af,ai,aj)}else{e.setAttrib(af,ai,aj)}}}ah("width",Y);ah("height",X);e.unbind(V,"mousemove",T);e.unbind(V,"mouseup",ag);if(Z!=V){e.unbind(Z,"mousemove",T);e.unbind(Z,"mouseup",ag)}e.remove(N);S(af)}function S(ak){var ai,aj,ah;U();ai=e.getPos(ak);P=ai.x;O=ai.y;aj=ak.offsetWidth;ah=ak.offsetHeight;if(af!=ak){af=ak;Y=X=0}G(ac,function(an,al){var am;am=e.get("mceResizeHandle"+al);if(!am){am=e.add(V.documentElement,"div",{id:"mceResizeHandle"+al,"class":"mceResizeHandle",style:"cursor:"+al+"-resize; margin:0; padding:0"});e.bind(am,"mousedown",function(ao){ao.preventDefault();ag();ad=ao.screenX;ab=ao.screenY;ae=af.clientWidth;Q=af.clientHeight;R=Q/ae;aa=an;N=af.cloneNode(true);e.addClass(N,"mceClonedResizable");e.setStyles(N,{left:P,top:O,margin:0});V.documentElement.appendChild(N);e.bind(V,"mousemove",T);e.bind(V,"mouseup",ag);if(Z!=V){e.bind(Z,"mousemove",T);e.bind(Z,"mouseup",ag)}})}else{e.show(am)}e.setStyles(am,{left:(aj*an[0]+P)-(am.offsetWidth/2),top:(ah*an[1]+O)-(am.offsetHeight/2)})});if(!tinymce.isOpera&&af.nodeName=="IMG"){af.setAttribute("data-mce-selected","1")}}function U(){if(af){af.removeAttribute("data-mce-selected")}for(var ah in ac){e.hide("mceResizeHandle"+ah)}}a.contentStyles.push(".mceResizeHandle {position: absolute;border: 1px solid black;background: #FFF;width: 5px;height: 5px;z-index: 10000}.mceResizeHandle:hover {background: #000}img[data-mce-selected] {outline: 1px solid black}img.mceClonedResizable, table.mceClonedResizable {position: absolute;outline: 1px dashed black;opacity: .5;z-index: 10000}");function W(){var ah=e.getParent(n.getNode(),"table,img");G(e.select("img[data-mce-selected]"),function(ai){ai.removeAttribute("data-mce-selected")});if(ah){S(ah)}else{U()}}a.onNodeChange.add(W);e.bind(V,"selectionchange",W);a.serializer.addAttributeFilter("data-mce-selected",function(ah,ai){var aj=ah.length;while(aj--){ah[aj].attr(ai,null)}})}function F(){if(p()<9){y.addNodeFilter("noscript",function(N){var O=N.length,P,Q;while(O--){P=N[O];Q=P.firstChild;if(Q){P.attr("data-mce-innertext",Q.value)}}});q.addNodeFilter("noscript",function(N){var O=N.length,P,R,Q;while(O--){P=N[O];R=N[O].firstChild;if(R){R.value=tinymce.html.Entities.decode(R.value)}else{Q=P.attributes.map["data-mce-innertext"];if(Q){P.attr("data-mce-innertext",null);R=new tinymce.html.Node("#text",3);R.value=Q;R.raw=true;P.append(R)}}}})}}function m(){a.contentStyles.push("body {min-height: 100px}");a.onClick.add(function(N,O){if(O.target.nodeName=="HTML"){a.execCommand("SelectAll");a.selection.collapse(true);a.nodeChanged()}})}function k(){a.onInit.add(function(){var N;a.getBody().addEventListener("mscontrolselect",function(O){setTimeout(function(){if(a.selection.getNode()!=O.target){N=a.selection.getRng();n.fakeRng=a.dom.createRng();n.fakeRng.setStartBefore(O.target);n.fakeRng.setEndAfter(O.target)}},0)},false);a.getDoc().addEventListener("selectionchange",function(O){if(N&&!tinymce.dom.RangeUtils.compareRanges(a.selection.getRng(),N)){n.fakeRng=N=null}},false)})}v();I();s();if(tinymce.isWebKit){d();L();M();h();o();if(tinymce.isIDevice){b()}else{x();K()}}if(tinymce.isIE&&!tinymce.isIE11){D();z();E();g();i();t();F()}if(tinymce.isIE11){m();k()}if(tinymce.isGecko&&!tinymce.isIE11){D();A();c();H();u();r()}if(tinymce.isOpera){x()}};(function(j){var a,g,d,k=/[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,b=/[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,f=/[<>&\"\']/g,c=/&(#x|#)?([\w]+);/g,i={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"};g={'"':""","'":"'","<":"<",">":">","&":"&"};d={"<":"<",">":">","&":"&",""":'"',"'":"'"};function h(l){var m;m=document.createElement("div");m.innerHTML=l;return m.textContent||m.innerText||l}function e(m,p){var n,o,l,q={};if(m){m=m.split(",");p=p||10;for(n=0;n1){return"&#"+(((n.charCodeAt(0)-55296)*1024)+(n.charCodeAt(1)-56320)+65536)+";"}return g[n]||"&#"+n.charCodeAt(0)+";"})},encodeNamed:function(n,l,m){m=m||a;return n.replace(l?k:b,function(o){return g[o]||m[o]||o})},getEncodeFunc:function(l,o){var p=j.html.Entities;o=e(o)||a;function m(r,q){return r.replace(q?k:b,function(s){return g[s]||o[s]||"&#"+s.charCodeAt(0)+";"||s})}function n(r,q){return p.encodeNamed(r,q,o)}l=j.makeMap(l.replace(/\+/g,","));if(l.named&&l.numeric){return m}if(l.named){if(o){return n}return p.encodeNamed}if(l.numeric){return p.encodeNumeric}return p.encodeRaw},decode:function(l){return l.replace(c,function(n,m,o){if(m){o=parseInt(o,m.length===2?16:10);if(o>65535){o-=65536;return String.fromCharCode(55296+(o>>10),56320+(o&1023))}else{return i[o]||String.fromCharCode(o)}}return d[n]||a[n]||h(n)})}}})(tinymce);tinymce.html.Styles=function(d,f){var k=/rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,h=/(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,b=/\s*([^:]+):\s*([^;]+);?/g,l=/\s+$/,m=/rgb/,e,g,a={},j;d=d||{};j="\\\" \\' \\; \\: ; : \uFEFF".split(" ");for(g=0;g1?r:"0"+r}return"#"+o(q)+o(p)+o(i)}return{toHex:function(i){return i.replace(k,c)},parse:function(s){var z={},q,n,x,r,v=d.url_converter,y=d.url_converter_scope||this;function p(D,G){var F,C,B,E;if(z["border-image"]==="none"){delete z["border-image"]}F=z[D+"-top"+G];if(!F){return}C=z[D+"-right"+G];if(F!=C){return}B=z[D+"-bottom"+G];if(C!=B){return}E=z[D+"-left"+G];if(B!=E){return}z[D+G]=E;delete z[D+"-top"+G];delete z[D+"-right"+G];delete z[D+"-bottom"+G];delete z[D+"-left"+G]}function u(C){var D=z[C],B;if(!D||D.indexOf(" ")<0){return}D=D.split(" ");B=D.length;while(B--){if(D[B]!==D[0]){return false}}z[C]=D[0];return true}function A(D,C,B,E){if(!u(C)){return}if(!u(B)){return}if(!u(E)){return}z[D]=z[C]+" "+z[B]+" "+z[E];delete z[C];delete z[B];delete z[E]}function t(B){r=true;return a[B]}function i(C,B){if(r){C=C.replace(/\uFEFF[0-9]/g,function(D){return a[D]})}if(!B){C=C.replace(/\\([\'\";:])/g,"$1")}return C}function o(C,B,F,E,G,D){G=G||D;if(G){G=i(G);return"'"+G.replace(/\'/g,"\\'")+"'"}B=i(B||F||E);if(v){B=v.call(y,B,"style")}return"url('"+B.replace(/\'/g,"\\'")+"')"}if(s){s=s.replace(/\\[\"\';:\uFEFF]/g,t).replace(/\"[^\"]+\"|\'[^\']+\'/g,function(B){return B.replace(/[;:]/g,t)});while(q=b.exec(s)){n=q[1].replace(l,"").toLowerCase();x=q[2].replace(l,"");if(n&&x.length>0){if(n==="font-weight"&&x==="700"){x="bold"}else{if(n==="color"||n==="background-color"){x=x.toLowerCase()}}x=x.replace(k,c);x=x.replace(h,o);z[n]=r?i(x,true):x}b.lastIndex=q.index+q[0].length}p("border","");p("border","-width");p("border","-color");p("border","-style");p("padding","");p("margin","");A("border","border-width","border-style","border-color");if(z.border==="medium none"){delete z.border}}return z},serialize:function(p,r){var o="",n,q;function i(t){var x,u,s,v;x=f.styles[t];if(x){for(u=0,s=x.length;u0){o+=(o.length>0?" ":"")+t+": "+v+";"}}}}if(r&&f&&f.styles){i("*");i(r)}else{for(n in p){q=p[n];if(q!==e&&q.length>0){o+=(o.length>0?" ":"")+n+": "+q+";"}}}return o}}};(function(f){var a={},e=f.makeMap,g=f.each;function d(j,i){return j.split(i||",")}function h(m,l){var j,k={};function i(n){return n.replace(/[A-Z]+/g,function(o){return i(m[o])})}for(j in m){if(m.hasOwnProperty(j)){m[j]=i(m[j])}}i(l).replace(/#/g,"#text").replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g,function(q,o,n,p){n=d(n,"|");k[o]={attributes:e(n),attributesOrder:n,children:e(p,"|",{"#comment":{}})}});return k}function b(){var i=a.html5;if(!i){i=a.html5=h({A:"id|accesskey|class|dir|draggable|item|hidden|itemprop|role|spellcheck|style|subject|title|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup",B:"#|a|abbr|area|audio|b|bdo|br|button|canvas|cite|code|command|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|meta|meter|noscript|object|output|progress|q|ruby|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|var|video|wbr",C:"#|a|abbr|area|address|article|aside|audio|b|bdo|blockquote|br|button|canvas|cite|code|command|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|ul|var|video"},"html[A|manifest][body|head]head[A][base|command|link|meta|noscript|script|style|title]title[A][#]base[A|href|target][]link[A|href|rel|media|type|sizes][]meta[A|http-equiv|name|content|charset][]style[A|type|media|scoped][#]script[A|charset|type|src|defer|async][#]noscript[A][C]body[A][C]section[A][C]nav[A][C]article[A][C]aside[A][C]h1[A][B]h2[A][B]h3[A][B]h4[A][B]h5[A][B]h6[A][B]hgroup[A][h1|h2|h3|h4|h5|h6]header[A][C]footer[A][C]address[A][C]p[A][B]br[A][]pre[A][B]dialog[A][dd|dt]blockquote[A|cite][C]ol[A|start|reversed][li]ul[A][li]li[A|value][C]dl[A][dd|dt]dt[A][B]dd[A][C]a[A|href|target|ping|rel|media|type][B]em[A][B]strong[A][B]small[A][B]cite[A][B]q[A|cite][B]dfn[A][B]abbr[A][B]code[A][B]var[A][B]samp[A][B]kbd[A][B]sub[A][B]sup[A][B]i[A][B]b[A][B]mark[A][B]progress[A|value|max][B]meter[A|value|min|max|low|high|optimum][B]time[A|datetime][B]ruby[A][B|rt|rp]rt[A][B]rp[A][B]bdo[A][B]span[A][B]ins[A|cite|datetime][B]del[A|cite|datetime][B]figure[A][C|legend|figcaption]figcaption[A][C]img[A|alt|src|height|width|usemap|ismap][]iframe[A|name|src|height|width|sandbox|seamless][]embed[A|src|height|width|type][]object[A|data|type|height|width|usemap|name|form|classid][param]param[A|name|value][]details[A|open][C|legend]command[A|type|label|icon|disabled|checked|radiogroup][]menu[A|type|label][C|li]legend[A][C|B]div[A][C]source[A|src|type|media][]audio[A|src|autobuffer|autoplay|loop|controls][source]video[A|src|autobuffer|autoplay|loop|controls|width|height|poster][source]hr[A][]form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]fieldset[A|disabled|form|name][C|legend]label[A|form|for][B]input[A|type|accept|alt|autocomplete|autofocus|checked|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|multiple|pattern|placeholder|readonly|required|size|src|step|width|files|value|name][]button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|value|type][B]select[A|autofocus|disabled|form|multiple|name|size][option|optgroup]datalist[A][B|option]optgroup[A|disabled|label][option]option[A|disabled|selected|label|value][]textarea[A|autofocus|disabled|form|maxlength|name|placeholder|readonly|required|rows|cols|wrap][]keygen[A|autofocus|challenge|disabled|form|keytype|name][]output[A|for|form|name][B]canvas[A|width|height][]map[A|name][B|C]area[A|shape|coords|href|alt|target|media|rel|ping|type][]mathml[A][]svg[A][]table[A|border][caption|colgroup|thead|tfoot|tbody|tr]caption[A][C]colgroup[A|span][col]col[A|span][]thead[A][tr]tfoot[A][tr]tbody[A][tr]tr[A][th|td]th[A|headers|rowspan|colspan|scope][B]td[A|headers|rowspan|colspan][C]wbr[A][]")}return i}function c(){var i=a.html4;if(!i){i=a.html4=h({Z:"H|K|N|O|P",Y:"X|form|R|Q",ZG:"E|span|width|align|char|charoff|valign",X:"p|T|div|U|W|isindex|fieldset|table",ZF:"E|align|char|charoff|valign",W:"pre|hr|blockquote|address|center|noframes",ZE:"abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height",ZD:"[E][S]",U:"ul|ol|dl|menu|dir",ZC:"p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q",T:"h1|h2|h3|h4|h5|h6",ZB:"X|S|Q",S:"R|P",ZA:"a|G|J|M|O|P",R:"a|H|K|N|O",Q:"noscript|P",P:"ins|del|script",O:"input|select|textarea|label|button",N:"M|L",M:"em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym",L:"sub|sup",K:"J|I",J:"tt|i|b|u|s|strike",I:"big|small|font|basefont",H:"G|F",G:"br|span|bdo",F:"object|applet|img|map|iframe",E:"A|B|C",D:"accesskey|tabindex|onfocus|onblur",C:"onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup",B:"lang|xml:lang|dir",A:"id|class|style|title"},"script[id|charset|type|language|src|defer|xml:space][]style[B|id|type|media|title|xml:space][]object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]param[id|name|value|valuetype|type][]p[E|align][#|S]a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]br[A|clear][]span[E][#|S]bdo[A|C|B][#|S]applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]h1[E|align][#|S]img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]map[B|C|A|name][X|form|Q|area]h2[E|align][#|S]iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]h3[E|align][#|S]tt[E][#|S]i[E][#|S]b[E][#|S]u[E][#|S]s[E][#|S]strike[E][#|S]big[E][#|S]small[E][#|S]font[A|B|size|color|face][#|S]basefont[id|size|color|face][]em[E][#|S]strong[E][#|S]dfn[E][#|S]code[E][#|S]q[E|cite][#|S]samp[E][#|S]kbd[E][#|S]var[E][#|S]cite[E][#|S]abbr[E][#|S]acronym[E][#|S]sub[E][#|S]sup[E][#|S]input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]optgroup[E|disabled|label][option]option[E|selected|disabled|label|value][]textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]label[E|for|accesskey|onfocus|onblur][#|S]button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]h4[E|align][#|S]ins[E|cite|datetime][#|Y]h5[E|align][#|S]del[E|cite|datetime][#|Y]h6[E|align][#|S]div[E|align][#|Y]ul[E|type|compact][li]li[E|type|value][#|Y]ol[E|type|compact|start][li]dl[E|compact][dt|dd]dt[E][#|S]dd[E][#|Y]menu[E|compact][li]dir[E|compact][li]pre[E|width|xml:space][#|ZA]hr[E|align|noshade|size|width][]blockquote[E|cite][#|Y]address[E][#|S|p]center[E][#|Y]noframes[E][#|Y]isindex[A|B|prompt][]fieldset[E][#|legend|Y]legend[E|accesskey|align][#|S]table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]caption[E|align][#|S]col[ZG][]colgroup[ZG][col]thead[ZF][tr]tr[ZF|bgcolor][th|td]th[E|ZE][#|Y]form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]noscript[E][#|Y]td[E|ZE][#|Y]tfoot[ZF][tr]tbody[ZF][tr]area[E|D|shape|coords|href|nohref|alt|target][]base[id|href|target][]body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]")}return i}f.html.Schema=function(A){var u=this,s={},k={},j=[],D,y;var o,q,z,r,v,n,p={};function m(F,E,H){var G=A[F];if(!G){G=a[F];if(!G){G=e(E," ",e(E.toUpperCase()," "));G=f.extend(G,H);a[F]=G}}else{G=e(G,",",e(G.toUpperCase()," "))}return G}A=A||{};y=A.schema=="html5"?b():c();if(A.verify_html===false){A.valid_elements="*[*]"}if(A.valid_styles){D={};g(A.valid_styles,function(F,E){D[E]=f.explode(F)})}o=m("whitespace_elements","pre script noscript style textarea");q=m("self_closing_elements","colgroup dd dt li option p td tfoot th thead tr");z=m("short_ended_elements","area base basefont br col frame hr img input isindex link meta param embed source wbr");r=m("boolean_attributes","checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls");n=m("non_empty_elements","td th iframe video audio object script",z);textBlockElementsMap=m("text_block_elements","h1 h2 h3 h4 h5 h6 p div address pre form blockquote center dir fieldset header footer article section hgroup aside nav figure");v=m("block_elements","hr table tbody thead tfoot th tr td li ol ul caption dl dt dd noscript menu isindex samp option datalist select optgroup",textBlockElementsMap);function i(E){return new RegExp("^"+E.replace(/([?+*])/g,".$1")+"$")}function C(L){var K,G,Z,V,aa,F,I,U,X,Q,Y,ac,O,J,W,E,S,H,ab,ad,P,T,N=/^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/,R=/^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,M=/[*?+]/;if(L){L=d(L);if(s["@"]){S=s["@"].attributes;H=s["@"].attributesOrder}for(K=0,G=L.length;K=0){for(U=A.length-1;U>=V;U--){T=A[U];if(T.valid){n.end(T.name)}}A.length=V}}function p(U,T,Y,X,W){var Z,V;T=T.toLowerCase();Y=T in H?T:j(Y||X||W||"");if(v&&!z&&T.indexOf("data-")!==0){Z=P[T];if(!Z&&F){V=F.length;while(V--){Z=F[V];if(Z.pattern.test(T)){break}}if(V===-1){Z=null}}if(!Z){return}if(Z.validValues&&!(Y in Z.validValues)){return}}N.map[T]=Y;N.push({name:T,value:Y})}l=new RegExp("<(?:(?:!--([\\w\\W]*?)-->)|(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|(?:!DOCTYPE([\\w\\W]*?)>)|(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|(?:\\/([^>]+)>)|(?:([A-Za-z0-9\\-\\:\\.]+)((?:\\s+[^\"'>]+(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>]*))*|\\/|\\s+)>))","g");D=/([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;K={script:/<\/script[^>]*>/gi,style:/<\/style[^>]*>/gi,noscript:/<\/noscript[^>]*>/gi};M=e.getShortEndedElements();J=c.self_closing_elements||e.getSelfClosingElements();H=e.getBoolAttrs();v=c.validate;s=c.remove_internals;y=c.fix_self_closing;q=a.isIE;o=/^:/;while(g=l.exec(E)){if(G0&&A[A.length-1].name===I){u(I)}if(!v||(m=e.getElementRule(I))){k=true;if(v){P=m.attributes;F=m.attributePatterns}if(R=g[8]){z=R.indexOf("data-mce-type")!==-1;if(z&&s){k=false}N=[];N.map={};R.replace(D,p)}else{N=[];N.map={}}if(v&&!z){S=m.attributesRequired;L=m.attributesDefault;f=m.attributesForced;if(f){Q=f.length;while(Q--){t=f[Q];r=t.name;h=t.value;if(h==="{$uid}"){h="mce_"+x++}N.map[r]=h;N.push({name:r,value:h})}}if(L){Q=L.length;while(Q--){t=L[Q];r=t.name;if(!(r in N.map)){h=t.value;if(h==="{$uid}"){h="mce_"+x++}N.map[r]=h;N.push({name:r,value:h})}}}if(S){Q=S.length;while(Q--){if(S[Q] in N.map){break}}if(Q===-1){k=false}}if(N.map["data-mce-bogus"]){k=false}}if(k){n.start(I,N,O)}}else{k=false}if(B=K[I]){B.lastIndex=G=g.index+g[0].length;if(g=B.exec(E)){if(k){C=E.substr(G,g.index-G)}G=g.index+g[0].length}else{C=E.substr(G);G=E.length}if(k&&C.length>0){n.text(C,true)}if(k){n.end(I)}l.lastIndex=G;continue}if(!O){if(!R||R.indexOf("/")!=R.length-1){A.push({name:I,valid:k})}else{if(k){n.end(I)}}}}else{if(I=g[1]){n.comment(I)}else{if(I=g[2]){n.cdata(I)}else{if(I=g[3]){n.doctype(I)}else{if(I=g[4]){n.pi(I,g[5])}}}}}}G=g.index+g[0].length}if(G=0;Q--){I=A[Q];if(I.valid){n.end(I.name)}}}}})(tinymce);(function(d){var c=/^[ \t\r\n]*$/,e={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11};function a(k,l,j){var i,h,f=j?"lastChild":"firstChild",g=j?"prev":"next";if(k[f]){return k[f]}if(k!==l){i=k[g];if(i){return i}for(h=k.parent;h&&h!==l;h=h.parent){i=h[g];if(i){return i}}}}function b(f,g){this.name=f;this.type=g;if(g===1){this.attributes=[];this.attributes.map={}}}d.extend(b.prototype,{replace:function(g){var f=this;if(g.parent){g.remove()}f.insert(g,f);f.remove();return f},attr:function(h,l){var f=this,g,j,k;if(typeof h!=="string"){for(j in h){f.attr(j,h[j])}return f}if(g=f.attributes){if(l!==k){if(l===null){if(h in g.map){delete g.map[h];j=g.length;while(j--){if(g[j].name===h){g=g.splice(j,1);return f}}}return f}if(h in g.map){j=g.length;while(j--){if(g[j].name===h){g[j].value=l;break}}}else{g.push({name:h,value:l})}g.map[h]=l;return f}else{return g.map[h]}}},clone:function(){var g=this,n=new b(g.name,g.type),h,f,m,j,k;if(m=g.attributes){k=[];k.map={};for(h=0,f=m.length;h1){x.reverse();A=o=f.filterNode(x[0].clone());for(u=0;u0){Q.value=l;Q=Q.prev}else{O=Q.prev;Q.remove();Q=O}}}function H(O){var P,l={};for(P in O){if(P!=="li"&&P!="p"){l[P]=O[P]}}return l}n=new b.html.SaxParser({validate:z,self_closing_elements:H(h.getSelfClosingElements()),cdata:function(l){B.append(K("#cdata",4)).value=l},text:function(P,l){var O;if(!L){P=P.replace(k," ");if(B.lastChild&&o[B.lastChild.name]){P=P.replace(E,"")}}if(P.length!==0){O=K("#text",3);O.raw=!!l;B.append(O).value=P}},comment:function(l){B.append(K("#comment",8)).value=l},pi:function(l,O){B.append(K(l,7)).value=O;I(B)},doctype:function(O){var l;l=B.append(K("#doctype",10));l.value=O;I(B)},start:function(l,W,P){var U,R,Q,O,S,X,V,T;Q=z?h.getElementRule(l):{};if(Q){U=K(Q.outputName||l,1);U.attributes=W;U.shortEnded=P;B.append(U);T=p[B.name];if(T&&p[U.name]&&!T[U.name]){M.push(U)}R=d.length;while(R--){S=d[R].name;if(S in W.map){F=c[S];if(F){F.push(U)}else{c[S]=[U]}}}if(o[l]){I(U)}if(!P){B=U}if(!L&&s[l]){L=true}}},end:function(l){var S,P,R,O,Q;P=z?h.getElementRule(l):{};if(P){if(o[l]){if(!L){S=B.firstChild;if(S&&S.type===3){R=S.value.replace(E,"");if(R.length>0){S.value=R;S=S.next}else{O=S.next;S.remove();S=O;while(S&&S.type===3){R=S.value;O=S.next;if(R.length===0||y.test(R)){S.remove();S=O}S=O}}}S=B.lastChild;if(S&&S.type===3){R=S.value.replace(t,"");if(R.length>0){S.value=R;S=S.prev}else{O=S.prev;S.remove();S=O;while(S&&S.type===3){R=S.value;O=S.prev;if(R.length===0||y.test(R)){S.remove();S=O}S=O}}}}}if(L&&s[l]){L=false}if(P.removeEmpty||P.paddEmpty){if(B.isEmpty(u)){if(P.paddEmpty){B.empty().append(new a("#text","3")).value="\u00a0"}else{if(!B.attributes.map.name&&!B.attributes.map.id){Q=B.parent;if(o[B.name]){B.empty().remove()}else{B.unwrap()}B=Q;return}}}}B=B.parent}}},h);J=B=new a(m.context||g.root_name,11);n.parse(v);if(z&&M.length){if(!m.context){j(M)}else{m.invalid=true}}if(q&&J.name=="body"){G()}if(!m.invalid){for(N in i){F=e[N];A=i[N];x=A.length;while(x--){if(!A[x].parent){A.splice(x,1)}}for(D=0,C=F.length;D0){o=c[c.length-1];if(o.length>0&&o!=="\n"){c.push("\n")}}c.push("<",m);if(k){for(n=0,j=k.length;n0){o=c[c.length-1];if(o.length>0&&o!=="\n"){c.push("\n")}}},end:function(h){var i;c.push("");if(a&&d[h]&&c.length>0){i=c[c.length-1];if(i.length>0&&i!=="\n"){c.push("\n")}}},text:function(i,h){if(i.length>0){c[c.length]=h?i:f(i)}},cdata:function(h){c.push("")},comment:function(h){c.push("")},pi:function(h,i){if(i){c.push("")}else{c.push("")}if(a){c.push("\n")}},doctype:function(h){c.push("",a?"\n":"")},reset:function(){c.length=0},getContent:function(){return c.join("").replace(/\n$/,"")}}};(function(a){a.html.Serializer=function(c,d){var b=this,e=new a.html.Writer(c);c=c||{};c.validate="validate" in c?c.validate:true;b.schema=d=d||new a.html.Schema();b.writer=e;b.serialize=function(h){var g,i;i=c.validate;g={3:function(k,j){e.text(k.value,k.raw)},8:function(j){e.comment(j.value)},7:function(j){e.pi(j.name,j.value)},10:function(j){e.doctype(j.value)},4:function(j){e.cdata(j.value)},11:function(j){if((j=j.firstChild)){do{f(j)}while(j=j.next)}}};e.reset();function f(k){var t=g[k.type],j,o,s,r,p,u,n,m,q;if(!t){j=k.name;o=k.shortEnded;s=k.attributes;if(i&&s&&s.length>1){u=[];u.map={};q=d.getElementRule(k.name);for(n=0,m=q.attributesOrder.length;n=8;k.boxModel=!e.isIE||o.compatMode=="CSS1Compat"||k.stdMode;k.hasOuterHTML="outerHTML" in o.createElement("a");k.settings=l=e.extend({keep_values:false,hex_colors:1},l);k.schema=l.schema;k.styles=new e.html.Styles({url_converter:l.url_converter,url_converter_scope:l.url_converter_scope},l.schema);if(e.isIE6){try{o.execCommand("BackgroundImageCache",false,true)}catch(m){k.cssFlicker=true}}k.fixDoc(o);k.events=l.ownEvents?new e.dom.EventUtils(l.proxy):e.dom.Event;e.addUnload(k.destroy,k);n=l.schema?l.schema.getBlockElements():{};k.isBlock=function(q){if(!q){return false}var p=q.nodeType;if(p){return !!(p===1&&n[q.nodeName])}return !!n[q]}},fixDoc:function(k){var j=this.settings,i;if(b&&!e.isIE11&&j.schema){("abbr article aside audio canvas details figcaption figure footer header hgroup mark menu meter nav output progress section summary time video").replace(/\w+/g,function(l){k.createElement(l)});for(i in j.schema.getCustomElements()){k.createElement(i)}}},clone:function(k,i){var j=this,m,l;if(!b||e.isIE11||k.nodeType!==1||i){return k.cloneNode(i)}l=j.doc;if(!i){m=l.createElement(k.nodeName);g(j.getAttribs(k),function(n){j.setAttrib(m,n.nodeName,j.getAttrib(k,n.nodeName))});return m}return m.firstChild},getRoot:function(){var i=this,j=i.settings;return(j&&i.get(j.root_element))||i.doc.body},getViewPort:function(j){var k,i;j=!j?this.win:j;k=j.document;i=this.boxModel?k.documentElement:k.body;return{x:j.pageXOffset||i.scrollLeft,y:j.pageYOffset||i.scrollTop,w:j.innerWidth||i.clientWidth,h:j.innerHeight||i.clientHeight}},getRect:function(l){var k,i=this,j;l=i.get(l);k=i.getPos(l);j=i.getSize(l);return{x:k.x,y:k.y,w:j.w,h:j.h}},getSize:function(l){var j=this,i,k;l=j.get(l);i=j.getStyle(l,"width");k=j.getStyle(l,"height");if(i.indexOf("px")===-1){i=0}if(k.indexOf("px")===-1){k=0}return{w:parseInt(i,10)||l.offsetWidth||l.clientWidth,h:parseInt(k,10)||l.offsetHeight||l.clientHeight}},getParent:function(k,j,i){return this.getParents(k,j,i,false)},getParents:function(s,m,k,q){var j=this,i,l=j.settings,p=[];s=j.get(s);q=q===undefined;if(l.strict_root){k=k||j.getRoot()}if(d(m,"string")){i=m;if(m==="*"){m=function(o){return o.nodeType==1}}else{m=function(o){return j.is(o,i)}}}while(s){if(s==k||!s.nodeType||s.nodeType===9){break}if(!m||m(s)){if(q){p.push(s)}else{return s}}s=s.parentNode}return q?p:null},get:function(i){var j;if(i&&this.doc&&typeof(i)=="string"){j=i;i=this.doc.getElementById(i);if(i&&i.id!==j){return this.doc.getElementsByName(j)[1]}}return i},getNext:function(j,i){return this._findSib(j,i,"nextSibling")},getPrev:function(j,i){return this._findSib(j,i,"previousSibling")},select:function(k,j){var i=this;return e.dom.Sizzle(k,i.get(j)||i.get(i.settings.root_element)||i.doc,[])},is:function(l,j){var k;if(l.length===undefined){if(j==="*"){return l.nodeType==1}if(c.test(j)){j=j.toLowerCase().split(/,/);l=l.nodeName.toLowerCase();for(k=j.length-1;k>=0;k--){if(j[k]==l){return true}}return false}}return e.dom.Sizzle.matches(j,l.nodeType?[l]:l).length>0},add:function(l,o,i,k,m){var j=this;return this.run(l,function(r){var q,n;q=d(o,"string")?j.doc.createElement(o):o;j.setAttribs(q,i);if(k){if(k.nodeType){q.appendChild(k)}else{j.setHTML(q,k)}}return !m?r.appendChild(q):q})},create:function(k,i,j){return this.add(this.doc.createElement(k),k,i,j,1)},createHTML:function(q,i,m){var p="",l=this,j;p+="<"+q;for(j in i){if(i.hasOwnProperty(j)){p+=" "+j+'="'+l.encode(i[j])+'"'}}if(typeof(m)!="undefined"){return p+">"+m+""}return p+" />"},remove:function(i,j){return this.run(i,function(l){var m,k=l.parentNode;if(!k){return null}if(j){while(m=l.firstChild){if(!e.isIE||m.nodeType!==3||m.nodeValue){k.insertBefore(m,l)}else{l.removeChild(m)}}}return k.removeChild(l)})},setStyle:function(l,i,j){var k=this;return k.run(l,function(o){var n,m;n=o.style;i=i.replace(/-(\D)/g,function(q,p){return p.toUpperCase()});if(k.pixelStyles.test(i)&&(e.is(j,"number")||/^[\-0-9\.]+$/.test(j))){j+="px"}switch(i){case"opacity":if(b&&!e.isIE11){n.filter=j===""?"":"alpha(opacity="+(j*100)+")";if(!l.currentStyle||!l.currentStyle.hasLayout){n.display="inline-block"}}n[i]=n["-moz-opacity"]=n["-khtml-opacity"]=j||"";break;case"float":(b&&!e.isIE11)?n.styleFloat=j:n.cssFloat=j;break;default:n[i]=j||""}if(k.settings.update_styles){k.setAttrib(o,"data-mce-style")}})},getStyle:function(l,i,k){l=this.get(l);if(!l){return}if(this.doc.defaultView&&k){i=i.replace(/[A-Z]/g,function(m){return"-"+m});try{return this.doc.defaultView.getComputedStyle(l,null).getPropertyValue(i)}catch(j){return null}}i=i.replace(/-(\D)/g,function(n,m){return m.toUpperCase()});if(i=="float"){i=b?"styleFloat":"cssFloat"}if(l.currentStyle&&k){return l.currentStyle[i]}return l.style?l.style[i]:undefined},setStyles:function(l,m){var j=this,k=j.settings,i;i=k.update_styles;k.update_styles=0;g(m,function(o,p){j.setStyle(l,p,o)});k.update_styles=i;if(k.update_styles){j.setAttrib(l,k.cssText)}},removeAllAttribs:function(i){return this.run(i,function(l){var k,j=l.attributes;for(k=j.length-1;k>=0;k--){l.removeAttributeNode(j.item(k))}})},setAttrib:function(k,l,i){var j=this;if(!k||!l){return}if(j.settings.strict){l=l.toLowerCase()}return this.run(k,function(p){var o=j.settings;var m=p.getAttribute(l);if(i!==null){switch(l){case"style":if(!d(i,"string")){g(i,function(q,r){j.setStyle(p,r,q)});return}if(o.keep_values){if(i&&!j._isRes(i)){p.setAttribute("data-mce-style",i,2)}else{p.removeAttribute("data-mce-style",2)}}p.style.cssText=i;break;case"class":p.className=i||"";break;case"src":case"href":if(o.keep_values){if(o.url_converter){i=o.url_converter.call(o.url_converter_scope||j,i,l,p)}j.setAttrib(p,"data-mce-"+l,i,2)}break;case"shape":p.setAttribute("data-mce-style",i);break}}if(d(i)&&i!==null&&i.length!==0){p.setAttribute(l,""+i,2)}else{p.removeAttribute(l,2)}if(tinyMCE.activeEditor&&m!=i){var n=tinyMCE.activeEditor;n.onSetAttrib.dispatch(n,p,l,i)}})},setAttribs:function(j,k){var i=this;return this.run(j,function(l){g(k,function(m,o){i.setAttrib(l,o,m)})})},getAttrib:function(m,o,k){var i,j=this,l;m=j.get(m);if(!m||m.nodeType!==1){return k===l?false:k}if(!d(k)){k=""}if(/^(src|href|style|coords|shape)$/.test(o)){i=m.getAttribute("data-mce-"+o);if(i){return i}}if(b&&j.props[o]){i=m[j.props[o]];i=i&&i.nodeValue?i.nodeValue:i}if(!i){i=m.getAttribute(o,2)}if(/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(o)){if(m[j.props[o]]===true&&i===""){return o}return i?o:""}if(m.nodeName==="FORM"&&m.getAttributeNode(o)){return m.getAttributeNode(o).nodeValue}if(o==="style"){i=i||m.style.cssText;if(i){i=j.serializeStyle(j.parseStyle(i),m.nodeName);if(j.settings.keep_values&&!j._isRes(i)){m.setAttribute("data-mce-style",i)}}}if(f&&o==="class"&&i){i=i.replace(/(apple|webkit)\-[a-z\-]+/gi,"")}if(b){switch(o){case"rowspan":case"colspan":if(i===1){i=""}break;case"size":if(i==="+0"||i===20||i===0){i=""}break;case"width":case"height":case"vspace":case"checked":case"disabled":case"readonly":if(i===0){i=""}break;case"hspace":if(i===-1){i=""}break;case"maxlength":case"tabindex":if(i===32768||i===2147483647||i==="32768"){i=""}break;case"multiple":case"compact":case"noshade":case"nowrap":if(i===65535){return o}return k;case"shape":i=i.toLowerCase();break;default:if(o.indexOf("on")===0&&i){i=e._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/,"$1",""+i)}}}return(i!==l&&i!==null&&i!=="")?""+i:k},getPos:function(q,l){var j=this,i=0,p=0,m,o=j.doc,k;q=j.get(q);l=l||o.body;if(q){if(q.getBoundingClientRect){q=q.getBoundingClientRect();m=j.boxModel?o.documentElement:o.body;i=q.left+(o.documentElement.scrollLeft||o.body.scrollLeft)-m.clientTop;p=q.top+(o.documentElement.scrollTop||o.body.scrollTop)-m.clientLeft;return{x:i,y:p}}k=q;while(k&&k!=l&&k.nodeType){i+=k.offsetLeft||0;p+=k.offsetTop||0;k=k.offsetParent}k=q.parentNode;while(k&&k!=l&&k.nodeType){i-=k.scrollLeft||0;p-=k.scrollTop||0;k=k.parentNode}}return{x:i,y:p}},parseStyle:function(i){return this.styles.parse(i)},serializeStyle:function(j,i){return this.styles.serialize(j,i)},addStyle:function(j){var k=this.doc,i;styleElm=k.getElementById("mceDefaultStyles");if(!styleElm){styleElm=k.createElement("style"),styleElm.id="mceDefaultStyles";styleElm.type="text/css";i=k.getElementsByTagName("head")[0];if(i.firstChild){i.insertBefore(styleElm,i.firstChild)}else{i.appendChild(styleElm)}}if(styleElm.styleSheet){styleElm.styleSheet.cssText+=j}else{styleElm.appendChild(k.createTextNode(j))}},loadCSS:function(i){var k=this,l=k.doc,j;if(!i){i=""}j=l.getElementsByTagName("head")[0];g(i.split(","),function(m){var n;if(k.files[m]){return}k.files[m]=true;n=k.create("link",{rel:"stylesheet",href:e._addVer(m)});if(b&&!e.isIE11&&l.documentMode&&l.recalc){n.onload=function(){if(l.recalc){l.recalc()}n.onload=null}}j.appendChild(n)})},addClass:function(i,j){return this.run(i,function(k){var l;if(!j){return 0}if(this.hasClass(k,j)){return k.className}l=this.removeClass(k,j);return k.className=(l!=""?(l+" "):"")+j})},removeClass:function(k,l){var i=this,j;return i.run(k,function(n){var m;if(i.hasClass(n,l)){if(!j){j=new RegExp("(^|\\s+)"+l+"(\\s+|$)","g")}m=n.className.replace(j," ");m=e.trim(m!=" "?m:"");n.className=m;if(!m){n.removeAttribute("class");n.removeAttribute("className")}return m}return n.className})},hasClass:function(j,i){j=this.get(j);if(!j||!i){return false}return(" "+j.className+" ").indexOf(" "+i+" ")!==-1},show:function(i){return this.setStyle(i,"display","block")},hide:function(i){return this.setStyle(i,"display","none")},isHidden:function(i){i=this.get(i);return !i||i.style.display=="none"||this.getStyle(i,"display")=="none"},uniqueId:function(i){return(!i?"mce_":i)+(this.counter++)},setHTML:function(k,j){var i=this;return i.run(k,function(m){if(b){while(m.firstChild){m.removeChild(m.firstChild)}try{m.innerHTML="
"+j;m.removeChild(m.firstChild)}catch(l){var n=i.create("div");n.innerHTML="
"+j;g(e.grep(n.childNodes),function(p,o){if(o&&m.canHaveHTML){m.appendChild(p)}})}}else{m.innerHTML=j}return j})},getOuterHTML:function(k){var j,i=this;k=i.get(k);if(!k){return null}if(k.nodeType===1&&i.hasOuterHTML){return k.outerHTML}j=(k.ownerDocument||i.doc).createElement("body");j.appendChild(k.cloneNode(true));return j.innerHTML},setOuterHTML:function(l,j,m){var i=this;function k(p,o,r){var s,q;q=r.createElement("body");q.innerHTML=o;s=q.lastChild;while(s){i.insertAfter(s.cloneNode(true),p);s=s.previousSibling}i.remove(p)}return this.run(l,function(o){o=i.get(o);if(o.nodeType==1){m=m||o.ownerDocument||i.doc;if(b){try{if(b&&o.nodeType==1){o.outerHTML=j}else{k(o,j,m)}}catch(n){k(o,j,m)}}else{k(o,j,m)}}})},decode:h.decode,encode:h.encodeAllRaw,insertAfter:function(i,j){j=this.get(j);return this.run(i,function(l){var k,m;k=j.parentNode;m=j.nextSibling;if(m){k.insertBefore(l,m)}else{k.appendChild(l)}return l})},replace:function(m,l,i){var j=this;if(d(l,"array")){m=m.cloneNode(true)}return j.run(l,function(k){if(i){g(e.grep(k.childNodes),function(n){m.appendChild(n)})}return k.parentNode.replaceChild(m,k)})},rename:function(l,i){var k=this,j;if(l.nodeName!=i.toUpperCase()){j=k.create(i);g(k.getAttribs(l),function(m){k.setAttrib(j,m.nodeName,k.getAttrib(l,m.nodeName))});k.replace(j,l,1)}return j||l},findCommonAncestor:function(k,i){var l=k,j;while(l){j=i;while(j&&l!=j){j=j.parentNode}if(l==j){break}l=l.parentNode}if(!l&&k.ownerDocument){return k.ownerDocument.documentElement}return l},toHex:function(i){var k=/^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(i);function j(l){l=parseInt(l,10).toString(16);return l.length>1?l:"0"+l}if(k){i="#"+j(k[1])+j(k[2])+j(k[3]);return i}return i},getClasses:function(){var n=this,j=[],m,o={},p=n.settings.class_filter,l;if(n.classes){return n.classes}function q(i){g(i.imports,function(s){q(s)});g(i.cssRules||i.rules,function(t){switch(t.type||1){case 1:if(t.selectorText){g(t.selectorText.split(","),function(r){r=r.replace(/^\s*|\s*$|^\s\./g,"");if(/\.mce/.test(r)||!/\.[\w\-]+$/.test(r)){return}l=r;r=e._replace(/.*\.([a-z0-9_\-]+).*/i,"$1",r);if(p&&!(r=p(r,l))){return}if(!o[r]){j.push({"class":r});o[r]=1}})}break;case 3:try{q(t.styleSheet)}catch(s){}break}})}try{g(n.doc.styleSheets,q)}catch(k){}if(j.length>0){n.classes=j}return j},run:function(l,k,j){var i=this,m;if(i.doc&&typeof(l)==="string"){l=i.get(l)}if(!l){return false}j=j||this;if(!l.nodeType&&(l.length||l.length===0)){m=[];g(l,function(o,n){if(o){if(typeof(o)=="string"){o=i.doc.getElementById(o)}m.push(k.call(j,o,n))}});return m}return k.call(j,l)},getAttribs:function(j){var i;j=this.get(j);if(!j){return[]}if(b){i=[];if(j.nodeName=="OBJECT"){return j.attributes}if(j.nodeName==="OPTION"&&this.getAttrib(j,"selected")){i.push({specified:1,nodeName:"selected"})}j.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi,"").replace(/[\w:\-]+/gi,function(k){i.push({specified:1,nodeName:k})});return i}return j.attributes},isEmpty:function(m,k){var r=this,o,n,q,j,l,p=0;m=m.firstChild;if(m){j=new e.dom.TreeWalker(m,m.parentNode);k=k||r.schema?r.schema.getNonEmptyElements():null;do{q=m.nodeType;if(q===1){if(m.getAttribute("data-mce-bogus")){continue}l=m.nodeName.toLowerCase();if(k&&k[l]){if(l==="br"){p++;continue}return false}n=r.getAttribs(m);o=m.attributes.length;while(o--){l=m.attributes[o].nodeName;if(l==="name"||l==="data-mce-bookmark"){return false}}}if(q==8){return false}if((q===3&&!a.test(m.nodeValue))){return false}}while(m=j.next())}return p<=1},destroy:function(j){var i=this;i.win=i.doc=i.root=i.events=i.frag=null;if(!j){e.removeUnload(i.destroy)}},createRng:function(){var i=this.doc;return i.createRange?i.createRange():new e.dom.Range(this)},nodeIndex:function(m,n){var i=0,k,l,j;if(m){for(k=m.nodeType,m=m.previousSibling,l=m;m;m=m.previousSibling){j=m.nodeType;if(n&&j==3){if(j==k||!m.nodeValue.length){continue}}i++;k=j}}return i},split:function(m,l,p){var q=this,i=q.createRng(),n,k,o;function j(v){var t,s=v.childNodes,u=v.nodeType;function x(A){var z=A.previousSibling&&A.previousSibling.nodeName=="SPAN";var y=A.nextSibling&&A.nextSibling.nodeName=="SPAN";return z&&y}if(u==1&&v.getAttribute("data-mce-type")=="bookmark"){return}for(t=s.length-1;t>=0;t--){j(s[t])}if(u!=9){if(u==3&&v.nodeValue.length>0){var r=e.trim(v.nodeValue).length;if(!q.isBlock(v.parentNode)||r>0||r===0&&x(v)){return}}else{if(u==1){s=v.childNodes;if(s.length==1&&s[0]&&s[0].nodeType==1&&s[0].getAttribute("data-mce-type")=="bookmark"){v.parentNode.insertBefore(s[0],v)}if(s.length||/^(br|hr|input|img)$/i.test(v.nodeName)){return}}}q.remove(v)}return v}if(m&&l){i.setStart(m.parentNode,q.nodeIndex(m));i.setEnd(l.parentNode,q.nodeIndex(l));n=i.extractContents();i=q.createRng();i.setStart(l.parentNode,q.nodeIndex(l)+1);i.setEnd(m.parentNode,q.nodeIndex(m)+1);k=i.extractContents();o=m.parentNode;o.insertBefore(j(n),m);if(p){o.replaceChild(p,l)}else{o.insertBefore(l,m)}o.insertBefore(j(k),m);q.remove(m);return p||l}},bind:function(l,i,k,j){return this.events.add(l,i,k,j||this)},unbind:function(k,i,j){return this.events.remove(k,i,j)},fire:function(k,j,i){return this.events.fire(k,j,i)},getContentEditable:function(j){var i;if(j.nodeType!=1){return null}i=j.getAttribute("data-mce-contenteditable");if(i&&i!=="inherit"){return i}return j.contentEditable!=="inherit"?j.contentEditable:null},_findSib:function(l,i,j){var k=this,m=i;if(l){if(d(m,"string")){m=function(n){return k.is(n,i)}}for(l=l[j];l;l=l[j]){if(m(l)){return l}}}return null},_isRes:function(i){return/^(top|left|bottom|right|width|height)/i.test(i)||/;\s*(top|left|bottom|right|width|height)/i.test(i)}});e.DOM=new e.dom.DOMUtils(document,{process_html:0})})(tinymce);(function(a){function b(c){var O=this,e=c.doc,U=0,F=1,j=2,E=true,S=false,W="startOffset",h="startContainer",Q="endContainer",A="endOffset",k=tinymce.extend,n=c.nodeIndex;k(O,{startContainer:e,startOffset:0,endContainer:e,endOffset:0,collapsed:E,commonAncestorContainer:e,START_TO_START:0,START_TO_END:1,END_TO_END:2,END_TO_START:3,setStart:q,setEnd:s,setStartBefore:g,setStartAfter:J,setEndBefore:K,setEndAfter:u,collapse:B,selectNode:y,selectNodeContents:G,compareBoundaryPoints:v,deleteContents:p,extractContents:I,cloneContents:d,insertNode:D,surroundContents:N,cloneRange:L,toStringIE:T});function x(){return e.createDocumentFragment()}function q(X,t){C(E,X,t)}function s(X,t){C(S,X,t)}function g(t){q(t.parentNode,n(t))}function J(t){q(t.parentNode,n(t)+1)}function K(t){s(t.parentNode,n(t))}function u(t){s(t.parentNode,n(t)+1)}function B(t){if(t){O[Q]=O[h];O[A]=O[W]}else{O[h]=O[Q];O[W]=O[A]}O.collapsed=E}function y(t){g(t);u(t)}function G(t){q(t,0);s(t,t.nodeType===1?t.childNodes.length:t.nodeValue.length)}function v(aa,t){var ad=O[h],Y=O[W],ac=O[Q],X=O[A],ab=t.startContainer,af=t.startOffset,Z=t.endContainer,ae=t.endOffset;if(aa===0){return H(ad,Y,ab,af)}if(aa===1){return H(ac,X,ab,af)}if(aa===2){return H(ac,X,Z,ae)}if(aa===3){return H(ad,Y,Z,ae)}}function p(){l(j)}function I(){return l(U)}function d(){return l(F)}function D(aa){var X=this[h],t=this[W],Z,Y;if((X.nodeType===3||X.nodeType===4)&&X.nodeValue){if(!t){X.parentNode.insertBefore(aa,X)}else{if(t>=X.nodeValue.length){c.insertAfter(aa,X)}else{Z=X.splitText(t);X.parentNode.insertBefore(aa,Z)}}}else{if(X.childNodes.length>0){Y=X.childNodes[t]}if(Y){X.insertBefore(aa,Y)}else{X.appendChild(aa)}}}function N(X){var t=O.extractContents();O.insertNode(X);X.appendChild(t);O.selectNode(X)}function L(){return k(new b(c),{startContainer:O[h],startOffset:O[W],endContainer:O[Q],endOffset:O[A],collapsed:O.collapsed,commonAncestorContainer:O.commonAncestorContainer})}function P(t,X){var Y;if(t.nodeType==3){return t}if(X<0){return t}Y=t.firstChild;while(Y&&X>0){--X;Y=Y.nextSibling}if(Y){return Y}return t}function m(){return(O[h]==O[Q]&&O[W]==O[A])}function H(Z,ab,X,aa){var ac,Y,t,ad,af,ae;if(Z==X){if(ab==aa){return 0}if(ab0){O.collapse(X)}}else{O.collapse(X)}O.collapsed=m();O.commonAncestorContainer=c.findCommonAncestor(O[h],O[Q])}function l(ad){var ac,Z=0,af=0,X,ab,Y,aa,t,ae;if(O[h]==O[Q]){return f(ad)}for(ac=O[Q],X=ac.parentNode;X;ac=X,X=X.parentNode){if(X==O[h]){return r(ac,ad)}++Z}for(ac=O[h],X=ac.parentNode;X;ac=X,X=X.parentNode){if(X==O[Q]){return V(ac,ad)}++af}ab=af-Z;Y=O[h];while(ab>0){Y=Y.parentNode;ab--}aa=O[Q];while(ab<0){aa=aa.parentNode;ab++}for(t=Y.parentNode,ae=aa.parentNode;t!=ae;t=t.parentNode,ae=ae.parentNode){Y=t;aa=ae}return o(Y,aa,ad)}function f(ac){var ae,af,t,Y,Z,ad,aa,X,ab;if(ac!=j){ae=x()}if(O[W]==O[A]){return ae}if(O[h].nodeType==3){af=O[h].nodeValue;t=af.substring(O[W],O[A]);if(ac!=F){Y=O[h];X=O[W];ab=O[A]-O[W];if(X===0&&ab>=Y.nodeValue.length-1){Y.parentNode.removeChild(Y)}else{Y.deleteData(X,ab)}O.collapse(E)}if(ac==j){return}if(t.length>0){ae.appendChild(e.createTextNode(t))}return ae}Y=P(O[h],O[W]);Z=O[A]-O[W];while(Y&&Z>0){ad=Y.nextSibling;aa=z(Y,ac);if(ae){ae.appendChild(aa)}--Z;Y=ad}if(ac!=F){O.collapse(E)}return ae}function r(ad,aa){var ac,ab,X,t,Z,Y;if(aa!=j){ac=x()}ab=i(ad,aa);if(ac){ac.appendChild(ab)}X=n(ad);t=X-O[W];if(t<=0){if(aa!=F){O.setEndBefore(ad);O.collapse(S)}return ac}ab=ad.previousSibling;while(t>0){Z=ab.previousSibling;Y=z(ab,aa);if(ac){ac.insertBefore(Y,ac.firstChild)}--t;ab=Z}if(aa!=F){O.setEndBefore(ad);O.collapse(S)}return ac}function V(ab,aa){var ad,X,ac,t,Z,Y;if(aa!=j){ad=x()}ac=R(ab,aa);if(ad){ad.appendChild(ac)}X=n(ab);++X;t=O[A]-X;ac=ab.nextSibling;while(ac&&t>0){Z=ac.nextSibling;Y=z(ac,aa);if(ad){ad.appendChild(Y)}--t;ac=Z}if(aa!=F){O.setStartAfter(ab);O.collapse(E)}return ad}function o(ab,t,ae){var Y,ag,aa,ac,ad,X,af,Z;if(ae!=j){ag=x()}Y=R(ab,ae);if(ag){ag.appendChild(Y)}aa=ab.parentNode;ac=n(ab);ad=n(t);++ac;X=ad-ac;af=ab.nextSibling;while(X>0){Z=af.nextSibling;Y=z(af,ae);if(ag){ag.appendChild(Y)}af=Z;--X}Y=i(t,ae);if(ag){ag.appendChild(Y)}if(ae!=F){O.setStartAfter(ab);O.collapse(E)}return ag}function i(ac,ad){var Y=P(O[Q],O[A]-1),ae,ab,aa,t,X,Z=Y!=O[Q];if(Y==ac){return M(Y,Z,S,ad)}ae=Y.parentNode;ab=M(ae,S,S,ad);while(ae){while(Y){aa=Y.previousSibling;t=M(Y,Z,S,ad);if(ad!=j){ab.insertBefore(t,ab.firstChild)}Z=E;Y=aa}if(ae==ac){return ab}Y=ae.previousSibling;ae=ae.parentNode;X=M(ae,S,S,ad);if(ad!=j){X.appendChild(ab)}ab=X}}function R(ac,ad){var Z=P(O[h],O[W]),aa=Z!=O[h],ae,ab,Y,t,X;if(Z==ac){return M(Z,aa,E,ad)}ae=Z.parentNode;ab=M(ae,S,E,ad);while(ae){while(Z){Y=Z.nextSibling;t=M(Z,aa,E,ad);if(ad!=j){ab.appendChild(t)}aa=E;Z=Y}if(ae==ac){return ab}Z=ae.nextSibling;ae=ae.parentNode;X=M(ae,S,E,ad);if(ad!=j){X.appendChild(ab)}ab=X}}function M(t,aa,ad,ae){var Z,Y,ab,X,ac;if(aa){return z(t,ae)}if(t.nodeType==3){Z=t.nodeValue;if(ad){X=O[W];Y=Z.substring(X);ab=Z.substring(0,X)}else{X=O[A];Y=Z.substring(0,X);ab=Z.substring(X)}if(ae!=F){t.nodeValue=ab}if(ae==j){return}ac=c.clone(t,S);ac.nodeValue=Y;return ac}if(ae==j){return}return c.clone(t,S)}function z(X,t){if(t!=j){return t==F?c.clone(X,E):X}X.parentNode.removeChild(X)}function T(){return c.create("body",null,d()).outerText}return O}a.Range=b;b.prototype.toString=function(){return this.toStringIE()}})(tinymce.dom);(function(){function a(d){var b=this,h=d.dom,c=true,f=false;function e(i,j){var k,t=0,q,n,m,l,o,r,p=-1,s;k=i.duplicate();k.collapse(j);s=k.parentElement();if(s.ownerDocument!==d.dom.doc){return}while(s.contentEditable==="false"){s=s.parentNode}if(!s.hasChildNodes()){return{node:s,inside:1}}m=s.children;q=m.length-1;while(t<=q){r=Math.floor((t+q)/2);l=m[r];k.moveToElementText(l);p=k.compareEndPoints(j?"StartToStart":"EndToEnd",i);if(p>0){q=r-1}else{if(p<0){t=r+1}else{return{node:l}}}}if(p<0){if(!l){k.moveToElementText(s);k.collapse(true);l=s;n=true}else{k.collapse(false)}o=0;while(k.compareEndPoints(j?"StartToStart":"StartToEnd",i)!==0){if(k.move("character",1)===0||s!=k.parentElement()){break}o++}}else{k.collapse(true);o=0;while(k.compareEndPoints(j?"StartToStart":"StartToEnd",i)!==0){if(k.move("character",-1)===0||s!=k.parentElement()){break}o++}}return{node:l,position:p,offset:o,inside:n}}function g(){var i=d.getRng(),r=h.createRng(),l,k,p,q,m,j;l=i.item?i.item(0):i.parentElement();if(l.ownerDocument!=h.doc){return r}k=d.isCollapsed();if(i.item){r.setStart(l.parentNode,h.nodeIndex(l));r.setEnd(r.startContainer,r.startOffset+1);return r}function o(A){var u=e(i,A),s,y,z=0,x,v,t;s=u.node;y=u.offset;if(u.inside&&!s.hasChildNodes()){r[A?"setStart":"setEnd"](s,0);return}if(y===v){r[A?"setStartBefore":"setEndAfter"](s);return}if(u.position<0){x=u.inside?s.firstChild:s.nextSibling;if(!x){r[A?"setStartAfter":"setEndAfter"](s);return}if(!y){if(x.nodeType==3){r[A?"setStart":"setEnd"](x,0)}else{r[A?"setStartBefore":"setEndBefore"](x)}return}while(x){t=x.nodeValue;z+=t.length;if(z>=y){s=x;z-=y;z=t.length-z;break}x=x.nextSibling}}else{x=s.previousSibling;if(!x){return r[A?"setStartBefore":"setEndBefore"](s)}if(!y){if(s.nodeType==3){r[A?"setStart":"setEnd"](x,s.nodeValue.length)}else{r[A?"setStartAfter":"setEndAfter"](x)}return}while(x){z+=x.nodeValue.length;if(z>=y){s=x;z-=y;break}x=x.previousSibling}}r[A?"setStart":"setEnd"](s,z)}try{o(true);if(!k){o()}}catch(n){if(n.number==-2147024809){m=b.getBookmark(2);p=i.duplicate();p.collapse(true);l=p.parentElement();if(!k){p=i.duplicate();p.collapse(false);q=p.parentElement();q.innerHTML=q.innerHTML}l.innerHTML=l.innerHTML;b.moveToBookmark(m);i=d.getRng();o(true);if(!k){o()}}else{throw n}}return r}this.getBookmark=function(m){var j=d.getRng(),o,i,l={};function n(u){var t,p,s,r,q=[];t=u.parentNode;p=h.getRoot().parentNode;while(t!=p&&t.nodeType!==9){s=t.children;r=s.length;while(r--){if(u===s[r]){q.push(r);break}}u=t;t=t.parentNode}return q}function k(q){var p;p=e(j,q);if(p){return{position:p.position,offset:p.offset,indexes:n(p.node),inside:p.inside}}}if(m===2){if(!j.item){l.start=k(true);if(!d.isCollapsed()){l.end=k()}}else{l.start={ctrl:true,indexes:n(j.item(0))}}}return l};this.moveToBookmark=function(k){var j,i=h.doc.body;function m(o){var r,q,n,p;r=h.getRoot();for(q=o.length-1;q>=0;q--){p=r.children;n=o[q];if(n<=p.length-1){r=p[n]}}return r}function l(r){var n=k[r?"start":"end"],q,p,o;if(n){q=n.position>0;p=i.createTextRange();p.moveToElementText(m(n.indexes));offset=n.offset;if(offset!==o){p.collapse(n.inside||q);p.moveStart("character",q?-offset:offset)}else{p.collapse(r)}j.setEndPoint(r?"StartToStart":"EndToStart",p);if(r){j.collapse(true)}}}if(k.start){if(k.start.ctrl){j=i.createControlRange();j.addElement(m(k.start.indexes));j.select()}else{j=i.createTextRange();l(true);l();j.select()}}};this.addRange=function(i){var n,l,k,p,v,q,t,s=d.dom.doc,m=s.body,r,u;function j(C){var y,B,x,A,z;x=h.create("a");y=C?k:v;B=C?p:q;A=n.duplicate();if(y==s||y==s.documentElement){y=m;B=0}if(y.nodeType==3){y.parentNode.insertBefore(x,y);A.moveToElementText(x);A.moveStart("character",B);h.remove(x);n.setEndPoint(C?"StartToStart":"EndToEnd",A)}else{z=y.childNodes;if(z.length){if(B>=z.length){h.insertAfter(x,z[z.length-1])}else{y.insertBefore(x,z[B])}A.moveToElementText(x)}else{if(y.canHaveHTML){y.innerHTML="\uFEFF";x=y.firstChild;A.moveToElementText(x);A.collapse(f)}}n.setEndPoint(C?"StartToStart":"EndToEnd",A);h.remove(x)}}k=i.startContainer;p=i.startOffset;v=i.endContainer;q=i.endOffset;n=m.createTextRange();if(k==v&&k.nodeType==1){if(p==q&&!k.hasChildNodes()){if(k.canHaveHTML){t=k.previousSibling;if(t&&!t.hasChildNodes()&&h.isBlock(t)){t.innerHTML="\uFEFF"}else{t=null}k.innerHTML="\uFEFF\uFEFF";n.moveToElementText(k.lastChild);n.select();h.doc.selection.clear();k.innerHTML="";if(t){t.innerHTML=""}return}else{p=h.nodeIndex(k);k=k.parentNode}}if(p==q-1){try{u=k.childNodes[p];l=m.createControlRange();l.addElement(u);l.select();r=d.getRng();if(r.item&&u===r.item(0)){return}}catch(o){}}}j(true);j();n.select()};this.getRangeAt=g}tinymce.dom.TridentSelection=a})();(function(){var n=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,i="sizcache",o=0,r=Object.prototype.toString,h=false,g=true,q=/\\/g,u=/\r\n/g,x=/\W/;[0,0].sort(function(){g=false;return 0});var d=function(C,e,F,G){F=F||[];e=e||document;var I=e;if(e.nodeType!==1&&e.nodeType!==9){return[]}if(!C||typeof C!=="string"){return F}var z,K,N,y,J,M,L,E,B=true,A=d.isXML(e),D=[],H=C;do{n.exec("");z=n.exec(H);if(z){H=z[3];D.push(z[1]);if(z[2]){y=z[3];break}}}while(z);if(D.length>1&&j.exec(C)){if(D.length===2&&k.relative[D[0]]){K=s(D[0]+D[1],e,G)}else{K=k.relative[D[0]]?[e]:d(D.shift(),e);while(D.length){C=D.shift();if(k.relative[C]){C+=D.shift()}K=s(C,K,G)}}}else{if(!G&&D.length>1&&e.nodeType===9&&!A&&k.match.ID.test(D[0])&&!k.match.ID.test(D[D.length-1])){J=d.find(D.shift(),e,A);e=J.expr?d.filter(J.expr,J.set)[0]:J.set[0]}if(e){J=G?{expr:D.pop(),set:l(G)}:d.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&e.parentNode?e.parentNode:e,A);K=J.expr?d.filter(J.expr,J.set):J.set;if(D.length>0){N=l(K)}else{B=false}while(D.length){M=D.pop();L=M;if(!k.relative[M]){M=""}else{L=D.pop()}if(L==null){L=e}k.relative[M](N,L,A)}}else{N=D=[]}}if(!N){N=K}if(!N){d.error(M||C)}if(r.call(N)==="[object Array]"){if(!B){F.push.apply(F,N)}else{if(e&&e.nodeType===1){for(E=0;N[E]!=null;E++){if(N[E]&&(N[E]===true||N[E].nodeType===1&&d.contains(e,N[E]))){F.push(K[E])}}}else{for(E=0;N[E]!=null;E++){if(N[E]&&N[E].nodeType===1){F.push(K[E])}}}}}else{l(N,F)}if(y){d(y,I,F,G);d.uniqueSort(F)}return F};d.uniqueSort=function(y){if(p){h=g;y.sort(p);if(h){for(var e=1;e0};d.find=function(E,e,F){var D,z,B,A,C,y;if(!E){return[]}for(z=0,B=k.order.length;z":function(D,y){var C,B=typeof y==="string",z=0,e=D.length;if(B&&!x.test(y)){y=y.toLowerCase();for(;z=0)){if(!z){e.push(C)}}else{if(z){y[B]=false}}}}return false},ID:function(e){return e[1].replace(q,"")},TAG:function(y,e){return y[1].replace(q,"").toLowerCase()},CHILD:function(e){if(e[1]==="nth"){if(!e[2]){d.error(e[0])}e[2]=e[2].replace(/^\+|\s*/g,"");var y=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(e[2]==="even"&&"2n"||e[2]==="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=(y[1]+(y[2]||1))-0;e[3]=y[3]-0}else{if(e[2]){d.error(e[0])}}e[0]=o++;return e},ATTR:function(B,y,z,e,C,D){var A=B[1]=B[1].replace(q,"");if(!D&&k.attrMap[A]){B[1]=k.attrMap[A]}B[4]=(B[4]||B[5]||"").replace(q,"");if(B[2]==="~="){B[4]=" "+B[4]+" "}return B},PSEUDO:function(B,y,z,e,C){if(B[1]==="not"){if((n.exec(B[3])||"").length>1||/^\w/.test(B[3])){B[3]=d(B[3],null,null,y)}else{var A=d.filter(B[3],y,z,true^C);if(!z){e.push.apply(e,A)}return false}}else{if(k.match.POS.test(B[0])||k.match.CHILD.test(B[0])){return true}}return B},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return !!e.firstChild},empty:function(e){return !e.firstChild},has:function(z,y,e){return !!d(e[3],z).length},header:function(e){return(/h\d/i).test(e.nodeName)},text:function(z){var e=z.getAttribute("type"),y=z.type;return z.nodeName.toLowerCase()==="input"&&"text"===y&&(e===y||e===null)},radio:function(e){return e.nodeName.toLowerCase()==="input"&&"radio"===e.type},checkbox:function(e){return e.nodeName.toLowerCase()==="input"&&"checkbox"===e.type},file:function(e){return e.nodeName.toLowerCase()==="input"&&"file"===e.type},password:function(e){return e.nodeName.toLowerCase()==="input"&&"password"===e.type},submit:function(y){var e=y.nodeName.toLowerCase();return(e==="input"||e==="button")&&"submit"===y.type},image:function(e){return e.nodeName.toLowerCase()==="input"&&"image"===e.type},reset:function(y){var e=y.nodeName.toLowerCase();return(e==="input"||e==="button")&&"reset"===y.type},button:function(y){var e=y.nodeName.toLowerCase();return e==="input"&&"button"===y.type||e==="button"},input:function(e){return(/input|select|textarea|button/i).test(e.nodeName)},focus:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(y,e){return e===0},last:function(z,y,e,A){return y===A.length-1},even:function(y,e){return e%2===0},odd:function(y,e){return e%2===1},lt:function(z,y,e){return ye[3]-0},nth:function(z,y,e){return e[3]-0===y},eq:function(z,y,e){return e[3]-0===y}},filter:{PSEUDO:function(z,E,D,F){var e=E[1],y=k.filters[e];if(y){return y(z,D,E,F)}else{if(e==="contains"){return(z.textContent||z.innerText||b([z])||"").indexOf(E[3])>=0}else{if(e==="not"){var A=E[3];for(var C=0,B=A.length;C=0)}}},ID:function(y,e){return y.nodeType===1&&y.getAttribute("id")===e},TAG:function(y,e){return(e==="*"&&y.nodeType===1)||!!y.nodeName&&y.nodeName.toLowerCase()===e},CLASS:function(y,e){return(" "+(y.className||y.getAttribute("class"))+" ").indexOf(e)>-1},ATTR:function(C,A){var z=A[1],e=d.attr?d.attr(C,z):k.attrHandle[z]?k.attrHandle[z](C):C[z]!=null?C[z]:C.getAttribute(z),D=e+"",B=A[2],y=A[4];return e==null?B==="!=":!B&&d.attr?e!=null:B==="="?D===y:B==="*="?D.indexOf(y)>=0:B==="~="?(" "+D+" ").indexOf(y)>=0:!y?D&&e!==false:B==="!="?D!==y:B==="^="?D.indexOf(y)===0:B==="$="?D.substr(D.length-y.length)===y:B==="|="?D===y||D.substr(0,y.length+1)===y+"-":false},POS:function(B,y,z,C){var e=y[2],A=k.setFilters[e];if(A){return A(B,z,y,C)}}}};var j=k.match.POS,c=function(y,e){return"\\"+(e-0+1)};for(var f in k.match){k.match[f]=new RegExp(k.match[f].source+(/(?![^\[]*\])(?![^\(]*\))/.source));k.leftMatch[f]=new RegExp(/(^(?:.|\r|\n)*?)/.source+k.match[f].source.replace(/\\(\d+)/g,c))}k.match.globalPOS=j;var l=function(y,e){y=Array.prototype.slice.call(y,0);if(e){e.push.apply(e,y);return e}return y};try{Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType}catch(v){l=function(B,A){var z=0,y=A||[];if(r.call(B)==="[object Array]"){Array.prototype.push.apply(y,B)}else{if(typeof B.length==="number"){for(var e=B.length;z";e.insertBefore(y,e.firstChild);if(document.getElementById(z)){k.find.ID=function(B,C,D){if(typeof C.getElementById!=="undefined"&&!D){var A=C.getElementById(B[1]);return A?A.id===B[1]||typeof A.getAttributeNode!=="undefined"&&A.getAttributeNode("id").nodeValue===B[1]?[A]:undefined:[]}};k.filter.ID=function(C,A){var B=typeof C.getAttributeNode!=="undefined"&&C.getAttributeNode("id");return C.nodeType===1&&B&&B.nodeValue===A}}e.removeChild(y);e=y=null})();(function(){var e=document.createElement("div");e.appendChild(document.createComment(""));if(e.getElementsByTagName("*").length>0){k.find.TAG=function(y,C){var B=C.getElementsByTagName(y[1]);if(y[1]==="*"){var A=[];for(var z=0;B[z];z++){if(B[z].nodeType===1){A.push(B[z])}}B=A}return B}}e.innerHTML="";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){k.attrHandle.href=function(y){return y.getAttribute("href",2)}}e=null})();if(document.querySelectorAll){(function(){var e=d,A=document.createElement("div"),z="__sizzle__";A.innerHTML="

";if(A.querySelectorAll&&A.querySelectorAll(".TEST").length===0){return}d=function(L,C,G,K){C=C||document;if(!K&&!d.isXML(C)){var J=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(L);if(J&&(C.nodeType===1||C.nodeType===9)){if(J[1]){return l(C.getElementsByTagName(L),G)}else{if(J[2]&&k.find.CLASS&&C.getElementsByClassName){return l(C.getElementsByClassName(J[2]),G)}}}if(C.nodeType===9){if(L==="body"&&C.body){return l([C.body],G)}else{if(J&&J[3]){var F=C.getElementById(J[3]);if(F&&F.parentNode){if(F.id===J[3]){return l([F],G)}}else{return l([],G)}}}try{return l(C.querySelectorAll(L),G)}catch(H){}}else{if(C.nodeType===1&&C.nodeName.toLowerCase()!=="object"){var D=C,E=C.getAttribute("id"),B=E||z,N=C.parentNode,M=/^\s*[+~]/.test(L);if(!E){C.setAttribute("id",B)}else{B=B.replace(/'/g,"\\$&")}if(M&&N){C=C.parentNode}try{if(!M||N){return l(C.querySelectorAll("[id='"+B+"'] "+L),G)}}catch(I){}finally{if(!E){D.removeAttribute("id")}}}}}return e(L,C,G,K)};for(var y in e){d[y]=e[y]}A=null})()}(function(){var e=document.documentElement,z=e.matchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.msMatchesSelector;if(z){var B=!z.call(document.createElement("div"),"div"),y=false;try{z.call(document.documentElement,"[test!='']:sizzle")}catch(A){y=true}d.matchesSelector=function(D,F){F=F.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!d.isXML(D)){try{if(y||!k.match.PSEUDO.test(F)&&!/!=/.test(F)){var C=z.call(D,F);if(C||!B||D.document&&D.document.nodeType!==11){return C}}}catch(E){}}return d(F,null,null,[D]).length>0}}})();(function(){var e=document.createElement("div");e.innerHTML="
";if(!e.getElementsByClassName||e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}k.order.splice(1,0,"CLASS");k.find.CLASS=function(y,z,A){if(typeof z.getElementsByClassName!=="undefined"&&!A){return z.getElementsByClassName(y[1])}};e=null})();function a(y,D,C,G,E,F){for(var A=0,z=G.length;A0){B=e;break}}}e=e[y]}G[A]=B}}}if(document.documentElement.contains){d.contains=function(y,e){return y!==e&&(y.contains?y.contains(e):true)}}else{if(document.documentElement.compareDocumentPosition){d.contains=function(y,e){return !!(y.compareDocumentPosition(e)&16)}}else{d.contains=function(){return false}}}d.isXML=function(e){var y=(e?e.ownerDocument||e:0).documentElement;return y?y.nodeName!=="HTML":false};var s=function(z,e,D){var C,E=[],B="",F=e.nodeType?[e]:e;while((C=k.match.PSEUDO.exec(z))){B+=C[0];z=z.replace(k.match.PSEUDO,"")}z=k.relative[z]?z+"*":z;for(var A=0,y=F.length;A"+(i.item?i.item(0).outerHTML:i.htmlText);m.removeChild(m.firstChild)}else{m.innerHTML=i.toString()}}if(/^\s/.test(m.innerHTML)){j=" "}if(/\s+$/.test(m.innerHTML)){l=" "}h.getInner=true;h.content=g.isCollapsed()?"":j+g.serializer.serialize(m,h)+l;g.onGetContent.dispatch(g,h);return h.content},setContent:function(h,j){var o=this,g=o.getRng(),k,l=o.win.document,n,m;j=j||{format:"html"};j.set=true;h=j.content=h;if(!j.no_events){o.onBeforeSetContent.dispatch(o,j)}h=j.content;if(g.insertNode){h+='_';if(g.startContainer==l&&g.endContainer==l){l.body.innerHTML=h}else{g.deleteContents();if(l.body.childNodes.length===0){l.body.innerHTML=h}else{if(g.createContextualFragment){g.insertNode(g.createContextualFragment(h))}else{n=l.createDocumentFragment();m=l.createElement("div");n.appendChild(m);m.outerHTML=h;g.insertNode(n)}}}k=o.dom.get("__caret");g=l.createRange();g.setStartBefore(k);g.setEndBefore(k);o.setRng(g);o.dom.remove("__caret");try{o.setRng(g)}catch(i){}}else{if(g.item){l.execCommand("Delete",false,null);g=o.getRng()}if(/^\s+/.test(h)){g.pasteHTML('_'+h);o.dom.remove("__mce_tmp")}else{g.pasteHTML(h)}}if(!j.no_events){o.onSetContent.dispatch(o,j)}},getStart:function(){var i=this,h=i.getRng(),j,g,l,k;if(h.duplicate||h.item){if(h.item){return h.item(0)}l=h.duplicate();l.collapse(1);j=l.parentElement();if(j.ownerDocument!==i.dom.doc){j=i.dom.getRoot()}g=k=h.parentElement();while(k=k.parentNode){if(k==j){j=g;break}}return j}else{j=h.startContainer;if(j.nodeType==1&&j.hasChildNodes()){j=j.childNodes[Math.min(j.childNodes.length-1,h.startOffset)]}if(j&&j.nodeType==3){return j.parentNode}return j}},getEnd:function(){var h=this,g=h.getRng(),j,i;if(g.duplicate||g.item){if(g.item){return g.item(0)}g=g.duplicate();g.collapse(0);j=g.parentElement();if(j.ownerDocument!==h.dom.doc){j=h.dom.getRoot()}if(j&&j.nodeName=="BODY"){return j.lastChild||j}return j}else{j=g.endContainer;i=g.endOffset;if(j.nodeType==1&&j.hasChildNodes()){j=j.childNodes[i>0?i-1:i]}if(j&&j.nodeType==3){return j.parentNode}return j}},getBookmark:function(s,v){var y=this,n=y.dom,h,k,j,o,i,p,q,m="\uFEFF",x;function g(z,A){var t=0;e(n.select(z),function(C,B){if(C==A){t=B}});return t}function u(t){function z(E){var A,D,C,B=E?"start":"end";A=t[B+"Container"];D=t[B+"Offset"];if(A.nodeType==1&&A.nodeName=="TR"){C=A.childNodes;A=C[Math.min(E?D:D-1,C.length-1)];if(A){D=E?0:A.childNodes.length;t["set"+(E?"Start":"End")](A,D)}}}z(true);z();return t}function l(){var z=y.getRng(true),t=n.getRoot(),A={};function B(E,J){var D=E[J?"startContainer":"endContainer"],I=E[J?"startOffset":"endOffset"],C=[],F,H,G=0;if(D.nodeType==3){if(v){for(F=D.previousSibling;F&&F.nodeType==3;F=F.previousSibling){I+=F.nodeValue.length}}C.push(I)}else{H=D.childNodes;if(I>=H.length&&H.length){G=1;I=Math.max(0,H.length-1)}C.push(y.dom.nodeIndex(H[I],v)+G)}for(;D&&D!=t;D=D.parentNode){C.push(y.dom.nodeIndex(D,v))}return C}A.start=B(z,true);if(!y.isCollapsed()){A.end=B(z)}return A}if(s==2){if(y.tridentSel){return y.tridentSel.getBookmark(s)}return l()}if(s){h=y.getRng();if(h.setStart){h={startContainer:h.startContainer,startOffset:h.startOffset,endContainer:h.endContainer,endOffset:h.endOffset}}return{rng:h}}h=y.getRng();j=n.uniqueId();o=tinyMCE.activeEditor.selection.isCollapsed();x="overflow:hidden;line-height:0px";if(h.duplicate||h.item){if(!h.item){k=h.duplicate();try{h.collapse();h.pasteHTML(''+m+"");if(!o){k.collapse(false);h.moveToElementText(k.parentElement());if(h.compareEndPoints("StartToEnd",k)===0){k.move("character",-1)}k.pasteHTML(''+m+"")}}catch(r){return null}}else{p=h.item(0);i=p.nodeName;return{name:i,index:g(i,p)}}}else{p=y.getNode();i=p.nodeName;if(i=="IMG"){return{name:i,index:g(i,p)}}k=u(h.cloneRange());if(!o){k.collapse(false);k.insertNode(n.create("span",{"data-mce-type":"bookmark",id:j+"_end",style:x},m))}h=u(h);h.collapse(true);h.insertNode(n.create("span",{"data-mce-type":"bookmark",id:j+"_start",style:x},m))}y.moveToBookmark({id:j,keep:1});return{id:j}},moveToBookmark:function(q){var v=this,n=v.dom,l,j,g,i,u,k,x,r,s;function h(C){var t=q[C?"start":"end"],z,A,B,y;if(t){B=t[0];for(A=u,z=t.length-1;z>=1;z--){y=A.childNodes;if(t[z]>y.length-1){return}A=y[t[z]]}if(A.nodeType===3){B=Math.min(t[0],A.nodeValue.length)}if(A.nodeType===1){B=Math.min(t[0],A.childNodes.length)}if(C){g.setStart(A,B)}else{g.setEnd(A,B)}}return true}function m(D){var y=n.get(q.id+"_"+D),C,t,A,B,z=q.keep;if(y){C=y.parentNode;if(D=="start"){if(!z){t=n.nodeIndex(y)}else{C=y.firstChild;t=1}k=x=C;r=s=t}else{if(!z){t=n.nodeIndex(y)}else{C=y.firstChild;t=1}x=C;s=t}if(!z){B=y.previousSibling;A=y.nextSibling;e(d.grep(y.childNodes),function(E){if(E.nodeType==3){E.nodeValue=E.nodeValue.replace(/\uFEFF/g,"")}});while(y=n.get(q.id+"_"+D)){n.remove(y,1)}if(B&&A&&B.nodeType==A.nodeType&&B.nodeType==3&&!d.isOpera){t=B.nodeValue.length;B.appendData(A.nodeValue);n.remove(A);if(D=="start"){k=x=B;r=s=t}else{x=B;s=t}}}}}function o(t){if(n.isBlock(t)&&!t.innerHTML&&!b){t.innerHTML='
'}return t}if(q){if(q.start){g=n.createRng();u=n.getRoot();if(v.tridentSel){return v.tridentSel.moveToBookmark(q)}if(h(true)&&h()){v.setRng(g)}}else{if(q.id){m("start");m("end");if(k){g=n.createRng();g.setStart(o(k),r);g.setEnd(o(x),s);v.setRng(g)}}else{if(q.name){v.select(n.select(q.name)[q.index])}else{if(q.rng){g=q.rng;if(g.startContainer){i=v.dom.createRng();try{i.setStart(g.startContainer,g.startOffset);i.setEnd(g.endContainer,g.endOffset)}catch(p){}g=i}v.setRng(g)}}}}}},select:function(l,k){var j=this,m=j.dom,h=m.createRng(),g;function i(n,p){var o=new a(n,n);do{if(n.nodeType==3&&d.trim(n.nodeValue).length!==0){if(p){h.setStart(n,0)}else{h.setEnd(n,n.nodeValue.length)}return}if(n.nodeName=="BR"){if(p){h.setStartBefore(n)}else{h.setEndBefore(n)}return}}while(n=(p?o.next():o.prev()))}if(l){g=m.nodeIndex(l);h.setStart(l.parentNode,g);h.setEnd(l.parentNode,g+1);if(k){i(l,1);i(l)}j.setRng(h)}return l},isCollapsed:function(){var g=this,i=g.getRng(),h=g.getSel();if(!i||i.item){return false}if(i.compareEndPoints){return i.compareEndPoints("StartToEnd",i)===0}return !h||i.collapsed},collapse:function(g){var i=this,h=i.getRng(),j;if(h.item){j=h.item(0);h=i.win.document.body.createTextRange();h.moveToElementText(j)}h.collapse(!!g);i.setRng(h)},getSel:function(){var h=this,g=this.win;return g.getSelection?g.getSelection():g.document.selection},getRng:function(m){var h=this,j,g,l,k=h.win.document;if(h.fakeRng){return h.fakeRng}if(m&&h.tridentSel){return h.tridentSel.getRangeAt(0)}try{if(j=h.getSel()){g=j.rangeCount>0?j.getRangeAt(0):(j.createRange?j.createRange():k.createRange())}}catch(i){}if(d.isIE&&!d.isIE11&&g&&g.setStart&&k.selection.createRange().item){l=k.selection.createRange().item(0);g=k.createRange();g.setStartBefore(l);g.setEndAfter(l)}if(!g){g=k.createRange?k.createRange():k.body.createTextRange()}if(g.setStart&&g.startContainer.nodeType===9&&g.collapsed){l=h.dom.getRoot();g.setStart(l,0);g.setEnd(l,0)}if(h.selectedRange&&h.explicitRange){if(g.compareBoundaryPoints(g.START_TO_START,h.selectedRange)===0&&g.compareBoundaryPoints(g.END_TO_END,h.selectedRange)===0){g=h.explicitRange}else{h.selectedRange=null;h.explicitRange=null}}return g},setRng:function(k,g){var j,i=this;if(!i.tridentSel){j=i.getSel();if(j){i.explicitRange=k;try{j.removeAllRanges()}catch(h){}j.addRange(k);if(g===false&&j.extend){j.collapse(k.endContainer,k.endOffset);j.extend(k.startContainer,k.startOffset)}i.selectedRange=j.rangeCount>0?j.getRangeAt(0):null}}else{if(k.cloneRange){try{i.tridentSel.addRange(k);return}catch(h){}}try{k.select()}catch(h){}}},setNode:function(h){var g=this;g.setContent(g.dom.getOuterHTML(h));return h},getNode:function(){var i=this,h=i.getRng(),j=i.getSel(),m,l=h.startContainer,g=h.endContainer;function k(q,o){var p=q;while(q&&q.nodeType===3&&q.length===0){q=o?q.nextSibling:q.previousSibling}return q||p}if(!h){return i.dom.getRoot()}if(h.setStart){m=h.commonAncestorContainer;if(!h.collapsed){if(h.startContainer==h.endContainer){if(h.endOffset-h.startOffset<2){if(h.startContainer.hasChildNodes()){m=h.startContainer.childNodes[h.startOffset]}}}if(l.nodeType===3&&g.nodeType===3){if(l.length===h.startOffset){l=k(l.nextSibling,true)}else{l=l.parentNode}if(h.endOffset===0){g=k(g.previousSibling,false)}else{g=g.parentNode}if(l&&l===g){return l}}}if(m&&m.nodeType==3){return m.parentNode}return m}return h.item?h.item(0):h.parentElement()},getSelectedBlocks:function(p,h){var o=this,k=o.dom,m,l,i,j=[];m=k.getParent(p||o.getStart(),k.isBlock);l=k.getParent(h||o.getEnd(),k.isBlock);if(m){j.push(m)}if(m&&l&&m!=l){i=m;var g=new a(m,k.getRoot());while((i=g.next())&&i!=l){if(k.isBlock(i)){j.push(i)}}}if(l&&m!=l){j.push(l)}return j},isForward:function(){var i=this.dom,g=this.getSel(),j,h;if(!g||g.anchorNode==null||g.focusNode==null){return true}j=i.createRng();j.setStart(g.anchorNode,g.anchorOffset);j.collapse(true);h=i.createRng();h.setStart(g.focusNode,g.focusOffset);h.collapse(true);return j.compareBoundaryPoints(j.START_TO_START,h)<=0},normalize:function(){var h=this,g,m,l,j,i;function k(p){var o,r,n,s=h.dom,u=s.getRoot(),q,t,v;function y(z,A){var B=new a(z,s.getParent(z.parentNode,s.isBlock)||u);while(z=B[A?"prev":"next"]()){if(z.nodeName==="BR"){return true}}}function x(B,z){var C,A;z=z||o;C=new a(z,s.getParent(z.parentNode,s.isBlock)||u);while(q=C[B?"prev":"next"]()){if(q.nodeType===3&&q.nodeValue.length>0){o=q;r=B?q.nodeValue.length:0;m=true;return}if(s.isBlock(q)||t[q.nodeName.toLowerCase()]){return}A=q}if(l&&A){o=A;m=true;r=0}}o=g[(p?"start":"end")+"Container"];r=g[(p?"start":"end")+"Offset"];t=s.schema.getNonEmptyElements();if(o.nodeType===9){o=s.getRoot();r=0}if(o===u){if(p){q=o.childNodes[r>0?r-1:0];if(q){v=q.nodeName.toLowerCase();if(t[q.nodeName]||q.nodeName=="TABLE"){return}}}if(o.hasChildNodes()){o=o.childNodes[Math.min(!p&&r>0?r-1:r,o.childNodes.length-1)];r=0;if(o.hasChildNodes()&&!/TABLE/.test(o.nodeName)){q=o;n=new a(o,u);do{if(q.nodeType===3&&q.nodeValue.length>0){r=p?0:q.nodeValue.length;o=q;m=true;break}if(t[q.nodeName.toLowerCase()]){r=s.nodeIndex(q);o=q.parentNode;if(q.nodeName=="IMG"&&!p){r++}m=true;break}}while(q=(p?n.next():n.prev()))}}}if(l){if(o.nodeType===3&&r===0){x(true)}if(o.nodeType===1){q=o.childNodes[r];if(q&&q.nodeName==="BR"&&!y(q)&&!y(q,true)){x(true,o.childNodes[r])}}}if(p&&!l&&o.nodeType===3&&r===o.nodeValue.length){x(false)}if(m){g["set"+(p?"Start":"End")](o,r)}}if(d.isIE){return}g=h.getRng();l=g.collapsed;k(true);if(!l){k()}if(m){if(l){g.collapse(true)}h.setRng(g,h.isForward())}},selectorChanged:function(g,j){var h=this,i;if(!h.selectorChangedData){h.selectorChangedData={};i={};h.editor.onNodeChange.addToTop(function(l,k,o){var p=h.dom,m=p.getParents(o,null,p.getRoot()),n={};e(h.selectorChangedData,function(r,q){e(m,function(s){if(p.is(s,q)){if(!i[q]){e(r,function(t){t(true,{node:s,selector:q,parents:m})});i[q]=r}n[q]=r;return false}})});e(i,function(r,q){if(!n[q]){delete i[q];e(r,function(s){s(false,{node:o,selector:q,parents:m})})}})})}if(!h.selectorChangedData[g]){h.selectorChangedData[g]=[]}h.selectorChangedData[g].push(j);return h},scrollIntoView:function(k){var j,h,g=this,i=g.dom;h=i.getViewPort(g.editor.getWin());j=i.getPos(k).y;if(jh.y+h.h){g.editor.getWin().scrollTo(0,j0){p.setEndPoint("StartToStart",o)}else{p.setEndPoint("EndToEnd",o)}p.select()}}else{l()}}function l(){var p=n.selection.createRange();if(o&&!p.item&&p.compareEndPoints("StartToEnd",p)===0){o.select()}h.unbind(n,"mouseup",l);h.unbind(n,"mousemove",m);o=k=0}n.documentElement.unselectable=true;h.bind(n,["mousedown","contextmenu"],function(p){if(p.target.nodeName==="HTML"){if(k){l()}g=n.documentElement;if(g.scrollHeight>g.clientHeight){return}k=1;o=j(p.x,p.y);if(o){h.bind(n,"mouseup",l);h.bind(n,"mousemove",m);h.win.focus();o.select()}}})}})})(tinymce);(function(a){a.dom.Serializer=function(e,i,f){var h,b,d=a.isIE,g=a.each,c;if(!e.apply_source_formatting){e.indent=false}i=i||a.DOM;f=f||new a.html.Schema(e);e.entity_encoding=e.entity_encoding||"named";e.remove_trailing_brs="remove_trailing_brs" in e?e.remove_trailing_brs:true;h=new a.util.Dispatcher(self);b=new a.util.Dispatcher(self);c=new a.html.DomParser(e,f);c.addAttributeFilter("src,href,style",function(k,j){var o=k.length,l,q,n="data-mce-"+j,p=e.url_converter,r=e.url_converter_scope,m;while(o--){l=k[o];q=l.attributes.map[n];if(q!==m){l.attr(j,q.length>0?q:null);l.attr(n,null)}else{q=l.attributes.map[j];if(j==="style"){q=i.serializeStyle(i.parseStyle(q),l.name)}else{if(p){q=p.call(r,q,j,l.name)}}l.attr(j,q.length>0?q:null)}}});c.addAttributeFilter("class",function(j,k){var l=j.length,m,n;while(l--){m=j[l];n=m.attr("class").replace(/(?:^|\s)mce(Item\w+|Selected)(?!\S)/g,"");m.attr("class",n.length>0?n:null)}});c.addAttributeFilter("data-mce-type",function(j,l,k){var m=j.length,n;while(m--){n=j[m];if(n.attributes.map["data-mce-type"]==="bookmark"&&!k.cleanup){n.remove()}}});c.addAttributeFilter("data-mce-expando",function(j,l,k){var m=j.length;while(m--){j[m].attr(l,null)}});c.addNodeFilter("noscript",function(j){var k=j.length,l;while(k--){l=j[k].firstChild;if(l){l.value=a.html.Entities.decode(l.value)}}});c.addNodeFilter("script,style",function(k,l){var m=k.length,n,o;function j(p){return p.replace(/()/g,"\n").replace(/^[\r\n]*|[\r\n]*$/g,"").replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g,"")}while(m--){n=k[m];o=n.firstChild?n.firstChild.value:"";if(l==="script"){n.attr("type",(n.attr("type")||"text/javascript").replace(/^mce\-/,""));if(o.length>0){n.firstChild.value="// "}}else{if(o.length>0){n.firstChild.value=""}}}});c.addNodeFilter("#comment",function(j,k){var l=j.length,m;while(l--){m=j[l];if(m.value.indexOf("[CDATA[")===0){m.name="#cdata";m.type=4;m.value=m.value.replace(/^\[CDATA\[|\]\]$/g,"")}else{if(m.value.indexOf("mce:protected ")===0){m.name="#text";m.type=3;m.raw=true;m.value=unescape(m.value).substr(14)}}}});c.addNodeFilter("xml:namespace,input",function(j,k){var l=j.length,m;while(l--){m=j[l];if(m.type===7){m.remove()}else{if(m.type===1){if(k==="input"&&!("type" in m.attributes.map)){m.attr("type","text")}}}}});if(e.fix_list_elements){c.addNodeFilter("ul,ol",function(k,l){var m=k.length,n,j;while(m--){n=k[m];j=n.parent;if(j.name==="ul"||j.name==="ol"){if(n.prev&&n.prev.name==="li"){n.prev.append(n)}}}})}c.addAttributeFilter("data-mce-src,data-mce-href,data-mce-style",function(j,k){var l=j.length;while(l--){j[l].attr(k,null)}});return{schema:f,addNodeFilter:c.addNodeFilter,addAttributeFilter:c.addAttributeFilter,onPreProcess:h,onPostProcess:b,serialize:function(o,m){var l,p,k,j,n;if(d&&i.select("script,style,select,map").length>0){n=o.innerHTML;o=o.cloneNode(false);i.setHTML(o,n)}else{o=o.cloneNode(true)}l=o.ownerDocument.implementation;if(l.createHTMLDocument){p=l.createHTMLDocument("");g(o.nodeName=="BODY"?o.childNodes:[o],function(q){p.body.appendChild(p.importNode(q,true))});if(o.nodeName!="BODY"){o=p.body.firstChild}else{o=p.body}k=i.doc;i.doc=p}m=m||{};m.format=m.format||"html";if(!m.no_events){m.node=o;h.dispatch(self,m)}j=new a.html.Serializer(e,f);m.content=j.serialize(c.parse(a.trim(m.getInner?o.innerHTML:i.getOuterHTML(o)),m));if(!m.cleanup){m.content=m.content.replace(/\uFEFF/g,"")}if(!m.no_events){b.dispatch(self,m)}if(k){i.doc=k}m.node=null;return m.content},addRules:function(j){f.addValidElements(j)},setRules:function(j){f.setValidElements(j)}}}})(tinymce);(function(a){a.dom.ScriptLoader=function(h){var c=0,k=1,i=2,l={},j=[],e={},d=[],g=0,f;function b(m,v){var x=this,q=a.DOM,s,o,r,n;function p(){q.remove(n);if(s){s.onreadystatechange=s.onload=s=null}v()}function u(){if(typeof(console)!=="undefined"&&console.log){console.log("Failed to load: "+m)}}n=q.uniqueId();if(a.isIE6){o=new a.util.URI(m);r=location;if(o.host==r.hostname&&o.port==r.port&&(o.protocol+":")==r.protocol&&o.protocol.toLowerCase()!="file"){a.util.XHR.send({url:a._addVer(o.getURI()),success:function(y){var t=q.create("script",{type:"text/javascript"});t.text=y;document.getElementsByTagName("head")[0].appendChild(t);q.remove(t);p()},error:u});return}}s=document.createElement("script");s.id=n;s.type="text/javascript";s.src=a._addVer(m);if(!a.isIE||a.isIE11){s.onload=p}s.onerror=u;if(!a.isOpera){s.onreadystatechange=function(){var t=s.readyState;if(t=="complete"||t=="loaded"){p()}}}(document.getElementsByTagName("head")[0]||document.body).appendChild(s)}this.isDone=function(m){return l[m]==i};this.markDone=function(m){l[m]=i};this.add=this.load=function(m,q,n){var o,p=l[m];if(p==f){j.push(m);l[m]=c}if(q){if(!e[m]){e[m]=[]}e[m].push({func:q,scope:n||this})}};this.loadQueue=function(n,m){this.loadScripts(j,n,m)};this.loadScripts=function(m,q,p){var o;function n(r){a.each(e[r],function(s){s.func.call(s.scope)});e[r]=f}d.push({func:q,scope:p||this});o=function(){var r=a.grep(m);m.length=0;a.each(r,function(s){if(l[s]==i){n(s);return}if(l[s]!=k){l[s]=k;g++;b(s,function(){l[s]=i;g--;n(s);o()})}});if(!g){a.each(d,function(s){s.func.call(s.scope)});d.length=0}};o()}};a.ScriptLoader=new a.dom.ScriptLoader()})(tinymce);(function(a){a.dom.RangeUtils=function(c){var b="\uFEFF";this.walk=function(d,s){var i=d.startContainer,l=d.startOffset,t=d.endContainer,m=d.endOffset,j,g,o,h,r,q,e;e=c.select("td.mceSelected,th.mceSelected");if(e.length>0){a.each(e,function(u){s([u])});return}function f(u){var v;v=u[0];if(v.nodeType===3&&v===i&&l>=v.nodeValue.length){u.splice(0,1)}v=u[u.length-1];if(m===0&&u.length>0&&v===t&&v.nodeType===3){u.splice(u.length-1,1)}return u}function p(x,v,u){var y=[];for(;x&&x!=u;x=x[v]){y.push(x)}return y}function n(v,u){do{if(v.parentNode==u){return v}v=v.parentNode}while(v)}function k(x,v,y){var u=y?"nextSibling":"previousSibling";for(h=x,r=h.parentNode;h&&h!=v;h=r){r=h.parentNode;q=p(h==x?h:h[u],u);if(q.length){if(!y){q.reverse()}s(f(q))}}}if(i.nodeType==1&&i.hasChildNodes()){i=i.childNodes[l]}if(t.nodeType==1&&t.hasChildNodes()){t=t.childNodes[Math.min(m-1,t.childNodes.length-1)]}if(i==t){return s(f([i]))}j=c.findCommonAncestor(i,t);for(h=i;h;h=h.parentNode){if(h===t){return k(i,j,true)}if(h===j){break}}for(h=t;h;h=h.parentNode){if(h===i){return k(t,j)}if(h===j){break}}g=n(i,j)||i;o=n(t,j)||t;k(i,g,true);q=p(g==i?g:g.nextSibling,"nextSibling",o==t?o.nextSibling:o);if(q.length){s(f(q))}k(t,o)};this.split=function(e){var h=e.startContainer,d=e.startOffset,i=e.endContainer,g=e.endOffset;function f(j,k){return j.splitText(k)}if(h==i&&h.nodeType==3){if(d>0&&dd){g=g-d;h=i=f(i,g).previousSibling;g=i.nodeValue.length;d=0}else{g=0}}}else{if(h.nodeType==3&&d>0&&d0&&g=m.length){r=0}}t=m[r];f.setAttrib(g,"tabindex","-1");f.setAttrib(t.id,"tabindex","0");f.get(t.id).focus();if(e.actOnFocus){e.onAction(t.id)}if(s){a.cancel(s)}};p=function(z){var v=37,u=39,y=38,A=40,r=27,t=14,s=13,x=32;switch(z.keyCode){case v:if(i){q.moveFocus(-1)}a.cancel(z);break;case u:if(i){q.moveFocus(1)}a.cancel(z);break;case y:if(o){q.moveFocus(-1)}a.cancel(z);break;case A:if(o){q.moveFocus(1)}a.cancel(z);break;case r:if(e.onCancel){e.onCancel();a.cancel(z)}break;case t:case s:case x:if(e.onAction){e.onAction(g);a.cancel(z)}break}};c(m,function(t,r){var s,u;if(!t.id){t.id=f.uniqueId("_mce_item_")}u=f.get(t.id);if(l){f.bind(u,"blur",h);s="-1"}else{s=(r===0?"0":"-1")}u.setAttribute("tabindex",s);f.bind(u,"focus",k)});if(m[0]){g=m[0].id}f.setAttrib(n,"tabindex","-1");var j=f.get(n);f.bind(j,"focus",d);f.bind(j,"keydown",p)}})})(tinymce);(function(c){var b=c.DOM,a=c.is;c.create("tinymce.ui.Control",{Control:function(f,e,d){this.id=f;this.settings=e=e||{};this.rendered=false;this.onRender=new c.util.Dispatcher(this);this.classPrefix="";this.scope=e.scope||this;this.disabled=0;this.active=0;this.editor=d},setAriaProperty:function(f,e){var d=b.get(this.id+"_aria")||b.get(this.id);if(d){b.setAttrib(d,"aria-"+f,!!e)}},focus:function(){b.get(this.id).focus()},setDisabled:function(d){if(d!=this.disabled){this.setAriaProperty("disabled",d);this.setState("Disabled",d);this.setState("Enabled",!d);this.disabled=d}},isDisabled:function(){return this.disabled},setActive:function(d){if(d!=this.active){this.setState("Active",d);this.active=d;this.setAriaProperty("pressed",d)}},isActive:function(){return this.active},setState:function(f,d){var e=b.get(this.id);f=this.classPrefix+f;if(d){b.addClass(e,f)}else{b.removeClass(e,f)}},isRendered:function(){return this.rendered},renderHTML:function(){},renderTo:function(d){b.setHTML(d,this.renderHTML())},postRender:function(){var e=this,d;if(a(e.disabled)){d=e.disabled;e.disabled=-1;e.setDisabled(d)}if(a(e.active)){d=e.active;e.active=-1;e.setActive(d)}},remove:function(){b.remove(this.id);this.destroy()},destroy:function(){c.dom.Event.clear(this.id)}})})(tinymce);tinymce.create("tinymce.ui.Container:tinymce.ui.Control",{Container:function(c,b,a){this.parent(c,b,a);this.controls=[];this.lookup={}},add:function(a){this.lookup[a.id]=a;this.controls.push(a);return a},get:function(a){return this.lookup[a]}});tinymce.create("tinymce.ui.Separator:tinymce.ui.Control",{Separator:function(b,a){this.parent(b,a);this.classPrefix="mceSeparator";this.setDisabled(true)},renderHTML:function(){return tinymce.DOM.createHTML("span",{"class":this.classPrefix,role:"separator","aria-orientation":"vertical",tabindex:"-1"})}});(function(d){var c=d.is,b=d.DOM,e=d.each,a=d.walk;d.create("tinymce.ui.MenuItem:tinymce.ui.Control",{MenuItem:function(g,f){this.parent(g,f);this.classPrefix="mceMenuItem"},setSelected:function(f){this.setState("Selected",f);this.setAriaProperty("checked",!!f);this.selected=f},isSelected:function(){return this.selected},postRender:function(){var f=this;f.parent();if(c(f.selected)){f.setSelected(f.selected)}}})})(tinymce);(function(d){var c=d.is,b=d.DOM,e=d.each,a=d.walk;d.create("tinymce.ui.Menu:tinymce.ui.MenuItem",{Menu:function(h,g){var f=this;f.parent(h,g);f.items={};f.collapsed=false;f.menuCount=0;f.onAddItem=new d.util.Dispatcher(this)},expand:function(g){var f=this;if(g){a(f,function(h){if(h.expand){h.expand()}},"items",f)}f.collapsed=false},collapse:function(g){var f=this;if(g){a(f,function(h){if(h.collapse){h.collapse()}},"items",f)}f.collapsed=true},isCollapsed:function(){return this.collapsed},add:function(f){if(!f.settings){f=new d.ui.MenuItem(f.id||b.uniqueId(),f)}this.onAddItem.dispatch(this,f);return this.items[f.id]=f},addSeparator:function(){return this.add({separator:true})},addMenu:function(f){if(!f.collapse){f=this.createMenu(f)}this.menuCount++;return this.add(f)},hasMenus:function(){return this.menuCount!==0},remove:function(f){delete this.items[f.id]},removeAll:function(){var f=this;a(f,function(g){if(g.removeAll){g.removeAll()}else{g.remove()}g.destroy()},"items",f);f.items={}},createMenu:function(g){var f=new d.ui.Menu(g.id||b.uniqueId(),g);f.onAddItem.add(this.onAddItem.dispatch,this.onAddItem);return f}})})(tinymce);(function(e){var d=e.is,c=e.DOM,f=e.each,a=e.dom.Event,b=e.dom.Element;e.create("tinymce.ui.DropMenu:tinymce.ui.Menu",{DropMenu:function(h,g){g=g||{};g.container=g.container||c.doc.body;g.offset_x=g.offset_x||0;g.offset_y=g.offset_y||0;g.vp_offset_x=g.vp_offset_x||0;g.vp_offset_y=g.vp_offset_y||0;if(d(g.icons)&&!g.icons){g["class"]+=" mceNoIcons"}this.parent(h,g);this.onShowMenu=new e.util.Dispatcher(this);this.onHideMenu=new e.util.Dispatcher(this);this.classPrefix="mceMenu"},createMenu:function(j){var h=this,i=h.settings,g;j.container=j.container||i.container;j.parent=h;j.constrain=j.constrain||i.constrain;j["class"]=j["class"]||i["class"];j.vp_offset_x=j.vp_offset_x||i.vp_offset_x;j.vp_offset_y=j.vp_offset_y||i.vp_offset_y;j.keyboard_focus=i.keyboard_focus;g=new e.ui.DropMenu(j.id||c.uniqueId(),j);g.onAddItem.add(h.onAddItem.dispatch,h.onAddItem);return g},focus:function(){var g=this;if(g.keyboardNav){g.keyboardNav.focus()}},update:function(){var i=this,j=i.settings,g=c.get("menu_"+i.id+"_tbl"),l=c.get("menu_"+i.id+"_co"),h,k;h=j.max_width?Math.min(g.offsetWidth,j.max_width):g.offsetWidth;k=j.max_height?Math.min(g.offsetHeight,j.max_height):g.offsetHeight;if(!c.boxModel){i.element.setStyles({width:h+2,height:k+2})}else{i.element.setStyles({width:h,height:k})}if(j.max_width){c.setStyle(l,"width",h)}if(j.max_height){c.setStyle(l,"height",k);if(g.clientHeightv){p=r?r-u:Math.max(0,(v-A.vp_offset_x)-u)}if((n+A.vp_offset_y+l)>q){n=Math.max(0,(q-A.vp_offset_y)-l)}}c.setStyles(o,{left:p,top:n});z.element.update();z.isMenuVisible=1;z.mouseClickFunc=a.add(o,"click",function(s){var h;s=s.target;if(s&&(s=c.getParent(s,"tr"))&&!c.hasClass(s,m+"ItemSub")){h=z.items[s.id];if(h.isDisabled()){return}k=z;while(k){if(k.hideMenu){k.hideMenu()}k=k.settings.parent}if(h.settings.onclick){h.settings.onclick(s)}return false}});if(z.hasMenus()){z.mouseOverFunc=a.add(o,"mouseover",function(x){var h,t,s;x=x.target;if(x&&(x=c.getParent(x,"tr"))){h=z.items[x.id];if(z.lastMenu){z.lastMenu.collapse(1)}if(h.isDisabled()){return}if(x&&c.hasClass(x,m+"ItemSub")){t=c.getRect(x);h.showMenu((t.x+t.w-i),t.y-i,t.x);z.lastMenu=h;c.addClass(c.get(h.id).firstChild,m+"ItemActive")}}})}a.add(o,"keydown",z._keyHandler,z);z.onShowMenu.dispatch(z);if(A.keyboard_focus){z._setupKeyboardNav()}},hideMenu:function(j){var g=this,i=c.get("menu_"+g.id),h;if(!g.isMenuVisible){return}if(g.keyboardNav){g.keyboardNav.destroy()}a.remove(i,"mouseover",g.mouseOverFunc);a.remove(i,"click",g.mouseClickFunc);a.remove(i,"keydown",g._keyHandler);c.hide(i);g.isMenuVisible=0;if(!j){g.collapse(1)}if(g.element){g.element.hide()}if(h=c.get(g.id)){c.removeClass(h.firstChild,g.classPrefix+"ItemActive")}g.onHideMenu.dispatch(g)},add:function(i){var g=this,h;i=g.parent(i);if(g.isRendered&&(h=c.get("menu_"+g.id))){g._add(c.select("tbody",h)[0],i)}return i},collapse:function(g){this.parent(g);this.hideMenu(1)},remove:function(g){c.remove(g.id);this.destroy();return this.parent(g)},destroy:function(){var g=this,h=c.get("menu_"+g.id);if(g.keyboardNav){g.keyboardNav.destroy()}a.remove(h,"mouseover",g.mouseOverFunc);a.remove(c.select("a",h),"focus",g.mouseOverFunc);a.remove(h,"click",g.mouseClickFunc);a.remove(h,"keydown",g._keyHandler);if(g.element){g.element.remove()}c.remove(h)},renderNode:function(){var i=this,j=i.settings,l,h,k,g;g=c.create("div",{role:"listbox",id:"menu_"+i.id,"class":j["class"],style:"position:absolute;left:0;top:0;z-index:200000;outline:0"});if(i.settings.parent){c.setAttrib(g,"aria-parent","menu_"+i.settings.parent.id)}k=c.add(g,"div",{role:"presentation",id:"menu_"+i.id+"_co","class":i.classPrefix+(j["class"]?" "+j["class"]:"")});i.element=new b("menu_"+i.id,{blocker:1,container:j.container});if(j.menu_line){c.add(k,"span",{"class":i.classPrefix+"Line"})}l=c.add(k,"table",{role:"presentation",id:"menu_"+i.id+"_tbl",border:0,cellPadding:0,cellSpacing:0});h=c.add(l,"tbody");f(i.items,function(m){i._add(h,m)});i.rendered=true;return g},_setupKeyboardNav:function(){var i,h,g=this;i=c.get("menu_"+g.id);h=c.select("a[role=option]","menu_"+g.id);h.splice(0,0,i);g.keyboardNav=new e.ui.KeyboardNavigation({root:"menu_"+g.id,items:h,onCancel:function(){g.hideMenu()},enableUpDown:true});i.focus()},_keyHandler:function(g){var h=this,i;switch(g.keyCode){case 37:if(h.settings.parent){h.hideMenu();h.settings.parent.focus();a.cancel(g)}break;case 39:if(h.mouseOverFunc){h.mouseOverFunc(g)}break}},_add:function(j,h){var i,q=h.settings,p,l,k,m=this.classPrefix,g;if(q.separator){l=c.add(j,"tr",{id:h.id,"class":m+"ItemSeparator"});c.add(l,"td",{"class":m+"ItemSeparator"});if(i=l.previousSibling){c.addClass(i,"mceLast")}return}i=l=c.add(j,"tr",{id:h.id,"class":m+"Item "+m+"ItemEnabled"});i=k=c.add(i,q.titleItem?"th":"td");i=p=c.add(i,"a",{id:h.id+"_aria",role:q.titleItem?"presentation":"option",href:"javascript:;",onclick:"return false;",onmousedown:"return false;"});if(q.parent){c.setAttrib(p,"aria-haspopup","true");c.setAttrib(p,"aria-owns","menu_"+h.id)}c.addClass(k,q["class"]);g=c.add(i,"span",{"class":"mceIcon"+(q.icon?" mce_"+q.icon:"")});if(q.icon_src){c.add(g,"img",{src:q.icon_src})}i=c.add(i,q.element||"span",{"class":"mceText",title:h.settings.title},h.settings.title);if(h.settings.style){if(typeof h.settings.style=="function"){h.settings.style=h.settings.style()}c.setAttrib(i,"style",h.settings.style)}if(j.childNodes.length==1){c.addClass(l,"mceFirst")}if((i=l.previousSibling)&&c.hasClass(i,m+"ItemSeparator")){c.addClass(l,"mceFirst")}if(h.collapse){c.addClass(l,m+"ItemSub")}if(i=l.previousSibling){c.removeClass(i,"mceLast")}c.addClass(l,"mceLast")}})})(tinymce);(function(b){var a=b.DOM;b.create("tinymce.ui.Button:tinymce.ui.Control",{Button:function(e,d,c){this.parent(e,d,c);this.classPrefix="mceButton"},renderHTML:function(){var f=this.classPrefix,e=this.settings,d,c;c=a.encode(e.label||"");d='';if(e.image&&!(this.editor&&this.editor.forcedHighContrastMode)){d+=''+a.encode(e.title)+''+(c?''+c+"":"")}else{d+=''+(c?''+c+"":"")}d+='";d+="";return d},postRender:function(){var d=this,e=d.settings,c;if(b.isIE&&d.editor){b.dom.Event.add(d.id,"mousedown",function(f){var g=d.editor.selection.getNode().nodeName;c=g==="IMG"?d.editor.selection.getBookmark():null})}b.dom.Event.add(d.id,"click",function(f){if(!d.isDisabled()){if(b.isIE&&d.editor&&c!==null){d.editor.selection.moveToBookmark(c)}return e.onclick.call(e.scope,f)}});b.dom.Event.add(d.id,"keydown",function(f){if(!d.isDisabled()&&f.keyCode==b.VK.SPACEBAR){b.dom.Event.cancel(f);return e.onclick.call(e.scope,f)}})}})})(tinymce);(function(e){var d=e.DOM,b=e.dom.Event,f=e.each,a=e.util.Dispatcher,c;e.create("tinymce.ui.ListBox:tinymce.ui.Control",{ListBox:function(j,i,g){var h=this;h.parent(j,i,g);h.items=[];h.onChange=new a(h);h.onPostRender=new a(h);h.onAdd=new a(h);h.onRenderMenu=new e.util.Dispatcher(this);h.classPrefix="mceListBox";h.marked={}},select:function(h){var g=this,j,i;g.marked={};if(h==c){return g.selectByIndex(-1)}if(h&&typeof(h)=="function"){i=h}else{i=function(k){return k==h}}if(h!=g.selectedValue){f(g.items,function(l,k){if(i(l.value)){j=1;g.selectByIndex(k);return false}});if(!j){g.selectByIndex(-1)}}},selectByIndex:function(g){var i=this,j,k,h;i.marked={};if(g!=i.selectedIndex){j=d.get(i.id+"_text");h=d.get(i.id+"_voiceDesc");k=i.items[g];if(k){i.selectedValue=k.value;i.selectedIndex=g;d.setHTML(j,d.encode(k.title));d.setHTML(h,i.settings.title+" - "+k.title);d.removeClass(j,"mceTitle");d.setAttrib(i.id,"aria-valuenow",k.title)}else{d.setHTML(j,d.encode(i.settings.title));d.setHTML(h,d.encode(i.settings.title));d.addClass(j,"mceTitle");i.selectedValue=i.selectedIndex=null;d.setAttrib(i.id,"aria-valuenow",i.settings.title)}j=0}},mark:function(g){this.marked[g]=true},add:function(j,g,i){var h=this;i=i||{};i=e.extend(i,{title:j,value:g});h.items.push(i);h.onAdd.dispatch(h,i)},getLength:function(){return this.items.length},renderHTML:function(){var j="",g=this,i=g.settings,k=g.classPrefix;j='';j+="";j+="";j+="";return j},showMenu:function(){var h=this,j,i=d.get(this.id),g;if(h.isDisabled()||h.items.length===0){return}if(h.menu&&h.menu.isMenuVisible){return h.hideMenu()}if(!h.isMenuRendered){h.renderMenu();h.isMenuRendered=true}j=d.getPos(i);g=h.menu;g.settings.offset_x=j.x;g.settings.offset_y=j.y;g.settings.keyboard_focus=!e.isOpera;f(h.items,function(k){if(g.items[k.id]){g.items[k.id].setSelected(0)}});f(h.items,function(k){if(g.items[k.id]&&h.marked[k.value]){g.items[k.id].setSelected(1)}if(k.value===h.selectedValue){g.items[k.id].setSelected(1)}});g.showMenu(0,i.clientHeight);b.add(d.doc,"mousedown",h.hideMenu,h);d.addClass(h.id,h.classPrefix+"Selected")},hideMenu:function(h){var g=this;if(g.menu&&g.menu.isMenuVisible){d.removeClass(g.id,g.classPrefix+"Selected");if(h&&h.type=="mousedown"&&(h.target.id==g.id+"_text"||h.target.id==g.id+"_open")){return}if(!h||!d.getParent(h.target,".mceMenu")){d.removeClass(g.id,g.classPrefix+"Selected");b.remove(d.doc,"mousedown",g.hideMenu,g);g.menu.hideMenu()}}},renderMenu:function(){var h=this,g;g=h.settings.control_manager.createDropMenu(h.id+"_menu",{menu_line:1,"class":h.classPrefix+"Menu mceNoIcons",max_width:250,max_height:150});g.onHideMenu.add(function(){h.hideMenu();h.focus()});g.add({title:h.settings.title,"class":"mceMenuItemTitle",onclick:function(){if(h.settings.onselect("")!==false){h.select("")}}});f(h.items,function(i){if(i.value===c){g.add({title:i.title,role:"option","class":"mceMenuItemTitle",onclick:function(){if(h.settings.onselect("")!==false){h.select("")}}})}else{i.id=d.uniqueId();i.role="option";i.onclick=function(){if(h.settings.onselect(i.value)!==false){h.select(i.value)}};g.add(i)}});h.onRenderMenu.dispatch(h,g);h.menu=g},postRender:function(){var g=this,h=g.classPrefix;b.add(g.id,"click",g.showMenu,g);b.add(g.id,"keydown",function(i){if(i.keyCode==32){g.showMenu(i);b.cancel(i)}});b.add(g.id,"focus",function(){if(!g._focused){g.keyDownHandler=b.add(g.id,"keydown",function(i){if(i.keyCode==40){g.showMenu();b.cancel(i)}});g.keyPressHandler=b.add(g.id,"keypress",function(j){var i;if(j.keyCode==13){i=g.selectedValue;g.selectedValue=null;b.cancel(j);g.settings.onselect(i)}})}g._focused=1});b.add(g.id,"blur",function(){b.remove(g.id,"keydown",g.keyDownHandler);b.remove(g.id,"keypress",g.keyPressHandler);g._focused=0});if(e.isIE6||!d.boxModel){b.add(g.id,"mouseover",function(){if(!d.hasClass(g.id,h+"Disabled")){d.addClass(g.id,h+"Hover")}});b.add(g.id,"mouseout",function(){if(!d.hasClass(g.id,h+"Disabled")){d.removeClass(g.id,h+"Hover")}})}g.onPostRender.dispatch(g,d.get(g.id))},destroy:function(){this.parent();b.clear(this.id+"_text");b.clear(this.id+"_open")}})})(tinymce);(function(e){var d=e.DOM,b=e.dom.Event,f=e.each,a=e.util.Dispatcher,c;e.create("tinymce.ui.NativeListBox:tinymce.ui.ListBox",{NativeListBox:function(h,g){this.parent(h,g);this.classPrefix="mceNativeListBox"},setDisabled:function(g){d.get(this.id).disabled=g;this.setAriaProperty("disabled",g)},isDisabled:function(){return d.get(this.id).disabled},select:function(h){var g=this,j,i;if(h==c){return g.selectByIndex(-1)}if(h&&typeof(h)=="function"){i=h}else{i=function(k){return k==h}}if(h!=g.selectedValue){f(g.items,function(l,k){if(i(l.value)){j=1;g.selectByIndex(k);return false}});if(!j){g.selectByIndex(-1)}}},selectByIndex:function(g){d.get(this.id).selectedIndex=g+1;this.selectedValue=this.items[g]?this.items[g].value:null},add:function(k,h,g){var j,i=this;g=g||{};g.value=h;if(i.isRendered()){d.add(d.get(this.id),"option",g,k)}j={title:k,value:h,attribs:g};i.items.push(j);i.onAdd.dispatch(i,j)},getLength:function(){return this.items.length},renderHTML:function(){var i,g=this;i=d.createHTML("option",{value:""},"-- "+g.settings.title+" --");f(g.items,function(h){i+=d.createHTML("option",{value:h.value},h.title)});i=d.createHTML("select",{id:g.id,"class":"mceNativeListBox","aria-labelledby":g.id+"_aria"},i);i+=d.createHTML("span",{id:g.id+"_aria",style:"display: none"},g.settings.title);return i},postRender:function(){var h=this,i,j=true;h.rendered=true;function g(l){var k=h.items[l.target.selectedIndex-1];if(k&&(k=k.value)){h.onChange.dispatch(h,k);if(h.settings.onselect){h.settings.onselect(k)}}}b.add(h.id,"change",g);b.add(h.id,"keydown",function(q){var n,p=37,m=39,l=38,r=40,k=13,o=32;b.remove(h.id,"change",i);j=false;n=b.add(h.id,"blur",function(){if(j){return}j=true;b.add(h.id,"change",g);b.remove(h.id,"blur",n)});if(q.keyCode==k||q.keyCode==o){g(q);return b.cancel(q)}else{if(q.keyCode==r||q.keyCode==l){q.stopImmediatePropagation()}}});h.onPostRender.dispatch(h,d.get(h.id))}})})(tinymce);(function(c){var b=c.DOM,a=c.dom.Event,d=c.each;c.create("tinymce.ui.MenuButton:tinymce.ui.Button",{MenuButton:function(g,f,e){this.parent(g,f,e);this.onRenderMenu=new c.util.Dispatcher(this);f.menu_container=f.menu_container||b.doc.body},showMenu:function(){var g=this,j,i,h=b.get(g.id),f;if(g.isDisabled()){return}if(!g.isMenuRendered){g.renderMenu();g.isMenuRendered=true}if(g.isMenuVisible){return g.hideMenu()}j=b.getPos(g.settings.menu_container);i=b.getPos(h);f=g.menu;f.settings.offset_x=i.x;f.settings.offset_y=i.y;f.settings.vp_offset_x=i.x;f.settings.vp_offset_y=i.y;f.settings.keyboard_focus=g._focused;f.showMenu(0,h.firstChild.clientHeight);a.add(b.doc,"mousedown",g.hideMenu,g);g.setState("Selected",1);g.isMenuVisible=1},renderMenu:function(){var f=this,e;e=f.settings.control_manager.createDropMenu(f.id+"_menu",{menu_line:1,"class":this.classPrefix+"Menu",icons:f.settings.icons});e.onHideMenu.add(function(){f.hideMenu();f.focus()});f.onRenderMenu.dispatch(f,e);f.menu=e},hideMenu:function(g){var f=this;if(g&&g.type=="mousedown"&&b.getParent(g.target,function(h){return h.id===f.id||h.id===f.id+"_open"})){return}if(!g||!b.getParent(g.target,".mceMenu")){f.setState("Selected",0);a.remove(b.doc,"mousedown",f.hideMenu,f);if(f.menu){f.menu.hideMenu()}}f.isMenuVisible=0},postRender:function(){var e=this,f=e.settings;a.add(e.id,"click",function(){if(!e.isDisabled()){if(f.onclick){f.onclick(e.value)}e.showMenu()}})}})})(tinymce);(function(c){var b=c.DOM,a=c.dom.Event,d=c.each;c.create("tinymce.ui.SplitButton:tinymce.ui.MenuButton",{SplitButton:function(g,f,e){this.parent(g,f,e);this.classPrefix="mceSplitButton"},renderHTML:function(){var i,f=this,g=f.settings,e;i="";if(g.image){e=b.createHTML("img ",{src:g.image,role:"presentation","class":"mceAction "+g["class"]})}else{e=b.createHTML("span",{"class":"mceAction "+g["class"]},"")}e+=b.createHTML("span",{"class":"mceVoiceLabel mceIconOnly",id:f.id+"_voice",style:"display:none;"},g.title);i+=""+b.createHTML("a",{role:"button",id:f.id+"_action",tabindex:"-1",href:"javascript:;","class":"mceAction "+g["class"],onclick:"return false;",onmousedown:"return false;",title:g.title},e)+"";e=b.createHTML("span",{"class":"mceOpen "+g["class"]},'');i+=""+b.createHTML("a",{role:"button",id:f.id+"_open",tabindex:"-1",href:"javascript:;","class":"mceOpen "+g["class"],onclick:"return false;",onmousedown:"return false;",title:g.title},e)+"";i+="";i=b.createHTML("table",{role:"presentation","class":"mceSplitButton mceSplitButtonEnabled "+g["class"],cellpadding:"0",cellspacing:"0",title:g.title},i);return b.createHTML("div",{id:f.id,role:"button",tabindex:"0","aria-labelledby":f.id+"_voice","aria-haspopup":"true"},i)},postRender:function(){var e=this,g=e.settings,f;if(g.onclick){f=function(h){if(!e.isDisabled()){g.onclick(e.value);a.cancel(h)}};a.add(e.id+"_action","click",f);a.add(e.id,["click","keydown"],function(h){var k=32,m=14,i=13,j=38,l=40;if((h.keyCode===32||h.keyCode===13||h.keyCode===14)&&!h.altKey&&!h.ctrlKey&&!h.metaKey){f();a.cancel(h)}else{if(h.type==="click"||h.keyCode===l){e.showMenu();a.cancel(h)}}})}a.add(e.id+"_open","click",function(h){e.showMenu();a.cancel(h)});a.add([e.id,e.id+"_open"],"focus",function(){e._focused=1});a.add([e.id,e.id+"_open"],"blur",function(){e._focused=0});if(c.isIE6||!b.boxModel){a.add(e.id,"mouseover",function(){if(!b.hasClass(e.id,"mceSplitButtonDisabled")){b.addClass(e.id,"mceSplitButtonHover")}});a.add(e.id,"mouseout",function(){if(!b.hasClass(e.id,"mceSplitButtonDisabled")){b.removeClass(e.id,"mceSplitButtonHover")}})}},destroy:function(){this.parent();a.clear(this.id+"_action");a.clear(this.id+"_open");a.clear(this.id)}})})(tinymce);(function(d){var c=d.DOM,a=d.dom.Event,b=d.is,e=d.each;d.create("tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton",{ColorSplitButton:function(i,h,f){var g=this;g.parent(i,h,f);g.settings=h=d.extend({colors:"000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,008000,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF",grid_width:8,default_color:"#888888"},g.settings);g.onShowMenu=new d.util.Dispatcher(g);g.onHideMenu=new d.util.Dispatcher(g);g.value=h.default_color},showMenu:function(){var f=this,g,j,i,h;if(f.isDisabled()){return}if(!f.isMenuRendered){f.renderMenu();f.isMenuRendered=true}if(f.isMenuVisible){return f.hideMenu()}i=c.get(f.id);c.show(f.id+"_menu");c.addClass(i,"mceSplitButtonSelected");h=c.getPos(i);c.setStyles(f.id+"_menu",{left:h.x,top:h.y+i.firstChild.clientHeight,zIndex:200000});i=0;a.add(c.doc,"mousedown",f.hideMenu,f);f.onShowMenu.dispatch(f);if(f._focused){f._keyHandler=a.add(f.id+"_menu","keydown",function(k){if(k.keyCode==27){f.hideMenu()}});c.select("a",f.id+"_menu")[0].focus()}f.keyboardNav=new d.ui.KeyboardNavigation({root:f.id+"_menu",items:c.select("a",f.id+"_menu"),onCancel:function(){f.hideMenu();f.focus()}});f.keyboardNav.focus();f.isMenuVisible=1},hideMenu:function(g){var f=this;if(f.isMenuVisible){if(g&&g.type=="mousedown"&&c.getParent(g.target,function(h){return h.id===f.id+"_open"})){return}if(!g||!c.getParent(g.target,".mceSplitButtonMenu")){c.removeClass(f.id,"mceSplitButtonSelected");a.remove(c.doc,"mousedown",f.hideMenu,f);a.remove(f.id+"_menu","keydown",f._keyHandler);c.hide(f.id+"_menu")}f.isMenuVisible=0;f.onHideMenu.dispatch();f.keyboardNav.destroy()}},renderMenu:function(){var p=this,h,k=0,q=p.settings,g,j,l,o,f;o=c.add(q.menu_container,"div",{role:"listbox",id:p.id+"_menu","class":q.menu_class+" "+q["class"],style:"position:absolute;left:0;top:-1000px;"});h=c.add(o,"div",{"class":q["class"]+" mceSplitButtonMenu"});c.add(h,"span",{"class":"mceMenuLine"});g=c.add(h,"table",{role:"presentation","class":"mceColorSplitMenu"});j=c.add(g,"tbody");k=0;e(b(q.colors,"array")?q.colors:q.colors.split(","),function(m){m=m.replace(/^#/,"");if(!k--){l=c.add(j,"tr");k=q.grid_width-1}g=c.add(l,"td");var i={href:"javascript:;",style:{backgroundColor:"#"+m},title:p.editor.getLang("colors."+m,m),"data-mce-color":"#"+m};if(!d.isIE){i.role="option"}g=c.add(g,"a",i);if(p.editor.forcedHighContrastMode){g=c.add(g,"canvas",{width:16,height:16,"aria-hidden":"true"});if(g.getContext&&(f=g.getContext("2d"))){f.fillStyle="#"+m;f.fillRect(0,0,16,16)}else{c.remove(g)}}});if(q.more_colors_func){g=c.add(j,"tr");g=c.add(g,"td",{colspan:q.grid_width,"class":"mceMoreColors"});g=c.add(g,"a",{role:"option",id:p.id+"_more",href:"javascript:;",onclick:"return false;","class":"mceMoreColors"},q.more_colors_title);a.add(g,"click",function(i){q.more_colors_func.call(q.more_colors_scope||this);return a.cancel(i)})}c.addClass(h,"mceColorSplitMenu");a.add(p.id+"_menu","mousedown",function(i){return a.cancel(i)});a.add(p.id+"_menu","click",function(i){var m;i=c.getParent(i.target,"a",j);if(i&&i.nodeName.toLowerCase()=="a"&&(m=i.getAttribute("data-mce-color"))){p.setColor(m)}return false});return o},setColor:function(f){this.displayColor(f);this.hideMenu();this.settings.onselect(f)},displayColor:function(g){var f=this;c.setStyle(f.id+"_preview","backgroundColor",g);f.value=g},postRender:function(){var f=this,g=f.id;f.parent();c.add(g+"_action","div",{id:g+"_preview","class":"mceColorPreview"});c.setStyle(f.id+"_preview","backgroundColor",f.value)},destroy:function(){var f=this;f.parent();a.clear(f.id+"_menu");a.clear(f.id+"_more");c.remove(f.id+"_menu");if(f.keyboardNav){f.keyboardNav.destroy()}}})})(tinymce);(function(b){var d=b.DOM,c=b.each,a=b.dom.Event;b.create("tinymce.ui.ToolbarGroup:tinymce.ui.Container",{renderHTML:function(){var f=this,i=[],e=f.controls,j=b.each,g=f.settings;i.push('
');i.push("");i.push('");j(e,function(h){i.push(h.renderHTML())});i.push("");i.push("
");return i.join("")},focus:function(){var e=this;d.get(e.id).focus()},postRender:function(){var f=this,e=[];c(f.controls,function(g){c(g.controls,function(h){if(h.id){e.push(h)}})});f.keyNav=new b.ui.KeyboardNavigation({root:f.id,items:e,onCancel:function(){if(b.isWebKit){d.get(f.editor.id+"_ifr").focus()}f.editor.focus()},excludeFromTabOrder:!f.settings.tab_focus_toolbar})},destroy:function(){var e=this;e.parent();e.keyNav.destroy();a.clear(e.id)}})})(tinymce);(function(a){var c=a.DOM,b=a.each;a.create("tinymce.ui.Toolbar:tinymce.ui.Container",{renderHTML:function(){var m=this,f="",j,k,n=m.settings,e,d,g,l;l=m.controls;for(e=0;e"))}if(d&&k.ListBox){if(d.Button||d.SplitButton){f+=c.createHTML("td",{"class":"mceToolbarEnd"},c.createHTML("span",null,""))}}if(c.stdMode){f+=''+k.renderHTML()+""}else{f+=""+k.renderHTML()+""}if(g&&k.ListBox){if(g.Button||g.SplitButton){f+=c.createHTML("td",{"class":"mceToolbarStart"},c.createHTML("span",null,""))}}}j="mceToolbarEnd";if(k.Button){j+=" mceToolbarEndButton"}else{if(k.SplitButton){j+=" mceToolbarEndSplitButton"}else{if(k.ListBox){j+=" mceToolbarEndListBox"}}}f+=c.createHTML("td",{"class":j},c.createHTML("span",null,""));return c.createHTML("table",{id:m.id,"class":"mceToolbar"+(n["class"]?" "+n["class"]:""),cellpadding:"0",cellspacing:"0",align:m.settings.align||"",role:"presentation",tabindex:"-1"},""+f+"")}})})(tinymce);(function(b){var a=b.util.Dispatcher,c=b.each;b.create("tinymce.AddOnManager",{AddOnManager:function(){var d=this;d.items=[];d.urls={};d.lookup={};d.onAdd=new a(d)},get:function(d){if(this.lookup[d]){return this.lookup[d].instance}else{return undefined}},dependencies:function(e){var d;if(this.lookup[e]){d=this.lookup[e].dependencies}return d||[]},requireLangPack:function(e){var d=b.settings;if(d&&d.language&&d.language_load!==false){b.ScriptLoader.add(this.urls[e]+"/langs/"+d.language+".js")}},add:function(f,e,d){this.items.push(e);this.lookup[f]={instance:e,dependencies:d};this.onAdd.dispatch(this,f,e);return e},createUrl:function(d,e){if(typeof e==="object"){return e}else{return{prefix:d.prefix,resource:e,suffix:d.suffix}}},addComponents:function(f,d){var e=this.urls[f];b.each(d,function(g){b.ScriptLoader.add(e+"/"+g)})},load:function(j,f,d,h){var g=this,e=f;function i(){var k=g.dependencies(j);b.each(k,function(m){var l=g.createUrl(f,m);g.load(l.resource,l,undefined,undefined)});if(d){if(h){d.call(h)}else{d.call(b.ScriptLoader)}}}if(g.urls[j]){return}if(typeof f==="object"){e=f.prefix+f.resource+f.suffix}if(e.indexOf("/")!==0&&e.indexOf("://")==-1){e=b.baseURL+"/"+e}g.urls[j]=e.substring(0,e.lastIndexOf("/"));if(g.lookup[j]){i()}else{b.ScriptLoader.add(e,i,h)}}});b.PluginManager=new b.AddOnManager();b.ThemeManager=new b.AddOnManager()}(tinymce));(function(j){var g=j.each,d=j.extend,k=j.DOM,i=j.dom.Event,f=j.ThemeManager,b=j.PluginManager,e=j.explode,h=j.util.Dispatcher,a,c=0;j.documentBaseURL=window.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,"");if(!/[\/\\]$/.test(j.documentBaseURL)){j.documentBaseURL+="/"}j.baseURL=new j.util.URI(j.documentBaseURL).toAbsolute(j.baseURL);j.baseURI=new j.util.URI(j.baseURL);j.onBeforeUnload=new h(j);i.add(window,"beforeunload",function(l){j.onBeforeUnload.dispatch(j,l)});j.onAddEditor=new h(j);j.onRemoveEditor=new h(j);j.EditorManager=d(j,{editors:[],i18n:{},activeEditor:null,init:function(x){var v=this,o,n=j.ScriptLoader,u,l=[],r;function q(t){var s=t.id;if(!s){s=t.name;if(s&&!k.get(s)){s=t.name}else{s=k.uniqueId()}t.setAttribute("id",s)}return s}function m(z,A,t){var y=z[A];if(!y){return}if(j.is(y,"string")){t=y.replace(/\.\w+$/,"");t=t?j.resolve(t):0;y=j.resolve(y)}return y.apply(t||this,Array.prototype.slice.call(arguments,2))}function p(t,s){return s.constructor===RegExp?s.test(t.className):k.hasClass(t,s)}v.settings=x;i.bind(window,"ready",function(){var s,t;m(x,"onpageload");switch(x.mode){case"exact":s=x.elements||"";if(s.length>0){g(e(s),function(y){if(k.get(y)){r=new j.Editor(y,x);l.push(r);r.render(1)}else{g(document.forms,function(z){g(z.elements,function(A){if(A.name===y){y="mce_editor_"+c++;k.setAttrib(A,"id",y);r=new j.Editor(y,x);l.push(r);r.render(1)}})})}})}break;case"textareas":case"specific_textareas":g(k.select("textarea"),function(y){if(x.editor_deselector&&p(y,x.editor_deselector)){return}if(!x.editor_selector||p(y,x.editor_selector)){r=new j.Editor(q(y),x);l.push(r);r.render(1)}});break;default:if(x.types){g(x.types,function(y){g(k.select(y.selector),function(A){var z=new j.Editor(q(A),j.extend({},x,y));l.push(z);z.render(1)})})}else{if(x.selector){g(k.select(x.selector),function(z){var y=new j.Editor(q(z),x);l.push(y);y.render(1)})}}}if(x.oninit){s=t=0;g(l,function(y){t++;if(!y.initialized){y.onInit.add(function(){s++;if(s==t){m(x,"oninit")}})}else{s++}if(s==t){m(x,"oninit")}})}})},get:function(l){if(l===a){return this.editors}if(!this.editors.hasOwnProperty(l)){return a}return this.editors[l]},getInstanceById:function(l){return this.get(l)},add:function(m){var l=this,n=l.editors;n[m.id]=m;n.push(m);l._setActive(m);l.onAddEditor.dispatch(l,m);return m},remove:function(n){var m=this,l,o=m.editors;if(!o[n.id]){return null}delete o[n.id];for(l=0;l':"",visual:n,font_size_style_values:"xx-small,x-small,small,medium,large,x-large,xx-large",font_size_legacy_values:"xx-small,small,medium,large,x-large,xx-large,300%",apply_source_formatting:n,directionality:"ltr",forced_root_block:"p",hidden_input:n,padd_empty_editor:n,render_ui:n,indentation:"30px",fix_table_elements:n,inline_styles:n,convert_fonts_to_spans:n,indent:"simple",indent_before:"p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist",indent_after:"p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist",validate:n,entity_encoding:"named",url_converter:m.convertURL,url_converter_scope:m,ie7_compat:n},o);m.id=m.editorId=p;m.isNotDirty=false;m.plugins={};m.documentBaseURI=new k.util.URI(o.document_base_url||k.documentBaseURL,{base_uri:tinyMCE.baseURI});m.baseURI=k.baseURI;m.contentCSS=[];m.contentStyles=[];m.setupEvents();m.execCommands={};m.queryStateCommands={};m.queryValueCommands={};m.execCallback("setup",m)},render:function(o){var p=this,q=p.settings,r=p.id,m=k.ScriptLoader;if(!j.domLoaded){j.add(window,"ready",function(){p.render()});return}tinyMCE.settings=q;if(!p.getElement()){return}if(k.isIDevice&&!k.isIOS5){return}if(!/TEXTAREA|INPUT/i.test(p.getElement().nodeName)&&q.hidden_input&&l.getParent(r,"form")){l.insertAfter(l.create("input",{type:"hidden",name:r}),r)}if(!q.content_editable){p.orgVisibility=p.getElement().style.visibility;p.getElement().style.visibility="hidden"}if(k.WindowManager){p.windowManager=new k.WindowManager(p)}if(q.encoding=="xml"){p.onGetContent.add(function(s,t){if(t.save){t.content=l.encode(t.content)}})}if(q.add_form_submit_trigger){p.onSubmit.addToTop(function(){if(p.initialized){p.save();p.isNotDirty=1}})}if(q.add_unload_trigger){p._beforeUnload=tinyMCE.onBeforeUnload.add(function(){if(p.initialized&&!p.destroyed&&!p.isHidden()){p.save({format:"raw",no_events:true})}})}k.addUnload(p.destroy,p);if(q.submit_patch){p.onBeforeRenderUI.add(function(){var s=p.getElement().form;if(!s){return}if(s._mceOldSubmit){return}if(!s.submit.nodeType&&!s.submit.length){p.formElement=s;s._mceOldSubmit=s.submit;s.submit=function(){k.triggerSave();p.isNotDirty=1;return p.formElement._mceOldSubmit(p.formElement)}}s=null})}function n(){if(q.language&&q.language_load!==false){m.add(k.baseURL+"/langs/"+q.language+".js")}if(q.theme&&typeof q.theme!="function"&&q.theme.charAt(0)!="-"&&!h.urls[q.theme]){h.load(q.theme,"themes/"+q.theme+"/editor_template"+k.suffix+".js")}i(g(q.plugins),function(t){if(t&&!c.urls[t]){if(t.charAt(0)=="-"){t=t.substr(1,t.length);var s=c.dependencies(t);i(s,function(v){var u={prefix:"plugins/",resource:v,suffix:"/editor_plugin"+k.suffix+".js"};v=c.createUrl(u,v);c.load(v.resource,v)})}else{if(t=="safari"){return}c.load(t,{prefix:"plugins/",resource:t,suffix:"/editor_plugin"+k.suffix+".js"})}}});m.loadQueue(function(){if(!p.removed){p.init()}})}n()},init:function(){var q,G=this,H=G.settings,D,y,z,C=G.getElement(),p,m,E,v,B,F,x,r=[];k.add(G);H.aria_label=H.aria_label||l.getAttrib(C,"aria-label",G.getLang("aria.rich_text_area"));if(H.theme){if(typeof H.theme!="function"){H.theme=H.theme.replace(/-/,"");p=h.get(H.theme);G.theme=new p();if(G.theme.init){G.theme.init(G,h.urls[H.theme]||k.documentBaseURL.replace(/\/$/,""))}}else{G.theme=H.theme}}function A(s){var t=c.get(s),o=c.urls[s]||k.documentBaseURL.replace(/\/$/,""),n;if(t&&k.inArray(r,s)===-1){i(c.dependencies(s),function(u){A(u)});n=new t(G,o);G.plugins[s]=n;if(n.init){n.init(G,o);r.push(s)}}}i(g(H.plugins.replace(/\-/g,"")),A);if(H.popup_css!==false){if(H.popup_css){H.popup_css=G.documentBaseURI.toAbsolute(H.popup_css)}else{H.popup_css=G.baseURI.toAbsolute("themes/"+H.theme+"/skins/"+H.skin+"/dialog.css")}}if(H.popup_css_add){H.popup_css+=","+G.documentBaseURI.toAbsolute(H.popup_css_add)}G.controlManager=new k.ControlManager(G);G.onBeforeRenderUI.dispatch(G,G.controlManager);if(H.render_ui&&G.theme){G.orgDisplay=C.style.display;if(typeof H.theme!="function"){D=H.width||C.style.width||C.offsetWidth;y=H.height||C.style.height||C.offsetHeight;z=H.min_height||100;F=/^[0-9\.]+(|px)$/i;if(F.test(""+D)){D=Math.max(parseInt(D,10)+(p.deltaWidth||0),100)}if(F.test(""+y)){y=Math.max(parseInt(y,10)+(p.deltaHeight||0),z)}p=G.theme.renderUI({targetNode:C,width:D,height:y,deltaWidth:H.delta_width,deltaHeight:H.delta_height});l.setStyles(p.sizeContainer||p.editorContainer,{width:D,height:y});y=(p.iframeHeight||y)+(typeof(y)=="number"?(p.deltaHeight||0):"");if(y';if(H.document_base_url!=k.documentBaseURL){G.iframeHTML+=''}if(k.isIE8){if(H.ie7_compat){G.iframeHTML+=''}else{G.iframeHTML+=''}}G.iframeHTML+='';for(x=0;x'}G.contentCSS=[];v=H.body_id||"tinymce";if(v.indexOf("=")!=-1){v=G.getParam("body_id","","hash");v=v[G.id]||v}B=H.body_class||"";if(B.indexOf("=")!=-1){B=G.getParam("body_class","","hash");B=B[G.id]||""}G.iframeHTML+='
";if(k.relaxedDomain&&(b||(k.isOpera&&parseFloat(opera.version())<11))){E='javascript:(function(){document.open();document.domain="'+document.domain+'";var ed = window.parent.tinyMCE.get("'+G.id+'");document.write(ed.iframeHTML);document.close();ed.initContentBody();})()'}q=l.add(p.iframeContainer,"iframe",{id:G.id+"_ifr",src:E||'javascript:""',frameBorder:"0",allowTransparency:"true",title:H.aria_label,style:{width:"100%",height:y,display:"block"}});G.contentAreaContainer=p.iframeContainer;if(p.editorContainer){l.get(p.editorContainer).style.display=G.orgDisplay}C.style.visibility=G.orgVisibility;l.get(G.id).style.display="none";l.setAttrib(G.id,"aria-hidden",true);if(!k.relaxedDomain||!E){G.initContentBody()}C=q=p=null},initContentBody:function(){var n=this,p=n.settings,q=l.get(n.id),r=n.getDoc(),o,m,s;if((!b||!k.relaxedDomain)&&!p.content_editable){r.open();r.write(n.iframeHTML);r.close();if(k.relaxedDomain){r.domain=k.relaxedDomain}}if(p.content_editable){l.addClass(q,"mceContentBody");n.contentDocument=r=p.content_document||document;n.contentWindow=p.content_window||window;n.bodyElement=q;p.content_document=p.content_window=null}m=n.getBody();m.disabled=true;if(!p.readonly){m.contentEditable=n.getParam("content_editable_state",true)}m.disabled=false;n.schema=new k.html.Schema(p);n.dom=new k.dom.DOMUtils(r,{keep_values:true,url_converter:n.convertURL,url_converter_scope:n,hex_colors:p.force_hex_style_colors,class_filter:p.class_filter,update_styles:true,root_element:p.content_editable?n.id:null,schema:n.schema});n.parser=new k.html.DomParser(p,n.schema);n.parser.addAttributeFilter("src,href,style",function(t,u){var v=t.length,y,A=n.dom,z,x;while(v--){y=t[v];z=y.attr(u);x="data-mce-"+u;if(!y.attributes.map[x]){if(u==="style"){y.attr(x,A.serializeStyle(A.parseStyle(z),y.name))}else{y.attr(x,n.convertURL(z,u,y.name))}}}});n.parser.addNodeFilter("script",function(t,u){var v=t.length,x;while(v--){x=t[v];x.attr("type","mce-"+(x.attr("type")||"text/javascript"))}});n.parser.addNodeFilter("#cdata",function(t,u){var v=t.length,x;while(v--){x=t[v];x.type=8;x.name="#comment";x.value="[CDATA["+x.value+"]]"}});n.parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div",function(u,v){var x=u.length,y,t=n.schema.getNonEmptyElements();while(x--){y=u[x];if(y.isEmpty(t)){y.empty().append(new k.html.Node("br",1)).shortEnded=true}}});n.serializer=new k.dom.Serializer(p,n.dom,n.schema);n.selection=new k.dom.Selection(n.dom,n.getWin(),n.serializer,n);n.formatter=new k.Formatter(n);n.undoManager=new k.UndoManager(n);n.forceBlocks=new k.ForceBlocks(n);n.enterKey=new k.EnterKey(n);n.editorCommands=new k.EditorCommands(n);n.onExecCommand.add(function(t,u){if(!/^(FontName|FontSize)$/.test(u)){n.nodeChanged()}});n.serializer.onPreProcess.add(function(t,u){return n.onPreProcess.dispatch(n,u,t)});n.serializer.onPostProcess.add(function(t,u){return n.onPostProcess.dispatch(n,u,t)});n.onPreInit.dispatch(n);if(!p.browser_spellcheck&&!p.gecko_spellcheck){r.body.spellcheck=false}if(!p.readonly){n.bindNativeEvents()}n.controlManager.onPostRender.dispatch(n,n.controlManager);n.onPostRender.dispatch(n);n.quirks=k.util.Quirks(n);if(p.directionality){m.dir=p.directionality}if(p.nowrap){m.style.whiteSpace="nowrap"}if(p.protect){n.onBeforeSetContent.add(function(t,u){i(p.protect,function(v){u.content=u.content.replace(v,function(x){return""})})})}n.onSetContent.add(function(){n.addVisual(n.getBody())});if(p.padd_empty_editor){n.onPostProcess.add(function(t,u){u.content=u.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")})}n.load({initial:true,format:"html"});n.startContent=n.getContent({format:"raw"});n.initialized=true;n.onInit.dispatch(n);n.execCallback("setupcontent_callback",n.id,m,r);n.execCallback("init_instance_callback",n);n.focus(true);n.nodeChanged({initial:true});if(n.contentStyles.length>0){s="";i(n.contentStyles,function(t){s+=t+"\r\n"});n.dom.addStyle(s)}i(n.contentCSS,function(t){n.dom.loadCSS(t)});if(p.auto_focus){setTimeout(function(){var t=k.get(p.auto_focus);t.selection.select(t.getBody(),1);t.selection.collapse(1);t.getBody().focus();t.getWin().focus()},100)}q=r=m=null},focus:function(p){var o,u=this,t=u.selection,q=u.settings.content_editable,n,r,s=u.getDoc(),m;if(!p){if(u.bookmark){t.moveToBookmark(u.bookmark);u.bookmark=null}n=t.getRng();if(n.item){r=n.item(0)}u._refreshContentEditable();if(!q){u.getWin().focus()}if(k.isGecko||q){m=u.getBody();if(m.setActive&&!k.isIE11){m.setActive()}else{m.focus()}if(q){t.normalize()}}if(r&&r.ownerDocument==s){n=s.body.createControlRange();n.addElement(r);n.select()}}if(k.activeEditor!=u){if((o=k.activeEditor)!=null){o.onDeactivate.dispatch(o,u)}u.onActivate.dispatch(u,o)}k._setActive(u)},execCallback:function(q){var m=this,p=m.settings[q],o;if(!p){return}if(m.callbackLookup&&(o=m.callbackLookup[q])){p=o.func;o=o.scope}if(d(p,"string")){o=p.replace(/\.\w+$/,"");o=o?k.resolve(o):0;p=k.resolve(p);m.callbackLookup=m.callbackLookup||{};m.callbackLookup[q]={func:p,scope:o}}return p.apply(o||m,Array.prototype.slice.call(arguments,1))},translate:function(m){var o=this.settings.language||"en",n=k.i18n;if(!m){return""}return n[o+"."+m]||m.replace(/\{\#([^\}]+)\}/g,function(q,p){return n[o+"."+p]||"{#"+p+"}"})},getLang:function(o,m){return k.i18n[(this.settings.language||"en")+"."+o]||(d(m)?m:"{#"+o+"}")},getParam:function(t,q,m){var r=k.trim,p=d(this.settings[t])?this.settings[t]:q,s;if(m==="hash"){s={};if(d(p,"string")){i(p.indexOf("=")>0?p.split(/[;,](?![^=;,]*(?:[;,]|$))/):p.split(","),function(n){n=n.split("=");if(n.length>1){s[r(n[0])]=r(n[1])}else{s[r(n[0])]=r(n)}})}else{s=p}return s}return p},nodeChanged:function(q){var m=this,n=m.selection,p;if(!m.initialized){return}q=q||{};p=n.getStart()||m.getBody();p=b&&p.ownerDocument!=m.getDoc()?m.getBody():p;q.parents=[];m.dom.getParent(p,function(o){if(o.nodeName=="BODY"){return true}q.parents.push(o)});m.onNodeChange.dispatch(m,q?q.controlManager||m.controlManager:m.controlManager,p,n.isCollapsed(),q)},addButton:function(n,o){var m=this;m.buttons=m.buttons||{};m.buttons[n]=o},addCommand:function(m,o,n){this.execCommands[m]={func:o,scope:n||this}},addQueryStateHandler:function(m,o,n){this.queryStateCommands[m]={func:o,scope:n||this}},addQueryValueHandler:function(m,o,n){this.queryValueCommands[m]={func:o,scope:n||this}},addShortcut:function(o,q,m,p){var n=this,r;if(n.settings.custom_shortcuts===false){return false}n.shortcuts=n.shortcuts||{};if(d(m,"string")){r=m;m=function(){n.execCommand(r,false,null)}}if(d(m,"object")){r=m;m=function(){n.execCommand(r[0],r[1],r[2])}}i(g(o),function(s){var t={func:m,scope:p||this,desc:n.translate(q),alt:false,ctrl:false,shift:false};i(g(s,"+"),function(u){switch(u){case"alt":case"ctrl":case"shift":t[u]=true;break;default:t.charCode=u.charCodeAt(0);t.keyCode=u.toUpperCase().charCodeAt(0)}});n.shortcuts[(t.ctrl?"ctrl":"")+","+(t.alt?"alt":"")+","+(t.shift?"shift":"")+","+t.keyCode]=t});return true},execCommand:function(u,r,x,m){var p=this,q=0,v,n;if(!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(u)&&(!m||!m.skip_focus)){p.focus()}m=f({},m);p.onBeforeExecCommand.dispatch(p,u,r,x,m);if(m.terminate){return false}if(p.execCallback("execcommand_callback",p.id,p.selection.getNode(),u,r,x)){p.onExecCommand.dispatch(p,u,r,x,m);return true}if(v=p.execCommands[u]){n=v.func.call(v.scope,r,x);if(n!==true){p.onExecCommand.dispatch(p,u,r,x,m);return n}}i(p.plugins,function(o){if(o.execCommand&&o.execCommand(u,r,x)){p.onExecCommand.dispatch(p,u,r,x,m);q=1;return false}});if(q){return true}if(p.theme&&p.theme.execCommand&&p.theme.execCommand(u,r,x)){p.onExecCommand.dispatch(p,u,r,x,m);return true}if(p.editorCommands.execCommand(u,r,x)){p.onExecCommand.dispatch(p,u,r,x,m);return true}p.getDoc().execCommand(u,r,x);p.onExecCommand.dispatch(p,u,r,x,m)},queryCommandState:function(q){var n=this,r,p;if(n._isHidden()){return}if(r=n.queryStateCommands[q]){p=r.func.call(r.scope);if(p!==true){return p}}r=n.editorCommands.queryCommandState(q);if(r!==-1){return r}try{return this.getDoc().queryCommandState(q)}catch(m){}},queryCommandValue:function(r){var n=this,q,p;if(n._isHidden()){return}if(q=n.queryValueCommands[r]){p=q.func.call(q.scope);if(p!==true){return p}}q=n.editorCommands.queryCommandValue(r);if(d(q)){return q}try{return this.getDoc().queryCommandValue(r)}catch(m){}},show:function(){var m=this;l.show(m.getContainer());l.hide(m.id);m.load()},hide:function(){var m=this,n=m.getDoc();if(b&&n){n.execCommand("SelectAll")}m.save();l.hide(m.getContainer());l.setStyle(m.id,"display",m.orgDisplay)},isHidden:function(){return !l.isHidden(this.id)},setProgressState:function(m,n,p){this.onSetProgressState.dispatch(this,m,n,p);return m},load:function(q){var m=this,p=m.getElement(),n;if(p){q=q||{};q.load=true;n=m.setContent(d(p.value)?p.value:p.innerHTML,q);q.element=p;if(!q.no_events){m.onLoadContent.dispatch(m,q)}q.element=p=null;return n}},save:function(r){var m=this,q=m.getElement(),n,p;if(!q||!m.initialized){return}r=r||{};r.save=true;r.element=q;n=r.content=m.getContent(r);if(!r.no_events){m.onSaveContent.dispatch(m,r)}n=r.content;if(!/TEXTAREA|INPUT/i.test(q.nodeName)){q.innerHTML=n;if(p=l.getParent(m.id,"form")){i(p.elements,function(o){if(o.name==m.id){o.value=n;return false}})}}else{q.value=n}r.element=q=null;return n},setContent:function(q,o){var n=this,m=n.getBody(),p;o=o||{};o.format=o.format||"html";o.set=true;o.content=q;if(!o.no_events){n.onBeforeSetContent.dispatch(n,o)}q=o.content;if(q.length===0||/^\s+$/.test(q)){p=n.settings.forced_root_block;if(p&&n.schema.isValidChild(m.nodeName.toLowerCase(),p.toLowerCase())){if(b){q="<"+p+">"}else{q="<"+p+'>
"}}else{if(!b){q='
'}}m.innerHTML=q;n.selection.select(m,true);n.selection.collapse(true);return}if(o.format!=="raw"){q=new k.html.Serializer({},n.schema).serialize(n.parser.parse(q))}o.content=k.trim(q);n.dom.setHTML(m,o.content);if(!o.no_events){n.onSetContent.dispatch(n,o)}if(!n.settings.content_editable||document.activeElement===n.getBody()){n.selection.normalize()}return o.content},getContent:function(o){var n=this,p,m=n.getBody();o=o||{};o.format=o.format||"html";o.get=true;o.getInner=true;if(!o.no_events){n.onBeforeGetContent.dispatch(n,o)}if(o.format=="raw"){p=m.innerHTML}else{if(o.format=="text"){p=m.innerText||m.textContent}else{p=n.serializer.serialize(m,o)}}if(o.format!="text"){o.content=k.trim(p)}else{o.content=p}if(!o.no_events){n.onGetContent.dispatch(n,o)}return o.content},isDirty:function(){var m=this;return k.trim(m.startContent)!==k.trim(m.getContent({format:"raw"}))&&!m.isNotDirty},getContainer:function(){var m=this;if(!m.container){m.container=l.get(m.editorContainer||m.id+"_parent")}return m.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return l.get(this.settings.content_element||this.id)},getWin:function(){var m=this,n;if(!m.contentWindow){n=l.get(m.id+"_ifr");if(n){m.contentWindow=n.contentWindow}}return m.contentWindow},getDoc:function(){var m=this,n;if(!m.contentDocument){n=m.getWin();if(n){m.contentDocument=n.document}}return m.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(o,n,q){var m=this,p=m.settings;if(p.urlconverter_callback){return m.execCallback("urlconverter_callback",o,q,true,n)}if(!p.convert_urls||(q&&q.nodeName=="LINK")||o.indexOf("file:")===0){return o}if(p.relative_urls){return m.documentBaseURI.toRelative(o)}o=m.documentBaseURI.toAbsolute(o,p.remove_script_host);return o},addVisual:function(q){var n=this,o=n.settings,p=n.dom,m;q=q||n.getBody();if(!d(n.hasVisual)){n.hasVisual=o.visual}i(p.select("table,a",q),function(s){var r;switch(s.nodeName){case"TABLE":m=o.visual_table_class||"mceItemTable";r=p.getAttrib(s,"border");if(!r||r=="0"){if(n.hasVisual){p.addClass(s,m)}else{p.removeClass(s,m)}}return;case"A":if(!p.getAttrib(s,"href",false)){r=p.getAttrib(s,"name")||s.id;m="mceItemAnchor";if(r){if(n.hasVisual){p.addClass(s,m)}else{p.removeClass(s,m)}}}return}});n.onVisualAid.dispatch(n,q,n.hasVisual)},remove:function(){var m=this,o=m.getContainer(),n=m.getDoc();if(!m.removed){m.removed=1;if(b&&n){n.execCommand("SelectAll")}m.save();l.setStyle(m.id,"display",m.orgDisplay);if(!m.settings.content_editable){j.unbind(m.getWin());j.unbind(m.getDoc())}j.unbind(m.getBody());j.clear(o);m.execCallback("remove_instance_callback",m);m.onRemove.dispatch(m);m.onExecCommand.listeners=[];k.remove(m);l.remove(o)}},destroy:function(n){var m=this;if(m.destroyed){return}if(a){j.unbind(m.getDoc());j.unbind(m.getWin());j.unbind(m.getBody())}if(!n){k.removeUnload(m.destroy);tinyMCE.onBeforeUnload.remove(m._beforeUnload);if(m.theme&&m.theme.destroy){m.theme.destroy()}m.controlManager.destroy();m.selection.destroy();m.dom.destroy()}if(m.formElement){m.formElement.submit=m.formElement._mceOldSubmit;m.formElement._mceOldSubmit=null}m.contentAreaContainer=m.formElement=m.container=m.settings.content_element=m.bodyElement=m.contentDocument=m.contentWindow=null;if(m.selection){m.selection=m.selection.win=m.selection.dom=m.selection.dom.doc=null}m.destroyed=1},_refreshContentEditable:function(){var n=this,m,o;if(n._isHidden()){m=n.getBody();o=m.parentNode;o.removeChild(m);o.appendChild(m);m.focus()}},_isHidden:function(){var m;if(!a){return 0}m=this.selection.getSel();return(!m||!m.rangeCount||m.rangeCount===0)}})})(tinymce);(function(a){var b=a.each;a.Editor.prototype.setupEvents=function(){var c=this,d=c.settings;b(["onPreInit","onBeforeRenderUI","onPostRender","onLoad","onInit","onRemove","onActivate","onDeactivate","onClick","onEvent","onMouseUp","onMouseDown","onDblClick","onKeyDown","onKeyUp","onKeyPress","onContextMenu","onSubmit","onReset","onPaste","onPreProcess","onPostProcess","onBeforeSetContent","onBeforeGetContent","onSetContent","onGetContent","onLoadContent","onSaveContent","onNodeChange","onChange","onBeforeExecCommand","onExecCommand","onUndo","onRedo","onVisualAid","onSetProgressState","onSetAttrib"],function(e){c[e]=new a.util.Dispatcher(c)});if(d.cleanup_callback){c.onBeforeSetContent.add(function(e,f){f.content=e.execCallback("cleanup_callback","insert_to_editor",f.content,f)});c.onPreProcess.add(function(e,f){if(f.set){e.execCallback("cleanup_callback","insert_to_editor_dom",f.node,f)}if(f.get){e.execCallback("cleanup_callback","get_from_editor_dom",f.node,f)}});c.onPostProcess.add(function(e,f){if(f.set){f.content=e.execCallback("cleanup_callback","insert_to_editor",f.content,f)}if(f.get){f.content=e.execCallback("cleanup_callback","get_from_editor",f.content,f)}})}if(d.save_callback){c.onGetContent.add(function(e,f){if(f.save){f.content=e.execCallback("save_callback",e.id,f.content,e.getBody())}})}if(d.handle_event_callback){c.onEvent.add(function(f,g,h){if(c.execCallback("handle_event_callback",g,f,h)===false){g.preventDefault();g.stopPropagation()}})}if(d.handle_node_change_callback){c.onNodeChange.add(function(f,e,g){f.execCallback("handle_node_change_callback",f.id,g,-1,-1,true,f.selection.isCollapsed())})}if(d.save_callback){c.onSaveContent.add(function(e,g){var f=e.execCallback("save_callback",e.id,g.content,e.getBody());if(f){g.content=f}})}if(d.onchange_callback){c.onChange.add(function(f,e){f.execCallback("onchange_callback",f,e)})}};a.Editor.prototype.bindNativeEvents=function(){var l=this,f,d=l.settings,e=l.dom,h;h={mouseup:"onMouseUp",mousedown:"onMouseDown",click:"onClick",keyup:"onKeyUp",keydown:"onKeyDown",keypress:"onKeyPress",submit:"onSubmit",reset:"onReset",contextmenu:"onContextMenu",dblclick:"onDblClick",paste:"onPaste"};function c(i,m){var n=i.type;if(l.removed){return}if(l.onEvent.dispatch(l,i,m)!==false){l[h[i.fakeType||i.type]].dispatch(l,i,m)}}function j(i){l.focus(true)}function k(i,m){if(m.keyCode!=65||!a.VK.metaKeyPressed(m)){l.selection.normalize()}l.nodeChanged()}b(h,function(m,n){var i=d.content_editable?l.getBody():l.getDoc();switch(n){case"contextmenu":e.bind(i,n,c);break;case"paste":e.bind(l.getBody(),n,c);break;case"submit":case"reset":e.bind(l.getElement().form||a.DOM.getParent(l.id,"form"),n,c);break;default:e.bind(i,n,c)}});e.bind(d.content_editable?l.getBody():(a.isGecko?l.getDoc():l.getWin()),"focus",function(i){l.focus(true)});if(d.content_editable&&a.isOpera){e.bind(l.getBody(),"click",j);e.bind(l.getBody(),"keydown",j)}l.onMouseUp.add(k);l.onKeyUp.add(function(i,n){var m=n.keyCode;if((m>=33&&m<=36)||(m>=37&&m<=40)||m==13||m==45||m==46||m==8||(a.isMac&&(m==91||m==93))||n.ctrlKey){k(i,n)}});l.onReset.add(function(){l.setContent(l.startContent,{format:"raw"})});function g(m,i){if(m.altKey||m.ctrlKey||m.metaKey){b(l.shortcuts,function(n){var o=a.isMac?m.metaKey:m.ctrlKey;if(n.ctrl!=o||n.alt!=m.altKey||n.shift!=m.shiftKey){return}if(m.keyCode==n.keyCode||(m.charCode&&m.charCode==n.charCode)){m.preventDefault();if(i){n.func.call(n.scope)}return true}})}}l.onKeyUp.add(function(i,m){g(m)});l.onKeyPress.add(function(i,m){g(m)});l.onKeyDown.add(function(i,m){g(m,true)});if(a.isOpera){l.onClick.add(function(i,m){m.preventDefault()})}}})(tinymce);(function(d){var e=d.each,b,a=true,c=false;d.EditorCommands=function(n){var m=n.dom,p=n.selection,j={state:{},exec:{},value:{}},k=n.settings,q=n.formatter,o;function r(z,y,x){var v;z=z.toLowerCase();if(v=j.exec[z]){v(z,y,x);return a}return c}function l(x){var v;x=x.toLowerCase();if(v=j.state[x]){return v(x)}return -1}function h(x){var v;x=x.toLowerCase();if(v=j.value[x]){return v(x)}return c}function u(v,x){x=x||"exec";e(v,function(z,y){e(y.toLowerCase().split(","),function(A){j[x][A]=z})})}d.extend(this,{execCommand:r,queryCommandState:l,queryCommandValue:h,addCommands:u});function f(y,x,v){if(x===b){x=c}if(v===b){v=null}return n.getDoc().execCommand(y,x,v)}function t(v){return q.match(v)}function s(v,x){q.toggle(v,x?{value:x}:b)}function i(v){o=p.getBookmark(v)}function g(){p.moveToBookmark(o)}u({"mceResetDesignMode,mceBeginUndoLevel":function(){},"mceEndUndoLevel,mceAddUndoLevel":function(){n.undoManager.add()},"Cut,Copy,Paste":function(z){var y=n.getDoc(),v;try{f(z)}catch(x){v=a}if(v||!y.queryCommandSupported(z)){if(d.isGecko){n.windowManager.confirm(n.getLang("clipboard_msg"),function(A){if(A){open("http://www.mozilla.org/editor/midasdemo/securityprefs.html","_blank")}})}else{n.windowManager.alert(n.getLang("clipboard_no_support"))}}},unlink:function(v){if(p.isCollapsed()){p.select(p.getNode())}f(v);p.collapse(c)},"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(v){var x=v.substring(7);e("left,center,right,full".split(","),function(y){if(x!=y){q.remove("align"+y)}});s("align"+x);r("mceRepaint")},"InsertUnorderedList,InsertOrderedList":function(y){var v,x;f(y);v=m.getParent(p.getNode(),"ol,ul");if(v){x=v.parentNode;if(/^(H[1-6]|P|ADDRESS|PRE)$/.test(x.nodeName)){i();m.split(x,v);g()}}},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(v){s(v)},"ForeColor,HiliteColor,FontName":function(y,x,v){s(y,v)},FontSize:function(z,y,x){var v,A;if(x>=1&&x<=7){A=d.explode(k.font_size_style_values);v=d.explode(k.font_size_classes);if(v){x=v[x-1]||x}else{x=A[x-1]||x}}s(z,x)},RemoveFormat:function(v){q.remove(v)},mceBlockQuote:function(v){s("blockquote")},FormatBlock:function(y,x,v){return s(v||"p")},mceCleanup:function(){var v=p.getBookmark();n.setContent(n.getContent({cleanup:a}),{cleanup:a});p.moveToBookmark(v)},mceRemoveNode:function(z,y,x){var v=x||p.getNode();if(v!=n.getBody()){i();n.dom.remove(v,a);g()}},mceSelectNodeDepth:function(z,y,x){var v=0;m.getParent(p.getNode(),function(A){if(A.nodeType==1&&v++==x){p.select(A);return c}},n.getBody())},mceSelectNode:function(y,x,v){p.select(v)},mceInsertContent:function(B,I,K){var y,J,E,z,F,G,D,C,L,x,A,M,v,H;y=n.parser;J=new d.html.Serializer({},n.schema);v='\uFEFF';G={content:K,format:"html"};p.onBeforeSetContent.dispatch(p,G);K=G.content;if(K.indexOf("{$caret}")==-1){K+="{$caret}"}K=K.replace(/\{\$caret\}/,v);if(!p.isCollapsed()){n.getDoc().execCommand("Delete",false,null)}E=p.getNode();G={context:E.nodeName.toLowerCase()};F=y.parse(K,G);A=F.lastChild;if(A.attr("id")=="mce_marker"){D=A;for(A=A.prev;A;A=A.walk(true)){if(A.type==3||!m.isBlock(A.name)){A.parent.insert(D,A,A.name==="br");break}}}if(!G.invalid){K=J.serialize(F);A=E.firstChild;M=E.lastChild;if(!A||(A===M&&A.nodeName==="BR")){m.setHTML(E,K)}else{p.setContent(K)}}else{p.setContent(v);E=p.getNode();z=n.getBody();if(E.nodeType==9){E=A=z}else{A=E}while(A!==z){E=A;A=A.parentNode}K=E==z?z.innerHTML:m.getOuterHTML(E);K=J.serialize(y.parse(K.replace(//i,function(){return J.serialize(F)})));if(E==z){m.setHTML(z,K)}else{m.setOuterHTML(E,K)}}D=m.get("mce_marker");C=m.getRect(D);L=m.getViewPort(n.getWin());if((C.y+C.h>L.y+L.h||C.yL.x+L.w||C.x")},mceToggleVisualAid:function(){n.hasVisual=!n.hasVisual;n.addVisual()},mceReplaceContent:function(y,x,v){n.execCommand("mceInsertContent",false,v.replace(/\{\$selection\}/g,p.getContent({format:"text"})))},mceInsertLink:function(z,y,x){var v;if(typeof(x)=="string"){x={href:x}}v=m.getParent(p.getNode(),"a");x.href=x.href.replace(" ","%20");if(!v||!x.href){q.remove("link")}if(x.href){q.apply("link",x,v)}},selectAll:function(){var x=m.getRoot(),v=m.createRng();if(p.getRng().setStart){v.setStart(x,0);v.setEnd(x,x.childNodes.length);p.setRng(v)}else{f("SelectAll")}}});u({"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(z){var x="align"+z.substring(7);var v=p.isCollapsed()?[m.getParent(p.getNode(),m.isBlock)]:p.getSelectedBlocks();var y=d.map(v,function(A){return !!q.matchNode(A,x)});return d.inArray(y,a)!==-1},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(v){return t(v)},mceBlockQuote:function(){return t("blockquote")},Outdent:function(){var v;if(k.inline_styles){if((v=m.getParent(p.getStart(),m.isBlock))&&parseInt(v.style.paddingLeft)>0){return a}if((v=m.getParent(p.getEnd(),m.isBlock))&&parseInt(v.style.paddingLeft)>0){return a}}return l("InsertUnorderedList")||l("InsertOrderedList")||(!k.inline_styles&&!!m.getParent(p.getNode(),"BLOCKQUOTE"))},"InsertUnorderedList,InsertOrderedList":function(x){var v=m.getParent(p.getNode(),"ul,ol");return v&&(x==="insertunorderedlist"&&v.tagName==="UL"||x==="insertorderedlist"&&v.tagName==="OL")}},"state");u({"FontSize,FontName":function(y){var x=0,v;if(v=m.getParent(p.getNode(),"span")){if(y=="fontsize"){x=v.style.fontSize}else{x=v.style.fontFamily.replace(/, /g,",").replace(/[\'\"]/g,"").toLowerCase()}}return x}},"value");u({Undo:function(){n.undoManager.undo()},Redo:function(){n.undoManager.redo()}})}})(tinymce);(function(b){var a=b.util.Dispatcher;b.UndoManager=function(h){var l,i=0,e=[],g,k,j,f;function c(){return b.trim(h.getContent({format:"raw",no_events:1}).replace(/]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\/span>/g,""))}function d(){l.typing=false;l.add()}onBeforeAdd=new a(l);k=new a(l);j=new a(l);f=new a(l);k.add(function(m,n){if(m.hasUndo()){return h.onChange.dispatch(h,n,m)}});j.add(function(m,n){return h.onUndo.dispatch(h,n,m)});f.add(function(m,n){return h.onRedo.dispatch(h,n,m)});h.onInit.add(function(){l.add()});h.onBeforeExecCommand.add(function(m,p,o,q,n){if(p!="Undo"&&p!="Redo"&&p!="mceRepaint"&&(!n||!n.skip_undo)){l.beforeChange()}});h.onExecCommand.add(function(m,p,o,q,n){if(p!="Undo"&&p!="Redo"&&p!="mceRepaint"&&(!n||!n.skip_undo)){l.add()}});h.onSaveContent.add(d);h.dom.bind(h.dom.getRoot(),"dragend",d);h.dom.bind(h.getBody(),"focusout",function(m){if(!h.removed&&l.typing){d()}});h.onKeyUp.add(function(m,o){var n=o.keyCode;if((n>=33&&n<=36)||(n>=37&&n<=40)||n==45||n==13||o.ctrlKey){d()}});h.onKeyDown.add(function(m,o){var n=o.keyCode;if((n>=33&&n<=36)||(n>=37&&n<=40)||n==45){if(l.typing){d()}return}if((n<16||n>20)&&n!=224&&n!=91&&!l.typing){l.beforeChange();l.typing=true;l.add()}});h.onMouseDown.add(function(m,n){if(l.typing){d()}});h.addShortcut("ctrl+z","undo_desc","Undo");h.addShortcut("ctrl+y","redo_desc","Redo");l={data:e,typing:false,onBeforeAdd:onBeforeAdd,onAdd:k,onUndo:j,onRedo:f,beforeChange:function(){g=h.selection.getBookmark(2,true)},add:function(p){var m,n=h.settings,o;p=p||{};p.content=c();l.onBeforeAdd.dispatch(l,p);o=e[i];if(o&&o.content==p.content){return null}if(e[i]){e[i].beforeBookmark=g}if(n.custom_undo_redo_levels){if(e.length>n.custom_undo_redo_levels){for(m=0;m0){n=e[--i];h.setContent(n.content,{format:"raw"});h.selection.moveToBookmark(n.beforeBookmark);l.onUndo.dispatch(l,n)}return n},redo:function(){var m;if(i0||this.typing},hasRedo:function(){return i0){g.moveEnd("character",q)}g.select()}catch(n){}}}c.nodeChanged()}}if(b.forced_root_block){c.onKeyUp.add(f);c.onNodeChange.add(f)}};(function(c){var b=c.DOM,a=c.dom.Event,d=c.each,e=c.extend;c.create("tinymce.ControlManager",{ControlManager:function(f,j){var h=this,g;j=j||{};h.editor=f;h.controls={};h.onAdd=new c.util.Dispatcher(h);h.onPostRender=new c.util.Dispatcher(h);h.prefix=j.prefix||f.id+"_";h._cls={};h.onPostRender.add(function(){d(h.controls,function(i){i.postRender()})})},get:function(f){return this.controls[this.prefix+f]||this.controls[f]},setActive:function(h,f){var g=null;if(g=this.get(h)){g.setActive(f)}return g},setDisabled:function(h,f){var g=null;if(g=this.get(h)){g.setDisabled(f)}return g},add:function(g){var f=this;if(g){f.controls[g.id]=g;f.onAdd.dispatch(g,f)}return g},createControl:function(j){var o,k,g,h=this,m=h.editor,n,f;if(!h.controlFactories){h.controlFactories=[];d(m.plugins,function(i){if(i.createControl){h.controlFactories.push(i)}})}n=h.controlFactories;for(k=0,g=n.length;k1||ae==ax||ae.tagName=="BR"){return ae}}}var ap=Z.selection.getRng();var au=ap.startContainer;var ao=ap.endContainer;if(au!=ao&&ap.endOffset===0){var at=aq(au,ao);var ar=at.nodeType==3?at.length:at.childNodes.length;ap.setEnd(at,ar)}return ap}function ah(ao){var aq=-1;var ap;S(ao.childNodes,function(at,ar){if(at.nodeName==="UL"||at.nodeName==="OL"){aq=ar;ap=at;return false}});return{listIndex:aq,list:ap}}function al(ap,ao){var ar=-1;var aq=-1;S(ap.childNodes,function(au,at){if(au.nodeName==="SPAN"&&c.getAttrib(au,"data-mce-type")=="bookmark"){if(au.id==ao.id+"_start"){ar=at}else{if(au.id==ao.id+"_end"){aq=at}}}});return{startIndex:ar,endIndex:aq}}function am(ap,ar,av){var ao=[],au,aq,at=true;au=ak.inline||ak.block;aq=c.create(au);aa(aq);M.walk(ap,function(aw){var ax;function ay(aA){var aF,aD,aB,aC,aE;aE=at;aF=aA.nodeName.toLowerCase();aD=aA.parentNode.nodeName.toLowerCase();if(aA.nodeType===1&&x(aA)){aE=at;at=x(aA)==="true";aC=true}if(f(aF,"br")){ax=0;if(ak.block){c.remove(aA)}return}if(ak.wrapper&&y(aA,ac,aj)){ax=0;return}if(at&&!aC&&ak.block&&!ak.wrapper&&H(aF)){aA=c.rename(aA,au);aa(aA);ao.push(aA);ax=0;return}if(ak.selector){S(af,function(aG){if("collapsed" in aG&&aG.collapsed!==ag){return}if(c.is(aA,aG.selector)&&!b(aA)){aa(aA,aG);aB=true}});if(!ak.inline||aB){ax=0;return}}function az(aG){return aG.nodeType===3&&aG.nodeValue.length===1&&aG.nodeValue.charCodeAt(0)===65279}if(at&&!aC&&k(au,aF)&&k(aD,au)&&!(!av&&az(aA))&&!b(aA)&&(!ak.inline||!G(aA))){if(!ax){ax=c.clone(aq,W);aA.parentNode.insertBefore(ax,aA);ao.push(ax)}ax.appendChild(aA)}else{ax=0;S(a.grep(aA.childNodes),ay);if(aC){at=aE}ax=0}}S(aw,ay)});if(ak.wrap_links===false){S(ao,function(aw){function ax(aB){var aA,az,ay;if(aB.nodeName==="A"){az=c.clone(aq,W);ao.push(az);ay=a.grep(aB.childNodes);for(aA=0;aA1||!G(ay))&&aw===0){c.remove(ay,1);return}if(ak.inline||ak.wrapper){if(!ak.exact&&aw===1){ay=ax(ay)}S(af,function(aA){S(c.select(aA.inline,ay),function(aC){var aB;if(aA.wrap_links===false){aB=aC.parentNode;do{if(aB.nodeName==="A"){return}aB=aB.parentNode}while(aB)}Y(aA,aj,aC,aA.exact?aC:null)})});if(y(ay.parentNode,ac,aj)){c.remove(ay,1);ay=0;return B}if(ak.merge_with_parents){c.getParent(ay.parentNode,function(aA){if(y(aA,ac,aj)){c.remove(ay,1);ay=0;return B}})}if(ay&&ak.merge_siblings!==false){ay=u(D(ay),ay);ay=u(ay,D(ay,B))}}})}if(ak){if(ae){if(ae.nodeType){ab=c.createRng();ab.setStartBefore(ae);ab.setEndAfter(ae);am(p(ab,af),null,true)}else{am(ae,null,true)}}else{if(!ag||!ak.inline||c.select("td.mceSelected,th.mceSelected").length){var an=Z.selection.getNode();if(!m&&af[0].defaultBlock&&!c.getParent(an,c.isBlock)){X(af[0].defaultBlock)}Z.selection.setRng(ad());ai=r.getBookmark();am(p(r.getRng(B),af),ai);if(ak.styles&&(ak.styles.color||ak.styles.textDecoration)){a.walk(an,K,"childNodes");K(an)}r.moveToBookmark(ai);Q(r.getRng(B));Z.nodeChanged()}else{T("apply",ac,aj)}}}}function A(ac,aj,ae){var af=U(ac),am=af[0],ai,ab,ak=true;function ad(ar){var aq,ap,ao,au,at;if(ar.nodeType===3){return}if(ar.nodeType===1&&x(ar)){au=ak;ak=x(ar)==="true";at=true}aq=a.grep(ar.childNodes);if(ak&&!at){for(ap=0,ao=af.length;ap=0;ab--){aa=ag[ab].selector;if(!aa){return B}for(af=ac.length-1;af>=0;af--){if(c.is(ac[af],aa)){return B}}}}return W}function I(aa,ad,ab){var ac;if(!O){O={};ac={};Z.onNodeChange.addToTop(function(af,ae,ah){var ag=n(ah),ai={};S(O,function(aj,ak){S(ag,function(al){if(y(al,ak,{},aj.similar)){if(!ac[ak]){S(aj,function(am){am(true,{node:al,format:ak,parents:ag})});ac[ak]=aj}ai[ak]=aj;return false}})});S(ac,function(aj,ak){if(!ai[ak]){delete ac[ak];S(aj,function(al){al(false,{node:ah,format:ak,parents:ag})})}})})}S(aa.split(","),function(ae){if(!O[ae]){O[ae]=[];O[ae].similar=ab}O[ae].push(ad)});return this}a.extend(this,{get:U,register:l,apply:X,remove:A,toggle:E,match:j,matchAll:v,matchNode:y,canApply:z,formatChanged:I});i();V();function g(aa,ab){if(f(aa,ab.inline)){return B}if(f(aa,ab.block)){return B}if(ab.selector){return c.is(aa,ab.selector)}}function f(ab,aa){ab=ab||"";aa=aa||"";ab=""+(ab.nodeName||ab);aa=""+(aa.nodeName||aa);return ab.toLowerCase()==aa.toLowerCase()}function N(ab,aa){var ac=c.getStyle(ab,aa);if(aa=="color"||aa=="backgroundColor"){ac=c.toHex(ac)}if(aa=="fontWeight"&&ac==700){ac="bold"}return""+ac}function q(aa,ab){if(typeof(aa)!="string"){aa=aa(ab)}else{if(ab){aa=aa.replace(/%(\w+)/g,function(ad,ac){return ab[ac]||ad})}}return aa}function e(aa){return aa&&aa.nodeType===3&&/^([\t \r\n]+|)$/.test(aa.nodeValue)}function R(ac,ab,aa){var ad=c.create(ab,aa);ac.parentNode.insertBefore(ad,ac);ad.appendChild(ac);return ad}function p(aa,al,ad){var am,ag,ak,ac=aa.startContainer,ah=aa.startOffset,ap=aa.endContainer,aj=aa.endOffset;function an(ax){var ar,av,au,at,aq;ar=av=ax?ac:ap;at=ax?"previousSibling":"nextSibling";aq=c.getRoot();function aw(ay){return ay.nodeName=="BR"&&ay.getAttribute("data-mce-bogus")&&!ay.nextSibling}if(ar.nodeType==3&&!e(ar)){if(ax?ah>0:ajam?am:ah];if(ac&&ac.nodeType==3){ah=0}}if(ap.nodeType==1&&ap.hasChildNodes()){am=ap.childNodes.length-1;ap=ap.childNodes[aj>am?am:aj-1];if(ap&&ap.nodeType==3){aj=ap.nodeValue.length}}function ao(ar){var aq=ar;while(aq){if(aq.nodeType===1&&x(aq)){return x(aq)==="false"?aq:ar}aq=aq.parentNode}return ar}function ai(ar,aw,ay){var av,at,ax,aq;function au(aA,aC){var aD,az,aB=aA.nodeValue;if(typeof(aC)=="undefined"){aC=ay?aB.length:0}if(ay){aD=aB.lastIndexOf(" ",aC);az=aB.lastIndexOf("\u00a0",aC);aD=aD>az?aD:az;if(aD!==-1&&!ad){aD++}}else{aD=aB.indexOf(" ",aC);az=aB.indexOf("\u00a0",aC);aD=aD!==-1&&(az===-1||aD0&&ag.node.nodeType===3&&ag.node.nodeValue.charAt(ag.offset-1)===" "){if(ag.offset>1){ap=ag.node;ap.splitText(ag.offset-1)}}}}if(al[0].inline||al[0].block_expand){if(!al[0].inline||(ac.nodeType!=3||ah===0)){ac=an(true)}if(!al[0].inline||(ap.nodeType!=3||aj===ap.nodeValue.length)){ap=an()}}if(al[0].selector&&al[0].expand!==W&&!al[0].inline){ac=ae(ac,"previousSibling");ap=ae(ap,"nextSibling")}if(al[0].block||al[0].selector){ac=ab(ac,"previousSibling");ap=ab(ap,"nextSibling");if(al[0].block){if(!G(ac)){ac=an(true)}if(!G(ap)){ap=an()}}}if(ac.nodeType==1){ah=s(ac);ac=ac.parentNode}if(ap.nodeType==1){aj=s(ap)+1;ap=ap.parentNode}return{startContainer:ac,startOffset:ah,endContainer:ap,endOffset:aj}}function Y(ag,af,ad,aa){var ac,ab,ae;if(!g(ad,ag)){return W}if(ag.remove!="all"){S(ag.styles,function(ai,ah){ai=q(ai,af);if(typeof(ah)==="number"){ah=ai;aa=0}if(!aa||f(N(aa,ah),ai)){c.setStyle(ad,ah,"")}ae=1});if(ae&&c.getAttrib(ad,"style")===""){ad.removeAttribute("style");ad.removeAttribute("data-mce-style")}S(ag.attributes,function(aj,ah){var ai;aj=q(aj,af);if(typeof(ah)==="number"){ah=aj;aa=0}if(!aa||f(c.getAttrib(aa,ah),aj)){if(ah=="class"){aj=c.getAttrib(ad,ah);if(aj){ai="";S(aj.split(/\s+/),function(ak){if(/mce\w+/.test(ak)){ai+=(ai?" ":"")+ak}});if(ai){c.setAttrib(ad,ah,ai);return}}}if(ah=="class"){ad.removeAttribute("className")}if(d.test(ah)){ad.removeAttribute("data-mce-"+ah)}ad.removeAttribute(ah)}});S(ag.classes,function(ah){ah=q(ah,af);if(!aa||c.hasClass(aa,ah)){c.removeClass(ad,ah)}});ab=c.getAttribs(ad);for(ac=0;acac?ac:ad]}if(aa.nodeType===3&&ae&&ad>=aa.nodeValue.length){aa=new t(aa,Z.getBody()).next()||aa}if(aa.nodeType===3&&!ae&&ad===0){aa=new t(aa,Z.getBody()).prev()||aa}return aa}function T(ak,aa,ai){var am="_mce_caret",ab=Z.settings.caret_debug;function ac(aq){var ap=c.create("span",{id:am,"data-mce-bogus":true,style:ab?"color:red":""});if(aq){ap.appendChild(Z.getDoc().createTextNode(F))}return ap}function aj(aq,ap){while(aq){if((aq.nodeType===3&&aq.nodeValue!==F)||aq.childNodes.length>1){return false}if(ap&&aq.nodeType===1){ap.push(aq)}aq=aq.firstChild}return true}function af(ap){while(ap){if(ap.id===am){return ap}ap=ap.parentNode}}function ae(ap){var aq;if(ap){aq=new t(ap,ap);for(ap=aq.current();ap;ap=aq.next()){if(ap.nodeType===3){return ap}}}}function ad(ar,aq){var at,ap;if(!ar){ar=af(r.getStart());if(!ar){while(ar=c.get(am)){ad(ar,false)}}}else{ap=r.getRng(true);if(aj(ar)){if(aq!==false){ap.setStartBefore(ar);ap.setEndBefore(ar)}c.remove(ar)}else{at=ae(ar);if(at.nodeValue.charAt(0)===F){at=at.deleteData(0,1)}c.remove(ar,1)}r.setRng(ap)}}function al(aq){var ap=aq.nodeName.toLowerCase();switch(ap){case"html","#document":return false;case"body":return true;default:return al(aq.parentNode)}}function ag(ap){return al(ap.startContainer)||al(ap.endContainer)}function ah(){var ar,ap,aw,av,at,aq,au;ar=r.getRng(true);av=ar.startOffset;aq=ar.startContainer;au=aq.nodeValue;ap=af(r.getStart());if(ap){aw=ae(ap)}if(au&&av>0&&av=0;av--){ar.appendChild(c.clone(az[av],false));ar=ar.firstChild}ar.appendChild(c.doc.createTextNode(F));ar=ar.firstChild;var at=c.getParent(aA,H);if(at&&c.isEmpty(at)){aA.parentNode.replaceChild(ay,aA)}else{c.insertAfter(ay,aA)}r.setCursorLocation(ar,1);if(c.isEmpty(aA)){c.remove(aA)}}}function ao(){var ap;ap=af(r.getStart());if(ap&&!c.isEmpty(ap)){a.walk(ap,function(aq){if(aq.nodeType==1&&aq.id!==am&&!c.isEmpty(aq)){c.setAttrib(aq,"data-mce-bogus",null)}},"childNodes")}}if(!Z._hasCaretEvents){Z.onBeforeGetContent.addToTop(function(){var ap=[],aq;if(aj(af(r.getStart()),ap)){aq=ap.length;while(aq--){c.setAttrib(ap[aq],"data-mce-bogus","1")}}});a.each("onMouseUp onKeyUp".split(" "),function(ap){Z[ap].addToTop(function(){ad();ao()})});Z.onKeyDown.addToTop(function(ap,ar){var aq=ar.keyCode;if(aq==8||aq==37||aq==39){ad(af(r.getStart()))}ao()});r.onSetContent.add(ao);Z._hasCaretEvents=true}if(ak=="apply"){ah()}else{an()}}function Q(ab){var aa=ab.startContainer,ah=ab.startOffset,ad,ag,af,ac,ae;if(aa.nodeType==3&&ah>=aa.nodeValue.length){ah=s(aa);aa=aa.parentNode;ad=true}if(aa.nodeType==1){ac=aa.childNodes;aa=ac[Math.min(ah,ac.length-1)];ag=new t(aa,c.getParent(aa,c.isBlock));if(ah>ac.length-1||ad){ag.next()}for(af=ag.current();af;af=ag.next()){if(af.nodeType==3&&!e(af)){ae=c.create("a",null,F);af.parentNode.insertBefore(ae,af);ab.setStart(af,0);r.setRng(ab);c.remove(ae);return}}}}}})(tinymce);tinymce.onAddEditor.add(function(e,a){var d,h,g,c=a.settings;function b(j,i){e.each(i,function(l,k){if(l){g.setStyle(j,k,l)}});g.rename(j,"span")}function f(i,j){g=i.dom;if(c.convert_fonts_to_spans){e.each(g.select("font,u,strike",j.node),function(k){d[k.nodeName.toLowerCase()](a.dom,k)})}}if(c.inline_styles){h=e.explode(c.font_size_legacy_values);d={font:function(j,i){b(i,{backgroundColor:i.style.backgroundColor,color:i.color,fontFamily:i.face,fontSize:h[parseInt(i.size,10)-1]})},u:function(j,i){b(i,{textDecoration:"underline"})},strike:function(j,i){b(i,{textDecoration:"line-through"})}};a.onPreProcess.add(f);a.onSetContent.add(f);a.onInit.add(function(){a.selection.onSetContent.add(f)})}});(function(b){var a=b.dom.TreeWalker;b.EnterKey=function(f){var i=f.dom,e=f.selection,d=f.settings,h=f.undoManager,c=f.schema.getNonEmptyElements();function g(B){var v=e.getRng(true),G,j,A,u,p,M,C,o,k,n,t,J,x,D;function E(N){return N&&i.isBlock(N)&&!/^(TD|TH|CAPTION|FORM)$/.test(N.nodeName)&&!/^(fixed|absolute)/i.test(N.style.position)&&i.getContentEditable(N)!=="true"}function F(O){var N;if(b.isIE&&!b.isIE11&&i.isBlock(O)){N=e.getRng();O.appendChild(i.create("span",null,"\u00a0"));e.select(O);O.lastChild.outerHTML="";e.setRng(N)}}function z(P){var O=P,Q=[],N;while(O=O.firstChild){if(i.isBlock(O)){return}if(O.nodeType==1&&!c[O.nodeName.toLowerCase()]){Q.push(O)}}N=Q.length;while(N--){O=Q[N];if(!O.hasChildNodes()||(O.firstChild==O.lastChild&&O.firstChild.nodeValue==="")){i.remove(O)}else{if(O.nodeName=="A"&&(O.innerText||O.textContent)===" "){i.remove(O)}}}}function m(O){var T,R,N,U,S,Q=O,P;N=i.createRng();if(O.hasChildNodes()){T=new a(O,O);while(R=T.current()){if(R.nodeType==3){N.setStart(R,0);N.setEnd(R,0);break}if(c[R.nodeName.toLowerCase()]){N.setStartBefore(R);N.setEndBefore(R);break}Q=R;R=T.next()}if(!R){N.setStart(Q,0);N.setEnd(Q,0)}}else{if(O.nodeName=="BR"){if(O.nextSibling&&i.isBlock(O.nextSibling)){if(!M||M<9){P=i.create("br");O.parentNode.insertBefore(P,O)}N.setStartBefore(O);N.setEndBefore(O)}else{N.setStartAfter(O);N.setEndAfter(O)}}else{N.setStart(O,0);N.setEnd(O,0)}}e.setRng(N);i.remove(P);S=i.getViewPort(f.getWin());U=i.getPos(O).y;if(US.y+S.h){f.getWin().scrollTo(0,U'}return R}function q(Q){var P,O,N;if(A.nodeType==3&&(Q?u>0:u0){return true}}}function L(){var P,O,N;if(A&&A.nodeType==3&&u>=A.nodeValue.length){if((!b.isIE||b.isIE11)&&!y()){P=i.create("br");v.insertNode(P);v.setStartAfter(P);v.setEndAfter(P);O=true}}P=i.create("br");v.insertNode(P);if((b.isIE&&!b.isIE11)&&t=="PRE"&&(!M||M<8)){P.parentNode.insertBefore(i.doc.createTextNode("\r"),P)}N=i.create("span",{}," ");P.parentNode.insertBefore(N,P);e.scrollIntoView(N);i.remove(N);if(!O){v.setStartAfter(P);v.setEndAfter(P)}else{v.setStartBefore(P);v.setEndBefore(P)}e.setRng(v);h.add()}function s(N){do{if(N.nodeType===3){N.nodeValue=N.nodeValue.replace(/^[\r\n]+/,"")}N=N.firstChild}while(N)}function K(P){var N=i.getRoot(),O,Q;O=P;while(O!==N&&i.getContentEditable(O)!=="false"){if(i.getContentEditable(O)==="true"){Q=O}O=O.parentNode}return O!==N?Q:N}function I(O){var N;if(!b.isIE||b.isIE11){O.normalize();N=O.lastChild;if(!N||(/^(left|right)$/gi.test(i.getStyle(N,"float",true)))){i.add(O,"br")}}}if(!v.collapsed){f.execCommand("Delete");return}if(B.isDefaultPrevented()){return}A=v.startContainer;u=v.startOffset;x=(d.force_p_newlines?"p":"")||d.forced_root_block;x=x?x.toUpperCase():"";M=i.doc.documentMode;C=B.shiftKey;if(A.nodeType==1&&A.hasChildNodes()){D=u>A.childNodes.length-1;A=A.childNodes[Math.min(u,A.childNodes.length-1)]||A;if(D&&A.nodeType==3){u=A.nodeValue.length}else{u=0}}j=K(A);if(!j){return}h.beforeChange();if(!i.isBlock(j)&&j!=i.getRoot()){if(!x||C){L()}return}if((x&&!C)||(!x&&C)){A=l(A,u)}p=i.getParent(A,i.isBlock);n=p?i.getParent(p.parentNode,i.isBlock):null;t=p?p.nodeName.toUpperCase():"";J=n?n.nodeName.toUpperCase():"";if(J=="LI"&&!B.ctrlKey){p=n;t=J}if(t=="LI"){if(!x&&C){L();return}if(i.isEmpty(p)){if(/^(UL|OL|LI)$/.test(n.parentNode.nodeName)){return false}H();return}}if(t=="PRE"&&d.br_in_pre!==false){if(!C){L();return}}else{if((!x&&!C&&t!="LI")||(x&&C)){L();return}}x=x||"P";if(q()){if(/^(H[1-6]|PRE)$/.test(t)&&J!="HGROUP"){o=r(x)}else{o=r()}if(d.end_container_on_empty_block&&E(n)&&i.isEmpty(p)){o=i.split(n,p)}else{i.insertAfter(o,p)}m(o)}else{if(q(true)){o=p.parentNode.insertBefore(r(),p);F(o)}else{G=v.cloneRange();G.setEndAfter(p);k=G.extractContents();s(k);o=k.firstChild;i.insertAfter(k,p);z(o);I(p);m(o)}}i.setAttrib(o,"id","");h.add()}f.onKeyDown.add(function(k,j){if(j.keyCode==13){if(g(j)!==false){j.preventDefault()}}})}})(tinymce); +/** +* Name: editor_plugin_src.js (for pmGrids tinyMCE plugin) +**/ + +(function(){ + var strPluginURL; + tinymce.create('tinymce.plugins.pmGridsPlugin', { + init: function(ed, url) + { + strPluginURL = url; // store the URL for future use.. + ed.addCommand('mcepmGrids', function() { + pmGrids(); + }); + ed.addButton('pmGrids', { + title: 'pmGrids', + label : ' @#', + cmd: 'mcepmGrids', + image: url + '/img/grids.png' + }); + }, + createControl: function(n, cm) { + return null; + }, + getPluginURL: function() { + return strPluginURL; + } + }); + tinymce.PluginManager.add('pmGrids', tinymce.plugins.pmGridsPlugin); +})(); + +/** + * @function pmGrids + * @description The function intializes the plugin and also creates the popup + * window + * @param field_name deprecated + * @param win deprecated + */ +function pmGrids(field_name, win) { + //tinyMCE.activeEditor.anyVariable='path/to/ProcessMaker' + var strPluginPath = tinyMCE.activeEditor.plugins.pmGrids.getPluginURL(); // get the path to the uploader plugin + var strScriptURL = strPluginPath + "/pmGrids.html"; // loading the form + + tinyMCE.activeEditor.windowManager.open({ // open the plugin popup + file : strScriptURL, + title : 'ProcessMaker Grid Wizard', + width : '600px', + height : '230px', + resizable : "yes", + scrollbars : "no", + overflow : false, + inline : 1, // This parameter only has an effect if you use the inlinepopups plugin! + close_previous : "no" + }, { + window : win, + input : field_name + }); + + return false; +} + +/** + * @function closePluginPopup + * @description closes the plugin popup + */ +function closePluginPopup(){ + tinyMCEPopup.close(); // close popup window +} + + +/** + * @function updateEditorContent + * @description insert the editor content with a html code string + * @params serializedHTML String html code + */ +function updateEditorContent(serializedHTML){ + tinyMCE.activeEditor.execCommand('mceInsertRawHTML', false, serializedHTML); + closePluginPopup(); +} + + +/** +* Name: editor_plugin_src.js (for pmSimpleUploader tinyMCE plugin) +**/ + +(function(){ + var strPluginURL; + tinymce.create('tinymce.plugins.pmSimpleUploaderPlugin', { + init: function(ed, url) + { + strPluginURL = url; // store the URL for future use.. + ed.addCommand('mcepmSimpleUploader', function() { + pmSimpleUploader(); + }); + ed.addButton('pmSimpleUploader', { + title: 'pmSimpleUploader', + label : 'Upload File', + cmd: 'mcepmSimpleUploader', + image: url + '/img/pmSimpleUploader.png' + }); + }, + createControl: function(n, cm) { + return null; + }, + getPluginURL: function() { + return strPluginURL; + } + }); + tinymce.PluginManager.add('pmSimpleUploader', tinymce.plugins.pmSimpleUploaderPlugin); +})(); + +/** + * this function can get called from the plugin inint (above) or from the callback on advlink/advimg plugins.. + * in the latter case, win and type will be set.. In the rist case, we will just update the main editor window + * with the path of the uploaded file + */ +function pmSimpleUploader(field_name, url, type, win) { + var strPluginPath = tinyMCE.activeEditor.plugins.pmSimpleUploader.getPluginURL(); // get the path to the uploader plugin + var strUploaderURL = strPluginPath + "/uploader.php"; // generate the path to the uploader script + var strUploadPath = tinyMCE.activeEditor.getParam('plugin_pmSimpleUploader_upload_path'); // get the relative upload path + var strSubstitutePath = tinyMCE.activeEditor.getParam('plugin_pmSimpleUploader_upload_substitute_path'); // get the path we'll substitute for the for the upload path (i.e. fully qualified) + + if (strUploaderURL.indexOf("?") < 0){ // if we were called without any GET params + strUploaderURL = strUploaderURL + "?type=" + type + "&d=" + strUploadPath + "&subs=" + strSubstitutePath; // add our own params + } else { + strUploaderURL = strUploaderURL + "&type=" + type + "&d=" + strUploadPath + "&subs=" + strSubstitutePath; + } + tinyMCE.activeEditor.windowManager.open({ // open the plugin popup + file : strUploaderURL, + title : 'Upload from file', + width : 500, + height : 100, + resizable : "yes", + inline : 1, // This parameter only has an effect if you use the inlinepopups plugin! + close_previous : "no" + }, { + window : win, + input : field_name + }); + + return false; +} + +/** + * This function will get called when the uploader is done uploading the file and ready to update + * calling dialog and close the upload popup + * strReturnURL should be the string with the path to the uploaded file + */ + +function closePluginPopup(){ + tinyMCEPopup.close(); // close popup window +} + +/** + * This function update the content editor with the content template file + */ + +function updateEditorContent(serializedHTML){ + tinyMCE.activeEditor.execCommand('mceSetContent', false, serializedHTML); +} +/** +* Name: editor_plugin_src.js (for pmVariablePicker tinyMCE plugin) +**/ + +(function(){ + // set the base url setting + tinyMCE.baseURL = "/js/tinymce/jscripts/tiny_mce"; + var strPluginURL; + // the plugin init settings + tinymce.create('tinymce.plugins.pmVariablePickerPlugin', { + init: function(ed, url) + { + strPluginURL = url; // store the URL for future use.. + ed.addCommand('mcepmVariablePicker', function() { + pmVariablePicker(); + }); + ed.addButton('pmVariablePicker', { + title: 'pmVariablePicker', + label : ' @#', + cmd: 'mcepmVariablePicker', + image: url + '/img/picker.png' + }); + }, + createControl: function(n, cm) { + return null; + }, + getPluginURL: function() { + return strPluginURL; + } + }); + tinymce.PluginManager.add('pmVariablePicker', tinymce.plugins.pmVariablePickerPlugin); +})(); + +// this function can get called from the plugin inint (above) or from the callback on advlink/advimg plugins.. +// in the latter case, win and type will be set.. +/** + * @function pmVariablePicker + * @description Opens the plugin popup, loading the form inside it. + * @param field_name deprecated + * @param type deprecated + * @param win deprecated + * + */ +function pmVariablePicker(field_name, type, win) { + + var uloc=String(location); + var new_text = uloc.split('/'); + var loc='/'+new_text[3]+'/'+new_text[4]+'/'+new_text[5]+'/controls/varsAjax?displayOption=tinyMCE&sSymbol=@@&&sProcess='+tinyMCE.activeEditor.processID; + var strPluginPath = tinyMCE.activeEditor.plugins.pmVariablePicker.getPluginURL(); // get the path to the uploader plugin + var strUploaderURL = strPluginPath + "/uploader.php"; // generate the path to the uploader script + var strUploadPath = tinyMCE.activeEditor.getParam('plugin_pmVariablePicker_upload_path'); // get the relative upload path + var strSubstitutePath = tinyMCE.activeEditor.getParam('plugin_pmVariablePicker_upload_substitute_path'); // get the path we'll substitute for the for the upload path (i.e. fully qualified) + + if (strUploaderURL.indexOf("?") < 0){ // if we were called without any GET params + strUploaderURL = strUploaderURL + "?type=" + type + "&d=" + strUploadPath + "&subs=" + strSubstitutePath; // add our own params + } else { + strUploaderURL = strUploaderURL + "&type=" + type + "&d=" + strUploadPath + "&subs=" + strSubstitutePath; + } + //tinyMCE.activeEditor.anyVariable='path/to/ProcessMaker' + tinyMCE.activeEditor.windowManager.open({ // open the plugin popup + file : loc, + title : 'Upload Variable', + width : '600px', + height : '330px', + resizable : "yes", + scrollbars : "no", + overflow : false, + inline : 1, // This parameter only has an effect if you use the inlinepopups plugin! + close_previous : "no" + }, { + window : win, + input : field_name + }); + + return false; +} + +/** + * @function closePluginPopup + * @description closes the tinyMCE popup window + */ +function closePluginPopup(){ + tinyMCEPopup.close(); // close popup window +} + +/** + * @function updateEditorContent + * @description insert the editor content with a html code string + * @params serializedHTML String html code + */ +function updateEditorContent(serializedHTML){ + tinyMCE.activeEditor.execCommand('mceInsertContent', false, serializedHTML); +} + +/** + * @function insertFormVar + * @description alternate version of updateEditorContent this function is + * compatible with the variable picker calls, also closes the popup + * window + * @param fieldName String deprecated + * @param serializedHTML String the html code to be added. + */ +function insertFormVar(fieldName,serializedHTML){ + tinyMCEPopup.execCommand('mceInsertContent', false, serializedHTML); + closePluginPopup(); +} + +(function(){tinymce.create("tinymce.plugins.VisualChars",{init:function(a,b){var c=this;c.editor=a;a.addCommand("mceVisualChars",c._toggleVisualChars,c);a.addButton("visualchars",{title:"visualchars.desc",cmd:"mceVisualChars"});a.onBeforeGetContent.add(function(d,e){if(c.state&&e.format!="raw"&&!e.draft){c.state=true;c._toggleVisualChars(false)}})},getInfo:function(){return{longname:"Visual characters",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/visualchars",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_toggleVisualChars:function(m){var p=this,k=p.editor,a,g,j,n=k.getDoc(),o=k.getBody(),l,q=k.selection,e,c,f;p.state=!p.state;k.controlManager.setActive("visualchars",p.state);if(m){f=q.getBookmark()}if(p.state){a=[];tinymce.walk(o,function(b){if(b.nodeType==3&&b.nodeValue&&b.nodeValue.indexOf("\u00a0")!=-1){a.push(b)}},"childNodes");for(g=0;g$1');c=k.dom.create("div",null,l);while(node=c.lastChild){k.dom.insertAfter(node,a[g])}k.dom.remove(a[g])}}else{a=k.dom.select("span.mceItemNbsp",o);for(g=a.length-1;g>=0;g--){k.dom.remove(a[g],1)}}q.moveToBookmark(f)}});tinymce.PluginManager.add("visualchars",tinymce.plugins.VisualChars)})(); +(function(){tinymce.create("tinymce.plugins.XHTMLXtrasPlugin",{init:function(a,b){a.addCommand("mceCite",function(){a.windowManager.open({file:b+"/cite.htm",width:350+parseInt(a.getLang("xhtmlxtras.cite_delta_width",0)),height:250+parseInt(a.getLang("xhtmlxtras.cite_delta_height",0)),inline:1},{plugin_url:b})});a.addCommand("mceAcronym",function(){a.windowManager.open({file:b+"/acronym.htm",width:350+parseInt(a.getLang("xhtmlxtras.acronym_delta_width",0)),height:250+parseInt(a.getLang("xhtmlxtras.acronym_delta_height",0)),inline:1},{plugin_url:b})});a.addCommand("mceAbbr",function(){a.windowManager.open({file:b+"/abbr.htm",width:350+parseInt(a.getLang("xhtmlxtras.abbr_delta_width",0)),height:250+parseInt(a.getLang("xhtmlxtras.abbr_delta_height",0)),inline:1},{plugin_url:b})});a.addCommand("mceDel",function(){a.windowManager.open({file:b+"/del.htm",width:340+parseInt(a.getLang("xhtmlxtras.del_delta_width",0)),height:310+parseInt(a.getLang("xhtmlxtras.del_delta_height",0)),inline:1},{plugin_url:b})});a.addCommand("mceIns",function(){a.windowManager.open({file:b+"/ins.htm",width:340+parseInt(a.getLang("xhtmlxtras.ins_delta_width",0)),height:310+parseInt(a.getLang("xhtmlxtras.ins_delta_height",0)),inline:1},{plugin_url:b})});a.addCommand("mceAttributes",function(){a.windowManager.open({file:b+"/attributes.htm",width:380+parseInt(a.getLang("xhtmlxtras.attr_delta_width",0)),height:370+parseInt(a.getLang("xhtmlxtras.attr_delta_height",0)),inline:1},{plugin_url:b})});a.addButton("cite",{title:"xhtmlxtras.cite_desc",cmd:"mceCite"});a.addButton("acronym",{title:"xhtmlxtras.acronym_desc",cmd:"mceAcronym"});a.addButton("abbr",{title:"xhtmlxtras.abbr_desc",cmd:"mceAbbr"});a.addButton("del",{title:"xhtmlxtras.del_desc",cmd:"mceDel"});a.addButton("ins",{title:"xhtmlxtras.ins_desc",cmd:"mceIns"});a.addButton("attribs",{title:"xhtmlxtras.attribs_desc",cmd:"mceAttributes"});a.onNodeChange.add(function(d,c,f,e){f=d.dom.getParent(f,"CITE,ACRONYM,ABBR,DEL,INS");c.setDisabled("cite",e);c.setDisabled("acronym",e);c.setDisabled("abbr",e);c.setDisabled("del",e);c.setDisabled("ins",e);c.setDisabled("attribs",f&&f.nodeName=="BODY");c.setActive("cite",0);c.setActive("acronym",0);c.setActive("abbr",0);c.setActive("del",0);c.setActive("ins",0);if(f){do{c.setDisabled(f.nodeName.toLowerCase(),0);c.setActive(f.nodeName.toLowerCase(),1)}while(f=f.parentNode)}});a.onPreInit.add(function(){a.dom.create("abbr")})},getInfo:function(){return{longname:"XHTML Xtras Plugin",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/xhtmlxtras",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("xhtmlxtras",tinymce.plugins.XHTMLXtrasPlugin)})(); +(function(){tinymce.create("tinymce.plugins.WordCount",{block:0,id:null,countre:null,cleanre:null,init:function(c,d){var e=this,f=0,g=tinymce.VK;e.countre=c.getParam("wordcount_countregex",/[\w\u2019\u00co-\u00ff^\uc397^u00f7\'-]+/g);e.cleanre=c.getParam("wordcount_cleanregex",/[0-9.(),;:!?%#$?\'\"_+=\\\/-]*/g);e.update_rate=c.getParam("wordcount_update_rate",2000);e.update_on_delete=c.getParam("wordcount_update_on_delete",false);e.id=c.id+"-word-count";c.onPostRender.add(function(i,h){var j,k;k=i.getParam("wordcount_target_id");if(!k){j=tinymce.DOM.get(i.id+"_path_row");if(j){tinymce.DOM.add(j.parentNode,"div",{style:"float: right"},i.getLang("wordcount.words","Words: ")+'0')}}else{tinymce.DOM.add(k,"span",{},'0')}});c.onInit.add(function(h){h.selection.onSetContent.add(function(){e._count(h)});e._count(h)});c.onSetContent.add(function(h){e._count(h)});function b(h){return h!==f&&(h===g.ENTER||f===g.SPACEBAR||a(f))}function a(h){return h===g.DELETE||h===g.BACKSPACE}c.onKeyUp.add(function(h,i){if(b(i.keyCode)||e.update_on_delete&&a(i.keyCode)){e._count(h)}f=i.keyCode})},_getCount:function(c){var a=0;var b=c.getContent({format:"raw"});if(b){b=b.replace(/\.\.\./g," ");b=b.replace(/<.[^<>]*?>/g," ").replace(/ | /gi," ");b=b.replace(/(\w+)(&.+?;)+(\w+)/,"$1$3").replace(/&.+?;/g," ");b=b.replace(this.cleanre,"");var d=b.match(this.countre);if(d){a=d.length}}return a},_count:function(a){var b=this;if(b.block){return}b.block=1;setTimeout(function(){if(!a.destroyed){var c=b._getCount(a);tinymce.DOM.setHTML(b.id,c.toString());setTimeout(function(){b.block=0},b.update_rate)}},1)},getInfo:function(){return{longname:"Word Count plugin",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/wordcount",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("wordcount",tinymce.plugins.WordCount)})(); +(function(d){var e=d.each;function c(g,h){var i=h.ownerDocument,f=i.createRange(),j;f.setStartBefore(h);f.setEnd(g.endContainer,g.endOffset);j=i.createElement("body");j.appendChild(f.cloneContents());return j.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi,"-").replace(/<[^>]+>/g,"").length===0}function a(g,f){return parseInt(g.getAttribute(f)||1,10)}function b(E,D,H){var g,I,A,n;function x(K,J){K=K.cloneNode(J);K.removeAttribute("id");return K}function s(){var J=0;g=[];e(["thead","tbody","tfoot"],function(K){var L=D.select("> "+K+" tr",E);e(L,function(M,N){N+=J;e(D.select("> td, > th",M),function(T,O){var P,Q,R,S;if(g[N]){while(g[N][O]){O++}}R=a(T,"rowspan");S=a(T,"colspan");for(Q=N;Q'}return false}},"childNodes");J=x(J,false);r(J,"rowSpan",1);r(J,"colSpan",1);if(K){J.appendChild(K)}else{if(!d.isIE||d.isIE11){J.innerHTML='
'}}return J}function p(){var J=D.createRng(),K;e(D.select("tr",E),function(L){if(L.cells.length===0){D.remove(L)}});if(D.select("tr",E).length===0){J.setStartAfter(E);J.setEndAfter(E);H.setRng(J);D.remove(E);return}e(D.select("thead,tbody,tfoot",E),function(L){if(L.rows.length===0){D.remove(L)}});s();K=g[Math.min(g.length-1,I.y)];if(K){H.select(K[Math.min(K.length-1,I.x)].elm,true);H.collapse(true)}}function t(P,N,R,O){var M,K,J,L,Q;M=g[N][P].elm.parentNode;for(J=1;J<=R;J++){M=D.getNext(M,"tr");if(M){for(K=P;K>=0;K--){Q=g[N+J][K].elm;if(Q.parentNode==M){for(L=1;L<=O;L++){D.insertAfter(f(Q),Q)}break}}if(K==-1){for(L=1;L<=O;L++){M.insertBefore(f(M.cells[0]),M.cells[0])}}}}}function z(){e(g,function(J,K){e(J,function(M,L){var P,O,N;if(i(M)){M=M.elm;P=a(M,"colspan");O=a(M,"rowspan");if(P>1||O>1){r(M,"rowSpan",1);r(M,"colSpan",1);for(N=0;N1){r(P,"rowSpan",L+1);continue}}else{if(J>0&&g[J-1][O]){S=g[J-1][O].elm;L=a(S,"rowSpan");if(L>1){r(S,"rowSpan",L+1);continue}}}K=f(P);r(K,"colSpan",P.colSpan);R.appendChild(K);M=P}}if(R.hasChildNodes()){if(!N){D.insertAfter(R,Q)}else{Q.parentNode.insertBefore(R,Q)}}}function h(K){var L,J;e(g,function(M){e(M,function(O,N){if(i(O)){L=N;if(K){return false}}});if(K){return !L}});e(g,function(P,Q){var M,N,O;if(!P[L]){return}M=P[L].elm;if(M!=J){O=a(M,"colspan");N=a(M,"rowspan");if(O==1){if(!K){D.insertAfter(f(M),M);t(L,Q,N-1,O)}else{M.parentNode.insertBefore(f(M),M);t(L,Q,N-1,O)}}else{r(M,"colSpan",M.colSpan+1)}J=M}})}function m(){var J=[];e(g,function(K){e(K,function(M,L){if(i(M)&&d.inArray(J,L)===-1){e(g,function(P){var N=P[L].elm,O;O=a(N,"colSpan");if(O>1){r(N,"colSpan",O-1)}else{D.remove(N)}});J.push(L)}})});p()}function l(){var K;function J(M){var N,L;e(M.cells,function(O){var P=a(O,"rowSpan");if(P>1){r(O,"rowSpan",P-1);N=C(O);t(N.x,N.y,1,1)}});N=C(M.cells[0]);e(g[N.y],function(O){var P;O=O.elm;if(O!=L){P=a(O,"rowSpan");if(P<=1){D.remove(O)}else{r(O,"rowSpan",P-1)}L=O}})}K=j();e(K.reverse(),function(L){J(L)});p()}function B(){var J=j();D.remove(J);p();return J}function G(){var J=j();e(J,function(L,K){J[K]=x(L,true)});return J}function y(L,K){if(!L){return}var M=j(),J=M[K?0:M.length-1],N=J.cells.length;e(g,function(P){var O;N=0;e(P,function(Q){if(Q.real){N+=Q.colspan}if(Q.elm.parentNode==J){O=1}});if(O){return false}});if(!K){L.reverse()}e(L,function(R){var Q=R.cells.length,O,P;for(P=0;PK){K=N}if(M>J){J=M}if(O.real){Q=O.colspan-1;P=O.rowspan-1;if(Q){if(N+Q>K){K=N+Q}}if(P){if(M+P>J){J=M+P}}}}})});return{x:K,y:J}}function u(R){var M,L,T,S,K,J,N,O,P,Q;A=C(R);if(I&&A){M=Math.min(I.x,A.x);L=Math.min(I.y,A.y);T=Math.max(I.x,A.x);S=Math.max(I.y,A.y);K=T;J=S;for(P=L;P<=J;P++){R=g[P][M];if(!R.real){if(M-(R.colspan-1)K){K=Q+N}}if(O){if(P+O>J){J=P+O}}}}}D.removeClass(D.select("td.mceSelected,th.mceSelected"),"mceSelected");for(P=L;P<=J;P++){for(Q=M;Q<=K;Q++){if(g[P][Q]){D.addClass(g[P][Q].elm,"mceSelected")}}}}}s();n=D.getParent(H.getStart(),"th,td");if(n){I=C(n);A=F();n=w(I.x,I.y)}d.extend(this,{deleteTable:q,split:z,merge:o,insertRow:k,insertCol:h,deleteCols:m,deleteRows:l,cutRows:B,copyRows:G,pasteRows:y,getPos:C,setStartCell:v,setEndCell:u})}d.create("tinymce.plugins.TablePlugin",{init:function(g,h){var f,l,i=true;function k(o){var n=g.selection,m=g.dom.getParent(o||n.getNode(),"table");if(m){return new b(m,g.dom,n)}}function j(){g.getBody().style.webkitUserSelect="";if(i){g.dom.removeClass(g.dom.select("td.mceSelected,th.mceSelected"),"mceSelected");i=false}}e([["table","table.desc","mceInsertTable",true],["delete_table","table.del","mceTableDelete"],["delete_col","table.delete_col_desc","mceTableDeleteCol"],["delete_row","table.delete_row_desc","mceTableDeleteRow"],["col_after","table.col_after_desc","mceTableInsertColAfter"],["col_before","table.col_before_desc","mceTableInsertColBefore"],["row_after","table.row_after_desc","mceTableInsertRowAfter"],["row_before","table.row_before_desc","mceTableInsertRowBefore"],["row_props","table.row_desc","mceTableRowProps",true],["cell_props","table.cell_desc","mceTableCellProps",true],["split_cells","table.split_cells_desc","mceTableSplitCells",true],["merge_cells","table.merge_cells_desc","mceTableMergeCells",true]],function(m){g.addButton(m[0],{title:m[1],cmd:m[2],ui:m[3]})});if(!d.isIE){g.onClick.add(function(m,n){n=n.target;if(n.nodeName==="TABLE"){m.selection.select(n);m.nodeChanged()}})}g.onPreProcess.add(function(n,o){var m,p,q,s=n.dom,r;m=s.select("table",o.node);p=m.length;while(p--){q=m[p];s.setAttrib(q,"data-mce-style","");if((r=s.getAttrib(q,"width"))){s.setStyle(q,"width",r);s.setAttrib(q,"width","")}if((r=s.getAttrib(q,"height"))){s.setStyle(q,"height",r);s.setAttrib(q,"height","")}}});g.onNodeChange.add(function(o,m,r){var q;r=o.selection.getStart();q=o.dom.getParent(r,"td,th,caption");m.setActive("table",r.nodeName==="TABLE"||!!q);if(q&&q.nodeName==="CAPTION"){q=0}m.setDisabled("delete_table",!q);m.setDisabled("delete_col",!q);m.setDisabled("delete_table",!q);m.setDisabled("delete_row",!q);m.setDisabled("col_after",!q);m.setDisabled("col_before",!q);m.setDisabled("row_after",!q);m.setDisabled("row_before",!q);m.setDisabled("row_props",!q);m.setDisabled("cell_props",!q);m.setDisabled("split_cells",!q);m.setDisabled("merge_cells",!q)});g.onInit.add(function(q){var o,s,p=q.dom,t;f=q.windowManager;q.onMouseDown.add(function(v,w){if(w.button!=2){j();s=p.getParent(w.target,"td,th");o=p.getParent(s,"table")}});p.bind(q.getDoc(),"mouseover",function(z){var x,w,y=z.target;if(s&&(t||y!=s)&&(y.nodeName=="TD"||y.nodeName=="TH")){w=p.getParent(y,"table");if(w==o){if(!t){t=k(w);t.setStartCell(s);q.getBody().style.webkitUserSelect="none"}t.setEndCell(y);i=true}x=q.selection.getSel();try{if(x.removeAllRanges){x.removeAllRanges()}else{x.empty()}}catch(v){}z.preventDefault()}});q.onMouseUp.add(function(y){var w,B=y.selection,v,C,A,z;function x(D,F){var E=new d.dom.TreeWalker(D,D);do{if(D.nodeType==3&&d.trim(D.nodeValue).length!==0){if(F){w.setStart(D,0)}else{w.setEnd(D,D.nodeValue.length)}return}if(D.nodeName=="BR"){if(F){w.setStartBefore(D)}else{w.setEndBefore(D)}return}D=(F?E.next():E.prev())}while(D)}if(s){if(t){y.getBody().style.webkitUserSelect=""}v=p.select("td.mceSelected,th.mceSelected");if(v.length>0){w=p.createRng();A=v[0];w.setStartBefore(A);w.setEndAfter(A);x(A,1);C=new d.dom.TreeWalker(A,p.getParent(v[0],"table"));do{if(A.nodeName=="TD"||A.nodeName=="TH"){if(!p.hasClass(A,"mceSelected")){break}z=A}A=C.next()}while(A);x(z);B.setRng(w)}y.nodeChanged();s=t=o=null}});q.onKeyUp.add(function(){j()});q.onKeyDown.add(function(v){m(v)});q.onMouseDown.add(function(v,w){if(w.button!=2){m(v)}});function n(A,w,x,C){var y=3,D=A.dom.getParent(w.startContainer,"TABLE"),z,v,B;if(D){z=D.parentNode}v=w.startContainer.nodeType==y&&w.startOffset===0&&w.endOffset===0&&C&&(x.nodeName==="TR"||x===z);B=(x.nodeName==="TD"||x.nodeName==="TH")&&!C;return v||B}function m(x){if(!d.isWebKit){return}var w=x.selection.getRng();var z=x.selection.getNode();var y=x.dom.getParent(w.startContainer,"TD,TH");if(!n(x,w,z,y)){return}if(!y){y=z}var v=y.lastChild;while(v.lastChild){v=v.lastChild}w.setEnd(v,v.nodeValue.length);x.selection.setRng(w)}q.plugins.table.fixTableCellSelection=m;if(q&&q.plugins.contextmenu){q.plugins.contextmenu.onContextMenu.add(function(x,v,z){var A,y=q.selection,w=y.getNode()||q.getBody();if(q.dom.getParent(z,"td")||q.dom.getParent(z,"th")||q.dom.select("td.mceSelected,th.mceSelected").length){v.removeAll();if(w.nodeName=="A"&&!q.dom.getAttrib(w,"name")){v.add({title:"advanced.link_desc",icon:"link",cmd:q.plugins.advlink?"mceAdvLink":"mceLink",ui:true});v.add({title:"advanced.unlink_desc",icon:"unlink",cmd:"UnLink"});v.addSeparator()}if(w.nodeName=="IMG"&&w.className.indexOf("mceItem")==-1){v.add({title:"advanced.image_desc",icon:"image",cmd:q.plugins.advimage?"mceAdvImage":"mceImage",ui:true});v.addSeparator()}v.add({title:"table.desc",icon:"table",cmd:"mceInsertTable",value:{action:"insert"}});v.add({title:"table.props_desc",icon:"table_props",cmd:"mceInsertTable"});v.add({title:"table.del",icon:"delete_table",cmd:"mceTableDelete"});v.addSeparator();A=v.addMenu({title:"table.cell"});A.add({title:"table.cell_desc",icon:"cell_props",cmd:"mceTableCellProps"});A.add({title:"table.split_cells_desc",icon:"split_cells",cmd:"mceTableSplitCells"});A.add({title:"table.merge_cells_desc",icon:"merge_cells",cmd:"mceTableMergeCells"});A=v.addMenu({title:"table.row"});A.add({title:"table.row_desc",icon:"row_props",cmd:"mceTableRowProps"});A.add({title:"table.row_before_desc",icon:"row_before",cmd:"mceTableInsertRowBefore"});A.add({title:"table.row_after_desc",icon:"row_after",cmd:"mceTableInsertRowAfter"});A.add({title:"table.delete_row_desc",icon:"delete_row",cmd:"mceTableDeleteRow"});A.addSeparator();A.add({title:"table.cut_row_desc",icon:"cut",cmd:"mceTableCutRow"});A.add({title:"table.copy_row_desc",icon:"copy",cmd:"mceTableCopyRow"});A.add({title:"table.paste_row_before_desc",icon:"paste",cmd:"mceTablePasteRowBefore"}).setDisabled(!l);A.add({title:"table.paste_row_after_desc",icon:"paste",cmd:"mceTablePasteRowAfter"}).setDisabled(!l);A=v.addMenu({title:"table.col"});A.add({title:"table.col_before_desc",icon:"col_before",cmd:"mceTableInsertColBefore"});A.add({title:"table.col_after_desc",icon:"col_after",cmd:"mceTableInsertColAfter"});A.add({title:"table.delete_col_desc",icon:"delete_col",cmd:"mceTableDeleteCol"})}else{v.add({title:"table.desc",icon:"table",cmd:"mceInsertTable"})}})}function u(z,K){var I=d.VK;var N=K.keyCode;function L(V,R,P){var Q=V?"previousSibling":"nextSibling";var W=z.dom.getParent(R,"tr");var U=W[Q];if(U){w(z,R,U,V);d.dom.Event.cancel(P);return true}else{var X=z.dom.getParent(W,"table");var T=W.parentNode;var O=T.nodeName.toLowerCase();if(O==="tbody"||O===(V?"tfoot":"thead")){var S=v(V,X,T,"tbody");if(S!==null){return H(V,S,R,P)}}return J(V,W,Q,X,P)}}function v(S,Q,R,U){var P=z.dom.select(">"+U,Q);var O=P.indexOf(R);if(S&&O===0||!S&&O===P.length-1){return y(S,Q)}else{if(O===-1){var T=R.tagName.toLowerCase()==="thead"?0:P.length-1;return P[T]}else{return P[O+(S?-1:1)]}}}function y(R,Q){var P=R?"thead":"tfoot";var O=z.dom.select(">"+P,Q);return O.length!==0?O[0]:null}function H(S,Q,P,R){var O=G(Q,S);if(O){w(z,P,O,S)}d.dom.Event.cancel(R);return true}function J(V,R,O,U,T){var P=U[O];if(P){C(P);return true}else{var S=z.dom.getParent(U,"td,th");if(S){return L(V,S,T)}else{var Q=G(R,!V);C(Q);return d.dom.Event.cancel(T)}}}function G(P,O){var Q=P&&P[O?"lastChild":"firstChild"];return Q&&Q.nodeName==="BR"?z.dom.getParent(Q,"td,th"):Q}function C(O){z.selection.setCursorLocation(O,0)}function x(){return N==I.UP||N==I.DOWN}function A(O){var Q=O.selection.getNode();var P=O.dom.getParent(Q,"tr");return P!==null}function M(P){var O=0;var Q=P;while(Q.previousSibling){Q=Q.previousSibling;O=O+a(Q,"colspan")}return O}function B(Q,O){var R=0;var P=0;e(Q.children,function(S,T){R=R+a(S,"colspan");P=T;if(R>O){return false}});return P}function w(Q,T,V,S){var U=M(Q.dom.getParent(T,"td,th"));var P=B(V,U);var O=V.childNodes[P];var R=G(O,S);C(R||O)}function E(O){var Q=z.selection.getNode();var R=z.dom.getParent(Q,"td,th");var P=z.dom.getParent(O,"td,th");return R&&R!==P&&F(R,P)}function F(P,O){return z.dom.getParent(P,"TABLE")===z.dom.getParent(O,"TABLE")}if(x()&&A(z)){var D=z.selection.getNode();setTimeout(function(){if(E(D)){L(!K.shiftKey&&N===I.UP,D,K)}},0)}}if(d.isWebKit){q.onKeyDown.add(u)}function r(){var v;v=q.getBody().lastChild;while(v&&v.nodeType==3&&!v.nodeValue.length){v=v.previousSibling}if(v&&v.nodeName==="TABLE"){if(q.settings.forced_root_block){q.dom.add(q.getBody(),q.settings.forced_root_block,null,d.isIE&&!d.isIE11?" ":'
')}else{q.dom.add(q.getBody(),"br",{"data-mce-bogus":"1"})}}}if(d.isGecko){q.onKeyDown.add(function(w,y){var v,x,z=w.dom;if(y.keyCode==37||y.keyCode==38){v=w.selection.getRng();x=z.getParent(v.startContainer,"table");if(x&&w.getBody().firstChild==x){if(c(v,x)){v=z.createRng();v.setStartBefore(x);v.setEndBefore(x);w.selection.setRng(v);y.preventDefault()}}}})}q.onKeyUp.add(r);q.onSetContent.add(r);q.onVisualAid.add(r);q.onPreProcess.add(function(v,x){var w=x.node.lastChild;if(w&&(w.nodeName=="BR"||(w.childNodes.length==1&&(w.firstChild.nodeName=="BR"||w.firstChild.nodeValue=="\u00a0")))&&w.previousSibling&&w.previousSibling.nodeName=="TABLE"){v.dom.remove(w)}});r();q.startContent=q.getContent({format:"raw"})});e({mceTableSplitCells:function(m){m.split()},mceTableMergeCells:function(n){var o,p,m;m=g.dom.getParent(g.selection.getNode(),"th,td");if(m){o=m.rowSpan;p=m.colSpan}if(!g.dom.select("td.mceSelected,th.mceSelected").length){f.open({url:h+"/merge_cells.htm",width:240+parseInt(g.getLang("table.merge_cells_delta_width",0),10),height:110+parseInt(g.getLang("table.merge_cells_delta_height",0),10),inline:1},{rows:o,cols:p,onaction:function(q){n.merge(m,q.cols,q.rows)},plugin_url:h})}else{n.merge()}},mceTableInsertRowBefore:function(m){m.insertRow(true)},mceTableInsertRowAfter:function(m){m.insertRow()},mceTableInsertColBefore:function(m){m.insertCol(true)},mceTableInsertColAfter:function(m){m.insertCol()},mceTableDeleteCol:function(m){m.deleteCols()},mceTableDeleteRow:function(m){m.deleteRows()},mceTableCutRow:function(m){l=m.cutRows()},mceTableCopyRow:function(m){l=m.copyRows()},mceTablePasteRowBefore:function(m){m.pasteRows(l,true)},mceTablePasteRowAfter:function(m){m.pasteRows(l)},mceTableDelete:function(m){m.deleteTable()}},function(n,m){g.addCommand(m,function(){var o=k();if(o){n(o);g.execCommand("mceRepaint");j()}})});e({mceInsertTable:function(m){f.open({url:h+"/table.htm",width:400+parseInt(g.getLang("table.table_delta_width",0),10),height:320+parseInt(g.getLang("table.table_delta_height",0),10),inline:1},{plugin_url:h,action:m?m.action:0})},mceTableRowProps:function(){f.open({url:h+"/row.htm",width:400+parseInt(g.getLang("table.rowprops_delta_width",0),10),height:295+parseInt(g.getLang("table.rowprops_delta_height",0),10),inline:1},{plugin_url:h})},mceTableCellProps:function(){f.open({url:h+"/cell.htm",width:400+parseInt(g.getLang("table.cellprops_delta_width",0),10),height:295+parseInt(g.getLang("table.cellprops_delta_height",0),10),inline:1},{plugin_url:h})}},function(n,m){g.addCommand(m,function(o,p){n(p)})})}});d.PluginManager.add("table",d.plugins.TablePlugin)})(tinymce); +(function(){var a=tinymce.each;tinymce.create("tinymce.plugins.TemplatePlugin",{init:function(b,c){var d=this;d.editor=b;b.addCommand("mceTemplate",function(e){b.windowManager.open({file:c+"/template.htm",width:b.getParam("template_popup_width",750),height:b.getParam("template_popup_height",600),inline:1},{plugin_url:c})});b.addCommand("mceInsertTemplate",d._insertTemplate,d);b.addButton("template",{title:"template.desc",cmd:"mceTemplate"});b.onPreProcess.add(function(e,g){var f=e.dom;a(f.select("div",g.node),function(h){if(f.hasClass(h,"mceTmpl")){a(f.select("*",h),function(i){if(f.hasClass(i,e.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))){i.innerHTML=d._getDateTime(new Date(),e.getParam("template_mdate_format",e.getLang("template.mdate_format")))}});d._replaceVals(h)}})})},getInfo:function(){return{longname:"Template plugin",author:"Moxiecode Systems AB",authorurl:"http://www.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/template",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_insertTemplate:function(i,j){var k=this,g=k.editor,f,c,d=g.dom,b=g.selection.getContent();f=j.content;a(k.editor.getParam("template_replace_values"),function(l,h){if(typeof(l)!="function"){f=f.replace(new RegExp("\\{\\$"+h+"\\}","g"),l)}});c=d.create("div",null,f);n=d.select(".mceTmpl",c);if(n&&n.length>0){c=d.create("div",null);c.appendChild(n[0].cloneNode(true))}function e(l,h){return new RegExp("\\b"+h+"\\b","g").test(l.className)}a(d.select("*",c),function(h){if(e(h,g.getParam("template_cdate_classes","cdate").replace(/\s+/g,"|"))){h.innerHTML=k._getDateTime(new Date(),g.getParam("template_cdate_format",g.getLang("template.cdate_format")))}if(e(h,g.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))){h.innerHTML=k._getDateTime(new Date(),g.getParam("template_mdate_format",g.getLang("template.mdate_format")))}if(e(h,g.getParam("template_selected_content_classes","selcontent").replace(/\s+/g,"|"))){h.innerHTML=b}});k._replaceVals(c);g.execCommand("mceInsertContent",false,c.innerHTML);g.addVisual()},_replaceVals:function(c){var d=this.editor.dom,b=this.editor.getParam("template_replace_values");a(d.select("*",c),function(f){a(b,function(g,e){if(d.hasClass(f,e)){if(typeof(b[e])=="function"){b[e](f)}}})})},_getDateTime:function(e,b){if(!b){return""}function c(g,d){var f;g=""+g;if(g.length0){for(m=j+1;m=0;m--){if(r(n[m])){return n[m]}}}return null}if(p.keyCode===9){k=b(l.getParam("tab_focus",l.getParam("tabfocus_elements",":prev,:next")));if(k.length==1){k[1]=k[0];k[0]=":prev"}if(p.shiftKey){if(k[0]==":prev"){n=q(-1)}else{n=c.get(k[0])}}else{if(k[1]==":next"){n=q(1)}else{n=c.get(k[1])}}if(n){if(n.id&&(l=tinymce.get(n.id||n.name))){l.focus()}else{window.setTimeout(function(){if(!tinymce.isWebKit){window.focus()}n.focus()},10)}return a.cancel(p)}}}f.onKeyUp.add(e);if(tinymce.isGecko){f.onKeyPress.add(h);f.onKeyDown.add(e)}else{f.onKeyDown.add(h)}},getInfo:function(){return{longname:"Tabfocus",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("tabfocus",tinymce.plugins.TabFocusPlugin)})(); +(function(){tinymce.create("tinymce.plugins.SearchReplacePlugin",{init:function(a,c){function b(d){window.focus();a.windowManager.open({file:c+"/searchreplace.htm",width:420+parseInt(a.getLang("searchreplace.delta_width",0)),height:170+parseInt(a.getLang("searchreplace.delta_height",0)),inline:1,auto_focus:0},{mode:d,search_string:a.selection.getContent({format:"text"}),plugin_url:c})}a.addCommand("mceSearch",function(){b("search")});a.addCommand("mceReplace",function(){b("replace")});a.addButton("search",{title:"searchreplace.search_desc",cmd:"mceSearch"});a.addButton("replace",{title:"searchreplace.replace_desc",cmd:"mceReplace"});a.addShortcut("ctrl+f","searchreplace.search_desc","mceSearch")},getInfo:function(){return{longname:"Search/Replace",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("searchreplace",tinymce.plugins.SearchReplacePlugin)})(); +(function(){var c=tinymce.each,a={paste_auto_cleanup_on_paste:true,paste_enable_default_filters:true,paste_block_drop:false,paste_retain_style_properties:"none",paste_strip_class_attributes:"mso",paste_remove_spans:false,paste_remove_styles:false,paste_remove_styles_if_webkit:true,paste_convert_middot_lists:true,paste_convert_headers_to_strong:false,paste_dialog_width:"450",paste_dialog_height:"400",paste_max_consecutive_linebreaks:2,paste_text_use_dialog:false,paste_text_sticky:false,paste_text_sticky_default:false,paste_text_notifyalways:false,paste_text_linebreaktype:"combined",paste_text_replacements:[[/\u2026/g,"..."],[/[\x93\x94\u201c\u201d]/g,'"'],[/[\x60\x91\x92\u2018\u2019]/g,"'"]]};function b(d,e){return d.getParam(e,a[e])}tinymce.create("tinymce.plugins.PastePlugin",{init:function(d,e){var f=this;f.editor=d;f.url=e;f.onPreProcess=new tinymce.util.Dispatcher(f);f.onPostProcess=new tinymce.util.Dispatcher(f);f.onPreProcess.add(f._preProcess);f.onPostProcess.add(f._postProcess);f.onPreProcess.add(function(i,j){d.execCallback("paste_preprocess",i,j)});f.onPostProcess.add(function(i,j){d.execCallback("paste_postprocess",i,j)});d.onKeyDown.addToTop(function(i,j){if(((tinymce.isMac?j.metaKey:j.ctrlKey)&&j.keyCode==86)||(j.shiftKey&&j.keyCode==45)){return false}});d.pasteAsPlainText=b(d,"paste_text_sticky_default");function h(l,j){var k=d.dom,i;f.onPreProcess.dispatch(f,l);l.node=k.create("div",0,l.content);if(tinymce.isGecko){i=d.selection.getRng(true);if(i.startContainer==i.endContainer&&i.startContainer.nodeType==3){if(l.node.childNodes.length===1&&/^(p|h[1-6]|pre)$/i.test(l.node.firstChild.nodeName)&&l.content.indexOf("__MCE_ITEM__")===-1){k.remove(l.node.firstChild,true)}}}f.onPostProcess.dispatch(f,l);l.content=d.serializer.serialize(l.node,{getInner:1,forced_root_block:""});if((!j)&&(d.pasteAsPlainText)){f._insertPlainText(l.content);if(!b(d,"paste_text_sticky")){d.pasteAsPlainText=false;d.controlManager.setActive("pastetext",false)}}else{f._insert(l.content)}}d.addCommand("mceInsertClipboardContent",function(i,j){h(j,true)});if(!b(d,"paste_text_use_dialog")){d.addCommand("mcePasteText",function(j,i){var k=tinymce.util.Cookie;d.pasteAsPlainText=!d.pasteAsPlainText;d.controlManager.setActive("pastetext",d.pasteAsPlainText);if((d.pasteAsPlainText)&&(!k.get("tinymcePasteText"))){if(b(d,"paste_text_sticky")){d.windowManager.alert(d.translate("paste.plaintext_mode_sticky"))}else{d.windowManager.alert(d.translate("paste.plaintext_mode"))}if(!b(d,"paste_text_notifyalways")){k.set("tinymcePasteText","1",new Date(new Date().getFullYear()+1,12,31))}}})}d.addButton("pastetext",{title:"paste.paste_text_desc",cmd:"mcePasteText"});d.addButton("selectall",{title:"paste.selectall_desc",cmd:"selectall"});function g(s){var l,p,j,t,k=d.selection,o=d.dom,q=d.getBody(),i,r;if(s.clipboardData||o.doc.dataTransfer){r=(s.clipboardData||o.doc.dataTransfer).getData("Text");if(d.pasteAsPlainText){s.preventDefault();h({content:o.encode(r).replace(/\r?\n/g,"
")});return}}if(o.get("_mcePaste")){return}l=o.add(q,"div",{id:"_mcePaste","class":"mcePaste","data-mce-bogus":"1"},"\uFEFF\uFEFF");if(q!=d.getDoc().body){i=o.getPos(d.selection.getStart(),q).y}else{i=q.scrollTop+o.getViewPort(d.getWin()).y}o.setStyles(l,{position:"absolute",left:tinymce.isGecko?-40:0,top:i-25,width:1,height:1,overflow:"hidden"});if(tinymce.isIE){t=k.getRng();j=o.doc.body.createTextRange();j.moveToElementText(l);j.execCommand("Paste");o.remove(l);if(l.innerHTML==="\uFEFF\uFEFF"){d.execCommand("mcePasteWord");s.preventDefault();return}k.setRng(t);k.setContent("");setTimeout(function(){h({content:l.innerHTML})},0);return tinymce.dom.Event.cancel(s)}else{function m(n){n.preventDefault()}o.bind(d.getDoc(),"mousedown",m);o.bind(d.getDoc(),"keydown",m);p=d.selection.getRng();l=l.firstChild;j=d.getDoc().createRange();j.setStart(l,0);j.setEnd(l,2);k.setRng(j);window.setTimeout(function(){var u="",n;if(!o.select("div.mcePaste > div.mcePaste").length){n=o.select("div.mcePaste");c(n,function(w){var v=w.firstChild;if(v&&v.nodeName=="DIV"&&v.style.marginTop&&v.style.backgroundColor){o.remove(v,1)}c(o.select("span.Apple-style-span",w),function(x){o.remove(x,1)});c(o.select("br[data-mce-bogus]",w),function(x){o.remove(x)});if(w.parentNode.className!="mcePaste"){u+=w.innerHTML}})}else{u="

"+o.encode(r).replace(/\r?\n\r?\n/g,"

").replace(/\r?\n/g,"
")+"

"}c(o.select("div.mcePaste"),function(v){o.remove(v)});if(p){k.setRng(p)}h({content:u});o.unbind(d.getDoc(),"mousedown",m);o.unbind(d.getDoc(),"keydown",m)},0)}}if(b(d,"paste_auto_cleanup_on_paste")){if(tinymce.isOpera||/Firefox\/2/.test(navigator.userAgent)){d.onKeyDown.addToTop(function(i,j){if(((tinymce.isMac?j.metaKey:j.ctrlKey)&&j.keyCode==86)||(j.shiftKey&&j.keyCode==45)){g(j)}})}else{d.onPaste.addToTop(function(i,j){return g(j)})}}d.onInit.add(function(){d.controlManager.setActive("pastetext",d.pasteAsPlainText);if(b(d,"paste_block_drop")){d.dom.bind(d.getBody(),["dragend","dragover","draggesture","dragdrop","drop","drag"],function(i){i.preventDefault();i.stopPropagation();return false})}});f._legacySupport()},getInfo:function(){return{longname:"Paste text/word",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_preProcess:function(g,e){var k=this.editor,j=e.content,p=tinymce.grep,n=tinymce.explode,f=tinymce.trim,l,i;function d(h){c(h,function(o){if(o.constructor==RegExp){j=j.replace(o,"")}else{j=j.replace(o[0],o[1])}})}if(k.settings.paste_enable_default_filters==false){return}if(tinymce.isIE&&document.documentMode>=9&&/<(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)/.test(e.content)){d([[/(?:
 [\s\r\n]+|
)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:
 [\s\r\n]+|
)*/g,"$1"]]);d([[/

/g,"

"],[/
/g," "],[/

/g,"
"]])}if(/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(j)||e.wordContent){e.wordContent=true;d([/^\s*( )+/gi,/( |]*>)+\s*$/gi]);if(b(k,"paste_convert_headers_to_strong")){j=j.replace(/

]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi,"

$1

")}if(b(k,"paste_convert_middot_lists")){d([[//gi,"$&__MCE_ITEM__"],[/(]+(?:mso-list:|:\s*symbol)[^>]+>)/gi,"$1__MCE_ITEM__"],[/(]+(?:MsoListParagraph)[^>]+>)/gi,"$1__MCE_ITEM__"]])}d([//gi,/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,[/<(\/?)s>/gi,"<$1strike>"],[/ /gi,"\u00a0"]]);do{l=j.length;j=j.replace(/(]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi,"$1");j=j.replace(/(<(ol|ul)[^>]*\s)(?:id|name|language|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi,"$1")}while(l!=j.length);if(b(k,"paste_retain_style_properties").replace(/^none$/i,"").length==0){j=j.replace(/<\/?span[^>]*>/gi,"")}else{d([[/([\s\u00a0]*)<\/span>/gi,function(o,h){return(h.length>0)?h.replace(/./," ").slice(Math.floor(h.length/2)).split("").join("\u00a0"):""}],[/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,function(t,h,r){var u=[],o=0,q=n(f(r).replace(/"/gi,"'"),";");c(q,function(s){var w,y,z=n(s,":");function x(A){return A+((A!=="0")&&(/\d$/.test(A)))?"px":""}if(z.length==2){w=z[0].toLowerCase();y=z[1].toLowerCase();switch(w){case"mso-padding-alt":case"mso-padding-top-alt":case"mso-padding-right-alt":case"mso-padding-bottom-alt":case"mso-padding-left-alt":case"mso-margin-alt":case"mso-margin-top-alt":case"mso-margin-right-alt":case"mso-margin-bottom-alt":case"mso-margin-left-alt":case"mso-table-layout-alt":case"mso-height":case"mso-width":case"mso-vertical-align-alt":u[o++]=w.replace(/^mso-|-alt$/g,"")+":"+x(y);return;case"horiz-align":u[o++]="text-align:"+y;return;case"vert-align":u[o++]="vertical-align:"+y;return;case"font-color":case"mso-foreground":u[o++]="color:"+y;return;case"mso-background":case"mso-highlight":u[o++]="background:"+y;return;case"mso-default-height":u[o++]="min-height:"+x(y);return;case"mso-default-width":u[o++]="min-width:"+x(y);return;case"mso-padding-between-alt":u[o++]="border-collapse:separate;border-spacing:"+x(y);return;case"text-line-through":if((y=="single")||(y=="double")){u[o++]="text-decoration:line-through"}return;case"mso-zero-height":if(y=="yes"){u[o++]="display:none"}return}if(/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(w)){return}u[o++]=w+":"+z[1]}});if(o>0){return h+' style="'+u.join(";")+'"'}else{return h}}]])}}if(b(k,"paste_convert_headers_to_strong")){d([[/]*>/gi,"

"],[/<\/h[1-6][^>]*>/gi,"

"]])}d([[/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi,""]]);i=b(k,"paste_strip_class_attributes");if(i!=="none"){function m(q,o){if(i==="all"){return""}var h=p(n(o.replace(/^(["'])(.*)\1$/,"$2")," "),function(r){return(/^(?!mso)/i.test(r))});return h.length?' class="'+h.join(" ")+'"':""}j=j.replace(/ class="([^"]+)"/gi,m);j=j.replace(/ class=([\-\w]+)/gi,m)}if(b(k,"paste_remove_spans")){j=j.replace(/<\/?span[^>]*>/gi,"")}e.content=j},_postProcess:function(g,i){var f=this,e=f.editor,h=e.dom,d;if(e.settings.paste_enable_default_filters==false){return}if(i.wordContent){c(h.select("a",i.node),function(j){if(!j.href||j.href.indexOf("#_Toc")!=-1){h.remove(j,1)}});if(b(e,"paste_convert_middot_lists")){f._convertLists(g,i)}d=b(e,"paste_retain_style_properties");if((tinymce.is(d,"string"))&&(d!=="all")&&(d!=="*")){d=tinymce.explode(d.replace(/^none$/i,""));c(h.select("*",i.node),function(m){var n={},k=0,l,o,j;if(d){for(l=0;l0){h.setStyles(m,n)}else{if(m.nodeName=="SPAN"&&!m.className){h.remove(m,true)}}})}}if(b(e,"paste_remove_styles")||(b(e,"paste_remove_styles_if_webkit")&&tinymce.isWebKit)){c(h.select("*[style]",i.node),function(j){j.removeAttribute("style");j.removeAttribute("data-mce-style")})}else{if(tinymce.isWebKit){c(h.select("*",i.node),function(j){j.removeAttribute("data-mce-style")})}}},_convertLists:function(g,e){var i=g.editor.dom,h,l,d=-1,f,m=[],k,j;c(i.select("p",e.node),function(t){var q,u="",s,r,n,o;for(q=t.firstChild;q&&q.nodeType==3;q=q.nextSibling){u+=q.nodeValue}u=t.innerHTML.replace(/<\/?\w+[^>]*>/gi,"").replace(/ /g,"\u00a0");if(/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(u)){s="ul"}if(/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(u)){s="ol"}if(s){f=parseFloat(t.style.marginLeft||0);if(f>d){m.push(f)}if(!h||s!=k){h=i.create(s);i.insertAfter(h,t)}else{if(f>d){h=l.appendChild(i.create(s))}else{if(f]*>/gi,"");if(s=="ul"&&/^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(p)){i.remove(v)}else{if(/^__MCE_ITEM__[\s\S]*\w+\.( |\u00a0)*\s*/.test(p)){i.remove(v)}}});r=t.innerHTML;if(s=="ul"){r=t.innerHTML.replace(/__MCE_ITEM__/g,"").replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*( |\u00a0)+\s*/,"")}else{r=t.innerHTML.replace(/__MCE_ITEM__/g,"").replace(/^\s*[\w|'<'|'>']+\.( |\u00a0)+\s*/,"")}l=h.appendChild(i.create("li",0,r));i.remove(t);d=f;k=s}else{h=d=0}});j=e.node.innerHTML;if(j.indexOf("__MCE_ITEM__")!=-1){e.node.innerHTML=j.replace(/__MCE_ITEM__/g,"")}},_insert:function(f,d){var e=this.editor,g=e.selection.getRng();if(!e.selection.isCollapsed()&&g.startContainer!=g.endContainer){e.getDoc().execCommand("Delete",false,null)}e.execCommand("mceInsertContent",false,f,{skip_undo:d})},_insertPlainText:function(j){var h=this.editor,f=b(h,"paste_text_linebreaktype"),k=b(h,"paste_text_replacements"),g=tinymce.is;function e(m){c(m,function(n){if(n.constructor==RegExp){j=j.replace(n,"")}else{j=j.replace(n[0],n[1])}})}if((typeof(j)==="string")&&(j.length>0)){if(/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(j)){e([/[\n\r]+/g])}else{e([/\r+/g])}e([[/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi,"\n\n"],[/]*>|<\/tr>/gi,"\n"],[/<\/t[dh]>\s*]*>/gi,"\t"],/<[a-z!\/?][^>]*>/gi,[/ /gi," "],[/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi,"$1"]]);var d=Number(b(h,"paste_max_consecutive_linebreaks"));if(d>-1){var l=new RegExp("\n{"+(d+1)+",}","g");var i="";while(i.length"]])}else{if(f=="p"){e([[/\n+/g,"

"],[/^(.*<\/p>)(

)$/,"

$1"]])}else{e([[/\n\n/g,"

"],[/^(.*<\/p>)(

)$/,"

$1"],[/\n/g,"
"]])}}}h.execCommand("mceInsertContent",false,j)}},_legacySupport:function(){var e=this,d=e.editor;d.addCommand("mcePasteWord",function(){d.windowManager.open({file:e.url+"/pasteword.htm",width:parseInt(b(d,"paste_dialog_width")),height:parseInt(b(d,"paste_dialog_height")),inline:1})});if(b(d,"paste_text_use_dialog")){d.addCommand("mcePasteText",function(){d.windowManager.open({file:e.url+"/pastetext.htm",width:parseInt(b(d,"paste_dialog_width")),height:parseInt(b(d,"paste_dialog_height")),inline:1})})}d.addButton("pasteword",{title:"paste.paste_word_desc",cmd:"mcePasteWord"})}});tinymce.PluginManager.add("paste",tinymce.plugins.PastePlugin)})(); +(function(){var a=tinymce.explode("id,name,style,align,class,hspace,vspace,bgcolor,type"),c=tinymce.makeMap(a.join(",")),d=a.concat(tinymce.explode("width, height")),b=tinymce.makeMap(d.join(",")),h=tinymce.html.Node,g,j,i=tinymce.util.JSON;g=[["Flash","d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash","http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"],["ShockWave","166b1bca-3f9c-11cf-8075-444553540000","application/x-director","http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0"],["WindowsMedia","6bf52a52-394a-11d3-b153-00c04f79faa6,22d6f312-b0f6-11d0-94ab-0080c74c7e95,05589fa1-c356-11ce-bf01-00aa0055595a","application/x-mplayer2","http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"],["QuickTime","02bf25d5-8c17-4b23-bc80-d3488abddc6b","video/quicktime","http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"],["RealMedia","cfcdaa03-8be4-11cf-b84b-0020afbbccfa","audio/x-pn-realaudio-plugin","http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"],["Java","8ad9c840-044e-11d1-b3e9-00805f499d93","application/x-java-applet","http://java.sun.com/products/plugin/autodl/jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0"],["Silverlight","dfeaf541-f3e1-4c24-acac-99c30715084a","application/x-silverlight-2"],["Iframe"],["Video"],["EmbeddedAudio"],["Audio"],["Object"]];function f(k){return typeof(k)=="string"?k.replace(/[^0-9%]/g,""):k}function e(m){var k,l;if(m&&!m.splice){k=[];for(l=0;true;l++){if(m[l]){k[l]=m[l]}else{break}}return k}return m}tinymce.create("tinymce.plugins.MediaPlugin",{init:function(o,k){var s=this,m={},n,q,r,l;function p(t){return t&&t.nodeName==="IMG"&&o.dom.hasClass(t,"mceItemMedia")}s.editor=o;s.url=k;j="";for(n=0;n0){N+=(N?"&":"")+O+"="+escape(P)}});if(N.length){F.params.flashvars=N}K=q.getParam("flash_video_player_params",{allowfullscreen:true,allowscriptaccess:true});tinymce.each(K,function(P,O){F.params[O]=""+P})}}function x(K,J,I,L){G=new h("object",1).attr({id:K.attr("id"),width:f(K.attr("width")),height:f(K.attr("height")),style:J});tinymce.each(I,function(N){var O=L[N];if(N=="class"&&O){O=O.replace(/mceItem.+ ?/g,"")}if(O&&N!="type"){G.attr(N,O)}});for(var n in L.params){var M;M=new h("param",1);M.shortEnded=true;y=L.params[n];if(n==="src"&&r.name==="WindowsMedia"){n="url"}M.attr({name:n,value:y});G.append(M)}if(L.object_html){y=new h("#text",3);y.raw=true;y.value=L.object_html;G.append(y)}if(D){D.append(G)}return G}F=z.attr("data-mce-json");if(!F){return}F=i.parse(F);r=this.getType(z.attr("class"));C=z.attr("data-mce-style");if(!C){C=z.attr("style");if(C){C=q.dom.serializeStyle(q.dom.parseStyle(C,"img"))}}F.width=z.attr("width")||F.width;F.height=z.attr("height")||F.height;if(r.name==="Iframe"){A=new h("iframe",1);tinymce.each(d,function(n){var I=z.attr(n);if(n=="class"&&I){I=I.replace(/mceItem.+ ?/g,"")}if(I&&I.length>0){A.attr(n,I)}});for(H in F.params){A.attr(H,F.params[H])}A.attr({style:C,src:F.params.src});z.replace(A);return}if(this.editor.settings.media_use_script){A=new h("script",1).attr("type","text/javascript");y=new h("#text",3);y.value="write"+r.name+"("+i.serialize(tinymce.extend(F.params,{width:z.attr("width"),height:z.attr("height")}))+");";A.append(y);z.replace(A);return}if(r.name==="Video"&&F.video.sources[0]){D=new h("video",1).attr(tinymce.extend({id:z.attr("id"),width:f(z.attr("width")),height:f(z.attr("height")),style:C},F.video.attrs));if(F.video.attrs){m=F.video.attrs.poster}l=F.video.sources=e(F.video.sources);for(B=0;B1&&W.charCodeAt(W.length-1)==32){return(U.endOffset==W.length-1)}else{return(U.endOffset==W.length)}}else{if(V.nodeType==1){return U.endOffset==V.childNodes.length}}return false}function I(){var W=y.selection.getNode();var V="h1,h2,h3,h4,h5,h6,p,div";var U=y.dom.is(W,V)&&W.parentNode.tagName==="LI"&&W.parentNode.lastChild===W;return y.selection.isCollapsed()&&U&&C()}function K(W,Y){if(A(Y)&&I()){var X=W.selection.getNode();var V=W.dom.create("li");var U=W.dom.getParent(X,"li");W.dom.insertAfter(V,U);if(tinymce.isIE6||tinymce.isIE7||tinyMCE.isIE8){W.selection.setCursorLocation(V,1)}else{W.selection.setCursorLocation(V,0)}Y.preventDefault()}}function u(X,Z){var ac;if(!tinymce.isGecko){return}var V=X.selection.getStart();if(Z.keyCode!=tinymce.VK.BACKSPACE||V.tagName!=="IMG"){return}function W(ag){var ah=ag.firstChild;var af=null;do{if(!ah){break}if(ah.tagName==="LI"){af=ah}}while(ah=ah.nextSibling);return af}function ae(ag,af){while(ag.childNodes.length>0){af.appendChild(ag.childNodes[0])}}ac=V.parentNode.previousSibling;if(!ac){return}var aa;if(ac.tagName==="UL"||ac.tagName==="OL"){aa=ac}else{if(ac.previousSibling&&(ac.previousSibling.tagName==="UL"||ac.previousSibling.tagName==="OL")){aa=ac.previousSibling}else{return}}var ad=W(aa);var U=X.dom.createRng();U.setStart(ad,1);U.setEnd(ad,1);X.selection.setRng(U);X.selection.collapse(true);var Y=X.selection.getBookmark();var ab=V.parentNode.cloneNode(true);if(ab.tagName==="P"||ab.tagName==="DIV"){ae(ab,ad)}else{ad.appendChild(ab)}V.parentNode.parentNode.removeChild(V.parentNode);X.selection.moveToBookmark(Y)}function G(U){var V=y.dom.getParent(U,"ol,ul");if(V!=null){var W=V.lastChild;y.selection.setCursorLocation(W,0)}}this.ed=y;y.addCommand("Indent",this.indent,this);y.addCommand("Outdent",this.outdent,this);y.addCommand("InsertUnorderedList",function(){this.applyList("UL","OL")},this);y.addCommand("InsertOrderedList",function(){this.applyList("OL","UL")},this);y.onInit.add(function(){y.editorCommands.addCommands({outdent:function(){var V=y.selection,W=y.dom;function U(X){X=W.getParent(X,W.isBlock);return X&&(parseInt(y.dom.getStyle(X,"margin-left")||0,10)+parseInt(y.dom.getStyle(X,"padding-left")||0,10))>0}return U(V.getStart())||U(V.getEnd())||y.queryCommandState("InsertOrderedList")||y.queryCommandState("InsertUnorderedList")}},"state")});y.onKeyUp.add(function(V,W){if(x==v){V.execCommand(W.shiftKey?"Outdent":"Indent",true,null);x=N;return r.cancel(W)}else{if(x==s){var U=B();var Y=V.settings.list_outdent_on_enter===true||W.shiftKey;V.execCommand(Y?"Outdent":"Indent",true,null);if(tinymce.isIE){G(U)}return r.cancel(W)}else{if(x==J){if(tinymce.isIE6||tinymce.isIE7||tinymce.isIE8){var X=V.getDoc().createTextNode("\uFEFF");V.selection.getNode().appendChild(X)}else{if(tinymce.isIE9||tinymce.isGecko){V.execCommand("Outdent");return r.cancel(W)}}}}}});function L(V,U){var W=y.getDoc().createTextNode("\uFEFF");V.insertBefore(W,U);y.selection.setCursorLocation(W,0);y.execCommand("mceRepaint")}function R(V,X){if(T(X)){var U=B();if(U){var W=U.parentNode;var Y=W&&W.parentNode;if(Y&&Y.nodeName=="LI"&&Y.firstChild==W&&U==W.firstChild){L(Y,W)}}}}function S(V,X){if(T(X)){var U=B();if(V.dom.select("ul li",U).length===1){var W=U.firstChild;L(U,W)}}}function Q(W,aa){function X(ab){var ad=[];var ae=new tinymce.dom.TreeWalker(ab.firstChild,ab);for(var ac=ae.current();ac;ac=ae.next()){if(W.dom.is(ac,"ol,ul,li")){ad.push(ac)}}return ad}if(aa.keyCode==tinymce.VK.BACKSPACE){var U=B();if(U){var Z=W.dom.getParent(U,"ol,ul"),V=W.selection.getRng();if(Z&&Z.firstChild===U&&V.startOffset==0){var Y=X(U);Y.unshift(U);W.execCommand("Outdent",false,Y);W.undoManager.add();return r.cancel(aa)}}}}function O(V,X){var U=B();if(X.keyCode===tinymce.VK.BACKSPACE&&V.dom.is(U,"li")&&U.parentNode.firstChild!==U){if(V.dom.select("ul,ol",U).length===1){var Z=U.previousSibling;V.dom.remove(V.dom.select("br",U));V.dom.remove(U,true);var W=tinymce.grep(Z.childNodes,function(aa){return aa.nodeType===3});if(W.length===1){var Y=W[0];V.selection.setCursorLocation(Y,Y.length)}V.undoManager.add();return r.cancel(X)}}}y.onKeyDown.add(function(U,V){x=M(V)});y.onKeyDown.add(D);y.onKeyDown.add(u);y.onKeyDown.add(K);if(tinymce.isGecko){y.onKeyUp.add(R)}if(tinymce.isIE8){y.onKeyUp.add(S)}if(tinymce.isGecko||tinymce.isWebKit){y.onKeyDown.add(Q)}if(tinymce.isWebKit){y.onKeyDown.add(O)}},applyList:function(y,v){var C=this,z=C.ed,I=z.dom,s=[],H=false,u=false,w=false,B,G=z.selection.getSelectedBlocks();function E(t){if(t&&t.tagName==="BR"){I.remove(t)}}function F(M){var N=I.create(y),t;function L(O){if(O.style.marginLeft||O.style.paddingLeft){C.adjustPaddingFunction(false)(O)}}if(M.tagName==="LI"){}else{if(M.tagName==="P"||M.tagName==="DIV"||M.tagName==="BODY"){K(M,function(P,O){J(P,O,M.tagName==="BODY"?null:P.parentNode);t=P.parentNode;L(t);E(O)});if(t){if(t.tagName==="LI"&&(M.tagName==="P"||G.length>1)){I.split(t.parentNode.parentNode,t.parentNode)}m(t.parentNode,true)}return}else{t=I.create("li");I.insertAfter(t,M);t.appendChild(M);L(M);M=t}}I.insertAfter(N,M);N.appendChild(M);m(N,true);s.push(M)}function J(P,L,N){var t,O=P,M;while(!I.isBlock(P.parentNode)&&P.parentNode!==I.getRoot()){P=I.split(P.parentNode,P.previousSibling);P=P.nextSibling;O=P}if(N){t=N.cloneNode(true);P.parentNode.insertBefore(t,P);while(t.firstChild){I.remove(t.firstChild)}t=I.rename(t,"li")}else{t=I.create("li");P.parentNode.insertBefore(t,P)}while(O&&O!=L){M=O.nextSibling;t.appendChild(O);O=M}if(t.childNodes.length===0){t.innerHTML='
'}F(t)}function K(Q,T){var N,R,O=3,L=1,t="br,ul,ol,p,div,h1,h2,h3,h4,h5,h6,table,blockquote,address,pre,form,center,dl";function P(X,U){var V=I.createRng(),W;g.keep=true;z.selection.moveToBookmark(g);g.keep=false;W=z.selection.getRng(true);if(!U){U=X.parentNode.lastChild}V.setStartBefore(X);V.setEndAfter(U);return !(V.compareBoundaryPoints(O,W)>0||V.compareBoundaryPoints(L,W)<=0)}function S(U){if(U.nextSibling){return U.nextSibling}if(!I.isBlock(U.parentNode)&&U.parentNode!==I.getRoot()){return S(U.parentNode)}}N=Q.firstChild;var M=false;e(I.select(t,Q),function(U){if(U.hasAttribute&&U.hasAttribute("_mce_bogus")){return true}if(P(N,U)){I.addClass(U,"_mce_tagged_br");N=S(U)}});M=(N&&P(N,undefined));N=Q.firstChild;e(I.select(t,Q),function(V){var U=S(V);if(V.hasAttribute&&V.hasAttribute("_mce_bogus")){return true}if(I.hasClass(V,"_mce_tagged_br")){T(N,V,R);R=null}else{R=V}N=U});if(M){T(N,undefined,R)}}function D(t){K(t,function(M,L,N){J(M,L);E(L);E(N)})}function A(t){if(tinymce.inArray(s,t)!==-1){return}if(t.parentNode.tagName===v){I.split(t.parentNode,t);F(t);o(t.parentNode,false)}s.push(t)}function x(M){var O,N,L,t;if(tinymce.inArray(s,M)!==-1){return}M=c(M,I);while(I.is(M.parentNode,"ol,ul,li")){I.split(M.parentNode,M)}s.push(M);M=I.rename(M,"p");L=m(M,false,z.settings.force_br_newlines);if(L===M){O=M.firstChild;while(O){if(I.isBlock(O)){O=I.split(O.parentNode,O);t=true;N=O.nextSibling&&O.nextSibling.firstChild}else{N=O.nextSibling;if(t&&O.tagName==="BR"){I.remove(O)}t=false}O=N}}}e(G,function(t){t=k(t,I);if(t.tagName===v||(t.tagName==="LI"&&t.parentNode.tagName===v)){u=true}else{if(t.tagName===y||(t.tagName==="LI"&&t.parentNode.tagName===y)){H=true}else{w=true}}});if(w&&!H||u||G.length===0){B={LI:A,H1:F,H2:F,H3:F,H4:F,H5:F,H6:F,P:F,BODY:F,DIV:G.length>1?F:D,defaultAction:D,elements:this.selectedBlocks()}}else{B={defaultAction:x,elements:this.selectedBlocks(),processEvenIfEmpty:true}}this.process(B)},indent:function(){var u=this.ed,w=u.dom,x=[];function s(z){var y=w.create("li",{style:"list-style-type: none;"});w.insertAfter(y,z);return y}function t(B){var y=s(B),D=w.getParent(B,"ol,ul"),C=D.tagName,E=w.getStyle(D,"list-style-type"),A={},z;if(E!==""){A.style="list-style-type: "+E+";"}z=w.create(C,A);y.appendChild(z);return z}function v(z){if(!d(u,z,x)){z=c(z,w);var y=t(z);y.appendChild(z);m(y.parentNode,false);m(y,false);x.push(z)}}this.process({LI:v,defaultAction:this.adjustPaddingFunction(true),elements:this.selectedBlocks()})},outdent:function(y,x){var w=this,u=w.ed,z=u.dom,s=[];function A(t){var C,B,D;if(!d(u,t,s)){if(z.getStyle(t,"margin-left")!==""||z.getStyle(t,"padding-left")!==""){return w.adjustPaddingFunction(false)(t)}D=z.getStyle(t,"text-align",true);if(D==="center"||D==="right"){z.setStyle(t,"text-align","left");return}t=c(t,z);C=t.parentNode;B=t.parentNode.parentNode;if(B.tagName==="P"){z.split(B,t.parentNode)}else{z.split(C,t);if(B.tagName==="LI"){z.split(B,t)}else{if(!z.is(B,"ol,ul")){z.rename(t,"p")}}}s.push(t)}}var v=x&&tinymce.is(x,"array")?x:this.selectedBlocks();this.process({LI:A,defaultAction:this.adjustPaddingFunction(false),elements:v});e(s,m)},process:function(y){var F=this,w=F.ed.selection,z=F.ed.dom,E,u;function B(t){var s=tinymce.grep(t.childNodes,function(H){return !(H.nodeName==="BR"||H.nodeName==="SPAN"&&z.getAttrib(H,"data-mce-type")=="bookmark"||H.nodeType==3&&(H.nodeValue==String.fromCharCode(160)||H.nodeValue==""))});return s.length===0}function x(s){z.removeClass(s,"_mce_act_on");if(!s||s.nodeType!==1||!y.processEvenIfEmpty&&E.length>1&&B(s)){return}s=k(s,z);var t=y[s.tagName];if(!t){t=y.defaultAction}t(s)}function v(s){F.splitSafeEach(s.childNodes,x,true)}function C(s,t){return t>=0&&s.hasChildNodes()&&t0){t=s.shift();w.removeClass(t,"_mce_act_on");u(t);s=w.select("._mce_act_on")}},adjustPaddingFunction:function(u){var s,v,t=this.ed;s=t.settings.indentation;v=/[a-z%]+/i.exec(s);s=parseInt(s,10);return function(w){var y,x;y=parseInt(t.dom.getStyle(w,"margin-left")||0,10)+parseInt(t.dom.getStyle(w,"padding-left")||0,10);if(u){x=y+s}else{x=y-s}t.dom.setStyle(w,"padding-left","");t.dom.setStyle(w,"margin-left",x>0?x+v:"")}},selectedBlocks:function(){var s=this.ed,t=s.selection.getSelectedBlocks();return t.length==0?[s.dom.getRoot()]:t},getInfo:function(){return{longname:"Lists",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/lists",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("lists",tinymce.plugins.Lists)}()); +(function(){tinymce.create("tinymce.plugins.InsertDateTime",{init:function(a,b){var c=this;c.editor=a;a.addCommand("mceInsertDate",function(){var d=c._getDateTime(new Date(),a.getParam("plugin_insertdate_dateFormat",a.getLang("insertdatetime.date_fmt")));a.execCommand("mceInsertContent",false,d)});a.addCommand("mceInsertTime",function(){var d=c._getDateTime(new Date(),a.getParam("plugin_insertdate_timeFormat",a.getLang("insertdatetime.time_fmt")));a.execCommand("mceInsertContent",false,d)});a.addButton("insertdate",{title:"insertdatetime.insertdate_desc",cmd:"mceInsertDate"});a.addButton("inserttime",{title:"insertdatetime.inserttime_desc",cmd:"mceInsertTime"})},getInfo:function(){return{longname:"Insert date/time",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/insertdatetime",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_getDateTime:function(e,a){var c=this.editor;function b(g,d){g=""+g;if(g.length',a="mcePageBreak",c=b.getParam("pagebreak_separator",""),e;e=new RegExp(c.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g,function(g){return"\\"+g}),"g");b.addCommand("mcePageBreak",function(){b.execCommand("mceInsertContent",0,f)});b.addButton("pagebreak",{title:"pagebreak.desc",cmd:a});b.onInit.add(function(){if(b.theme.onResolveName){b.theme.onResolveName.add(function(g,h){if(h.node.nodeName=="IMG"&&b.dom.hasClass(h.node,a)){h.name="pagebreak"}})}});b.onClick.add(function(g,h){h=h.target;if(h.nodeName==="IMG"&&g.dom.hasClass(h,a)){g.selection.select(h)}});b.onNodeChange.add(function(h,g,i){g.setActive("pagebreak",i.nodeName==="IMG"&&h.dom.hasClass(i,a))});b.onBeforeSetContent.add(function(g,h){h.content=h.content.replace(e,f)});b.onPostProcess.add(function(g,h){if(h.get){h.content=h.content.replace(/]+>/g,function(i){if(i.indexOf('class="mcePageBreak')!==-1){i=c}return i})}})},getInfo:function(){return{longname:"PageBreak",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/pagebreak",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("pagebreak",tinymce.plugins.PageBreakPlugin)})(); +(function(){tinymce.create("tinymce.plugins.ExampleDependencyPlugin",{init:function(a,b){},getInfo:function(){return{longname:"Example Dependency plugin",author:"Some author",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example_dependency",version:"1.0"}}});tinymce.PluginManager.add("example_dependency",tinymce.plugins.ExampleDependencyPlugin,["example"])})(); +(function(){var h=tinymce.dom.TreeWalker;var d="contenteditable",c="data-mce-"+d;var i=tinymce.VK;var e,j,b;function g(t){var p=t.dom,v=t.selection,u="mce_noneditablecaret",x="\uFEFF",m=t.getParam("noneditable_prevent_delete");function s(z){var y;if(z.nodeType===1){y=z.getAttribute(c);if(y&&y!=="inherit"){return y}y=z.contentEditable;if(y!=="inherit"){return y}}return null}function l(y){var z;while(y){z=s(y);if(z){return z==="false"?y:null}y=y.parentNode}}function r(y){while(y){if(y.id===u){return y}y=y.parentNode}}function q(y){var z;if(y){z=new h(y,y);for(y=z.current();y;y=z.next()){if(y.nodeType===3){return y}}}}function k(B,A){var y,z;if(s(B)==="false"){if(p.isBlock(B)){v.select(B);return}}z=p.createRng();if(s(B)==="true"){if(!B.firstChild){B.appendChild(t.getDoc().createTextNode("\u00a0"))}B=B.firstChild;A=true}y=p.create("span",{id:u,"data-mce-bogus":true},x);if(A){B.parentNode.insertBefore(y,B)}else{p.insertAfter(y,B)}z.setStart(y.firstChild,1);z.collapse(true);v.setRng(z);return y}function o(y){var C,A,B,z;if(y){z=v.getRng(true);z.setStartBefore(y);z.setEndBefore(y);C=q(y);if(C&&C.nodeValue.charAt(0)==x){C=C.deleteData(0,1)}p.remove(y,true);v.setRng(z)}else{A=r(v.getStart());while((y=p.get(u))&&y!==B){if(A!==y){C=q(y);if(C&&C.nodeValue.charAt(0)==x){C=C.deleteData(0,1)}p.remove(y,true)}B=y}}}function w(){var y,C,A,z,B;function D(G,I){var F,K,J,H,E;F=z.startContainer;K=z.startOffset;if(F.nodeType==3){E=F.nodeValue.length;if((K>0&&K0?K-1:K;F=F.childNodes[L];if(F.hasChildNodes()){F=F.firstChild}}else{return !I?G:null}}J=new h(F,G);while(H=J[I?"prev":"next"]()){if(H.nodeType===3&&H.nodeValue.length>0){return}else{if(s(H)==="true"){return H}}}return G}o();A=v.isCollapsed();y=l(v.getStart());C=l(v.getEnd());if(y||C){z=v.getRng(true);if(A){y=y||C;if(D(y,true)){B=D(y,true);k(B,true)}else{if(D(y,false)){B=D(y,false);k(B,false)}else{v.select(y)}}}else{z=v.getRng(true);if(y){z.setStartBefore(y)}if(C){z.setEndAfter(C)}v.setRng(z)}}}function n(D,Q){var G=Q.keyCode,S,J,y,F,A,I=false,z;function B(U,T){while(U=U[T?"previousSibling":"nextSibling"]){if(U.nodeType!==3||U.nodeValue.length>0){return U}}}function K(T,U){v.select(T);v.collapse(U)}function P(X){var W,V,Z,U;function T(ab){var aa=V;while(aa){if(aa===ab){return}aa=aa.parentNode}p.remove(ab);w()}function Y(){var ab,ac,aa=D.schema.getNonEmptyElements();ac=new tinymce.dom.TreeWalker(V,D.getBody());while(ab=(X?ac.prev():ac.next())){if(aa[ab.nodeName.toLowerCase()]){break}if(ab.nodeType===3&&tinymce.trim(ab.nodeValue).length>0){break}if(s(ab)==="false"){if(!m){T(ab)}return true}}if(l(ab)){return true}return false}W=v.getRng(true);V=W.startContainer;Z=W.startOffset;V=r(V)||V;if(v.isCollapsed()){if(U=l(V)){T(U);return false}if(V.nodeType==3&&(X?Z>0:Z124)&&G!=i.DELETE&&G!=i.BACKSPACE){if((tinymce.isMac?Q.metaKey:Q.ctrlKey)&&(G==67||G==88||G==86)){return}Q.preventDefault();if(G==i.LEFT||G==i.RIGHT){var C=G==i.LEFT;if(D.dom.isBlock(S)){var H=C?S.previousSibling:S.nextSibling;var N=new h(H,H);var L=C?N.prev():N.next();K(L,!C)}else{K(S,C)}}}else{if(G==i.LEFT||G==i.RIGHT||G==i.BACKSPACE||G==i.DELETE){J=r(y);if(J){O(G,J,Q)}if((G==i.BACKSPACE||G==i.DELETE)&&!P(G==i.BACKSPACE)){Q.preventDefault();return false}if(m&&I){var R=confirm(D.getLang("noneditable.confirm_delete"));if(!R){Q.preventDefault();return false}}}}}t.onMouseUp.addToTop(w);t.onMouseDown.addToTop(w);t.onKeyDown.addToTop(n);t.onKeyUp.addToTop(w)}function a(k){return" "+tinymce.trim(k.getParam("noneditable_editable_class","mceEditable"))+" "}function f(k){return" "+tinymce.trim(k.getParam("noneditable_noneditable_class","mceNonEditable"))+" "}tinymce.PluginManager.requireLangPack("noneditable");tinymce.create("tinymce.plugins.NonEditablePlugin",{init:function(l){function k(n,o){var p=b.length,q=o.content,m=tinymce.trim(j);if(o.format=="raw"){return}while(p--){q=q.replace(b[p],function(t){var s=arguments,r=s[s.length-2];if(r>0&&q.charAt(r-1)=='"'){return t}return''+n.dom.encode(typeof(s[1])==="string"?s[1]:s[0])+""})}o.content=q}e=a(l);j=f(l);b=l.getParam("noneditable_regexp");if(b&&!b.length){b=[b]}l.onPreInit.add(function(){g(l);if(b){l.selection.onBeforeSetContent.add(k);l.onBeforeSetContent.add(k)}l.parser.addAttributeFilter("class",function(m){var n=m.length,o,p;while(n--){p=m[n];o=" "+p.attr("class")+" ";if(o.indexOf(e)!==-1){p.attr(c,"true")}else{if(o.indexOf(j)!==-1){p.attr(c,"false")}}}});l.serializer.addAttributeFilter(c,function(m){var n=m.length,o;while(n--){o=m[n];if(b&&o.attr("data-mce-content")){o.name="#text";o.type=3;o.raw=true;o.value=o.attr("data-mce-content")}else{o.attr(d,null);o.attr(c,null)}}});l.parser.addAttributeFilter(d,function(m){var n=m.length,o;while(n--){o=m[n];o.attr(c,o.attr(d));o.attr(d,null)}})})},getInfo:function(){return{longname:"Non editable elements",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("noneditable",tinymce.plugins.NonEditablePlugin)})(); +(function(){var b=tinymce.each,a=tinymce.html.Node;tinymce.create("tinymce.plugins.FullPagePlugin",{init:function(c,d){var e=this;e.editor=c;c.addCommand("mceFullPageProperties",function(){c.windowManager.open({file:d+"/fullpage.htm",width:430+parseInt(c.getLang("fullpage.delta_width",0)),height:495+parseInt(c.getLang("fullpage.delta_height",0)),inline:1},{plugin_url:d,data:e._htmlToData()})});c.addButton("fullpage",{title:"fullpage.desc",cmd:"mceFullPageProperties"});c.onBeforeSetContent.add(e._setContent,e);c.onGetContent.add(e._getContent,e)},getInfo:function(){return{longname:"Fullpage",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullpage",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_htmlToData:function(){var e=this._parseHeader(),g={},h,f,d=this.editor;function c(k,i){var j=k.attr(i);return j||""}g.fontface=d.getParam("fullpage_default_fontface","");g.fontsize=d.getParam("fullpage_default_fontsize","");h=e.firstChild;if(h.type==7){g.xml_pi=true;f=/encoding="([^"]+)"/.exec(h.value);if(f){g.docencoding=f[1]}}h=e.getAll("#doctype")[0];if(h){g.doctype=""}h=e.getAll("title")[0];if(h&&h.firstChild){g.metatitle=h.firstChild.value}b(e.getAll("meta"),function(l){var j=l.attr("name"),i=l.attr("http-equiv"),k;if(j){g["meta"+j.toLowerCase()]=l.attr("content")}else{if(i=="Content-Type"){k=/charset\s*=\s*(.*)\s*/gi.exec(l.attr("content"));if(k){g.docencoding=k[1]}}}});h=e.getAll("html")[0];if(h){g.langcode=c(h,"lang")||c(h,"xml:lang")}h=e.getAll("link")[0];if(h&&h.attr("rel")=="stylesheet"){g.stylesheet=h.attr("href")}h=e.getAll("body")[0];if(h){g.langdir=c(h,"dir");g.style=c(h,"style");g.visited_color=c(h,"vlink");g.link_color=c(h,"link");g.active_color=c(h,"alink")}return g},_dataToHtml:function(g){var f,d,h,j,k,e=this.editor.dom;function c(n,l,m){n.attr(l,m?m:undefined)}function i(l){if(d.firstChild){d.insert(l,d.firstChild)}else{d.append(l)}}f=this._parseHeader();d=f.getAll("head")[0];if(!d){j=f.getAll("html")[0];d=new a("head",1);if(j.firstChild){j.insert(d,j.firstChild,true)}else{j.append(d)}}j=f.firstChild;if(g.xml_pi){k='version="1.0"';if(g.docencoding){k+=' encoding="'+g.docencoding+'"'}if(j.type!=7){j=new a("xml",7);f.insert(j,f.firstChild,true)}j.value=k}else{if(j&&j.type==7){j.remove()}}j=f.getAll("#doctype")[0];if(g.doctype){if(!j){j=new a("#doctype",10);if(g.xml_pi){f.insert(j,f.firstChild)}else{i(j)}}j.value=g.doctype.substring(9,g.doctype.length-1)}else{if(j){j.remove()}}j=f.getAll("title")[0];if(g.metatitle){if(!j){j=new a("title",1);j.append(new a("#text",3)).value=g.metatitle;i(j)}}if(g.docencoding){j=null;b(f.getAll("meta"),function(l){if(l.attr("http-equiv")=="Content-Type"){j=l}});if(!j){j=new a("meta",1);j.attr("http-equiv","Content-Type");j.shortEnded=true;i(j)}j.attr("content","text/html; charset="+g.docencoding)}b("keywords,description,author,copyright,robots".split(","),function(m){var l=f.getAll("meta"),n,p,o=g["meta"+m];for(n=0;n"))},_parseHeader:function(){return new tinymce.html.DomParser({validate:false,root_name:"#document"}).parse(this.head)},_setContent:function(g,d){var m=this,i,c,h=d.content,f,l="",e=m.editor.dom,j;function k(n){return n.replace(/<\/?[A-Z]+/g,function(o){return o.toLowerCase()})}if(d.format=="raw"&&m.head){return}if(d.source_view&&g.getParam("fullpage_hide_in_source_view")){return}h=h.replace(/<(\/?)BODY/gi,"<$1body");i=h.indexOf("",i);m.head=k(h.substring(0,i+1));c=h.indexOf("\n"}f=m._parseHeader();b(f.getAll("style"),function(n){if(n.firstChild){l+=n.firstChild.value}});j=f.getAll("body")[0];if(j){e.setAttribs(m.editor.getBody(),{style:j.attr("style")||"",dir:j.attr("dir")||"",vLink:j.attr("vlink")||"",link:j.attr("link")||"",aLink:j.attr("alink")||""})}e.remove("fullpage_styles");if(l){e.add(m.editor.getDoc().getElementsByTagName("head")[0],"style",{id:"fullpage_styles"},l);j=e.get("fullpage_styles");if(j.styleSheet){j.styleSheet.cssText=l}}},_getDefaultHeader:function(){var f="",c=this.editor,e,d="";if(c.getParam("fullpage_default_xml_pi")){f+='\n'}f+=c.getParam("fullpage_default_doctype",'');f+="\n\n\n";if(e=c.getParam("fullpage_default_title")){f+=""+e+"\n"}if(e=c.getParam("fullpage_default_encoding")){f+='\n'}if(e=c.getParam("fullpage_default_font_family")){d+="font-family: "+e+";"}if(e=c.getParam("fullpage_default_font_size")){d+="font-size: "+e+";"}if(e=c.getParam("fullpage_default_text_color")){d+="color: "+e+";"}f+="\n\n";return f},_getContent:function(d,e){var c=this;if(!e.source_view||!d.getParam("fullpage_hide_in_source_view")){e.content=tinymce.trim(c.head)+"\n"+tinymce.trim(e.content)+"\n"+tinymce.trim(c.foot)}}});tinymce.PluginManager.add("fullpage",tinymce.plugins.FullPagePlugin)})(); +(function(){function a(b){do{if(b.className&&b.className.indexOf("mceItemLayer")!=-1){return b}}while(b=b.parentNode)}tinymce.create("tinymce.plugins.Layer",{init:function(b,c){var d=this;d.editor=b;b.addCommand("mceInsertLayer",d._insertLayer,d);b.addCommand("mceMoveForward",function(){d._move(1)});b.addCommand("mceMoveBackward",function(){d._move(-1)});b.addCommand("mceMakeAbsolute",function(){d._toggleAbsolute()});b.addButton("moveforward",{title:"layer.forward_desc",cmd:"mceMoveForward"});b.addButton("movebackward",{title:"layer.backward_desc",cmd:"mceMoveBackward"});b.addButton("absolute",{title:"layer.absolute_desc",cmd:"mceMakeAbsolute"});b.addButton("insertlayer",{title:"layer.insertlayer_desc",cmd:"mceInsertLayer"});b.onInit.add(function(){var e=b.dom;if(tinymce.isIE){b.getDoc().execCommand("2D-Position",false,true)}});b.onMouseUp.add(function(f,h){var g=a(h.target);if(g){f.dom.setAttrib(g,"data-mce-style","")}});b.onMouseDown.add(function(f,j){var h=j.target,i=f.getDoc(),g;if(tinymce.isGecko){if(a(h)){if(i.designMode!=="on"){i.designMode="on";h=i.body;g=h.parentNode;g.removeChild(h);g.appendChild(h)}}else{if(i.designMode=="on"){i.designMode="off"}}}});b.onNodeChange.add(d._nodeChange,d);b.onVisualAid.add(d._visualAid,d)},getInfo:function(){return{longname:"Layer",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/layer",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_nodeChange:function(c,b,f){var d,e;d=this._getParentLayer(f);e=c.dom.getParent(f,"DIV,P,IMG");if(!e){b.setDisabled("absolute",1);b.setDisabled("moveforward",1);b.setDisabled("movebackward",1)}else{b.setDisabled("absolute",0);b.setDisabled("moveforward",!d);b.setDisabled("movebackward",!d);b.setActive("absolute",d&&d.style.position.toLowerCase()=="absolute")}},_visualAid:function(b,d,c){var f=b.dom;tinymce.each(f.select("div,p",d),function(g){if(/^(absolute|relative|fixed)$/i.test(g.style.position)){if(c){f.addClass(g,"mceItemVisualAid")}else{f.removeClass(g,"mceItemVisualAid")}f.addClass(g,"mceItemLayer")}})},_move:function(j){var c=this.editor,g,h=[],f=this._getParentLayer(c.selection.getNode()),e=-1,k=-1,b;b=[];tinymce.walk(c.getBody(),function(d){if(d.nodeType==1&&/^(absolute|relative|static)$/i.test(d.style.position)){b.push(d)}},"childNodes");for(g=0;g-1){b[e].style.zIndex=h[k];b[k].style.zIndex=h[e]}else{if(h[e]>0){b[e].style.zIndex=h[e]-1}}}else{for(g=0;gh[e]){k=g;break}}if(k>-1){b[e].style.zIndex=h[k];b[k].style.zIndex=h[e]}else{b[e].style.zIndex=h[e]+1}}c.execCommand("mceRepaint")},_getParentLayer:function(b){return this.editor.dom.getParent(b,function(c){return c.nodeType==1&&/^(absolute|relative|static)$/i.test(c.style.position)})},_insertLayer:function(){var c=this.editor,e=c.dom,d=e.getPos(e.getParent(c.selection.getNode(),"*")),b=c.getBody();c.dom.add(b,"div",{style:{position:"absolute",left:d.x,top:(d.y>20?d.y:20),width:100,height:100},"class":"mceItemVisualAid mceItemLayer"},c.selection.getContent()||c.getLang("layer.content"));if(tinymce.isIE){e.setHTML(b,b.innerHTML)}},_toggleAbsolute:function(){var b=this.editor,c=this._getParentLayer(b.selection.getNode());if(!c){c=b.dom.getParent(b.selection.getNode(),"DIV,P,IMG")}if(c){if(c.style.position.toLowerCase()=="absolute"){b.dom.setStyles(c,{position:"",left:"",top:"",width:"",height:""});b.dom.removeClass(c,"mceItemVisualAid");b.dom.removeClass(c,"mceItemLayer")}else{if(c.style.left==""){c.style.left=20+"px"}if(c.style.top==""){c.style.top=20+"px"}if(c.style.width==""){c.style.width=c.width?(c.width+"px"):"100px"}if(c.style.height==""){c.style.height=c.height?(c.height+"px"):"100px"}c.style.position="absolute";b.dom.setAttrib(c,"data-mce-style","");b.addVisual(b.getBody())}b.execCommand("mceRepaint");b.nodeChanged()}}});tinymce.PluginManager.add("layer",tinymce.plugins.Layer)})(); +(function(a){a.onAddEditor.addToTop(function(c,b){b.settings.inline_styles=false});a.create("tinymce.plugins.LegacyOutput",{init:function(b){b.onInit.add(function(){var c="p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",e=a.explode(b.settings.font_size_style_values),d=b.schema;b.formatter.register({alignleft:{selector:c,attributes:{align:"left"}},aligncenter:{selector:c,attributes:{align:"center"}},alignright:{selector:c,attributes:{align:"right"}},alignfull:{selector:c,attributes:{align:"justify"}},bold:[{inline:"b",remove:"all"},{inline:"strong",remove:"all"},{inline:"span",styles:{fontWeight:"bold"}}],italic:[{inline:"i",remove:"all"},{inline:"em",remove:"all"},{inline:"span",styles:{fontStyle:"italic"}}],underline:[{inline:"u",remove:"all"},{inline:"span",styles:{textDecoration:"underline"},exact:true}],strikethrough:[{inline:"strike",remove:"all"},{inline:"span",styles:{textDecoration:"line-through"},exact:true}],fontname:{inline:"font",attributes:{face:"%value"}},fontsize:{inline:"font",attributes:{size:function(f){return a.inArray(e,f.value)+1}}},forecolor:{inline:"font",attributes:{color:"%value"}},hilitecolor:{inline:"font",styles:{backgroundColor:"%value"}}});a.each("b,i,u,strike".split(","),function(f){d.addValidElements(f+"[*]")});if(!d.getElementRule("font")){d.addValidElements("font[face|size|color|style]")}a.each(c.split(","),function(f){var h=d.getElementRule(f),g;if(h){if(!h.attributes.align){h.attributes.align={};h.attributesOrder.push("align")}}});b.onNodeChange.add(function(g,k){var j,f,h,i;f=g.dom.getParent(g.selection.getNode(),"font");if(f){h=f.face;i=f.size}if(j=k.get("fontselect")){j.select(function(l){return l==h})}if(j=k.get("fontsizeselect")){j.select(function(m){var l=a.inArray(e,m.fontSize);return l+1==i})}})})},getInfo:function(){return{longname:"LegacyOutput",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/legacyoutput",version:a.majorVersion+"."+a.minorVersion}}});a.PluginManager.add("legacyoutput",a.plugins.LegacyOutput)})(tinymce); +(function(){var b=tinymce.DOM;var a=function(d,f,e){var c=function(g){var i=d.controlManager.get(g);var h=f.controlManager.get(g);if(i&&h){h.displayColor(i.value)}};c("forecolor");c("backcolor");f.setContent(d.getContent({format:"raw"}),{format:"raw"});f.selection.moveToBookmark(e);if(d.plugins.spellchecker&&f.plugins.spellchecker){f.plugins.spellchecker.setLanguage(d.plugins.spellchecker.selectedLang)}};tinymce.create("tinymce.plugins.FullScreenPlugin",{init:function(i,c){var l=this,m={},k=b.doc.documentElement,d,o,h,g,f,e,j;i.addCommand("mceFullScreen",function(){var q,r;if(i.getParam("fullscreen_is_enabled")){if(i.getParam("fullscreen_new_window")){closeFullscreen()}else{b.win.setTimeout(function(){var t=i;var s=tinyMCE.get(t.getParam("fullscreen_editor_id"));s.plugins.fullscreen.saveState(t);tinyMCE.remove(t)},10)}return}if(i.getParam("fullscreen_new_window")){l.fullscreenSettings={bookmark:i.selection.getBookmark()};q=b.win.open(c+"/fullscreen.htm","mceFullScreenPopup","fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width="+screen.availWidth+",height="+screen.availHeight);try{q.resizeTo(screen.availWidth,screen.availHeight)}catch(p){}}else{o=b.getStyle(b.doc.body,"overflow",1)||"auto";h=b.getStyle(k,"overflow",1);d=b.getViewPort();g=d.x;f=d.y;if(tinymce.isOpera&&o=="visible"){o="auto"}if(tinymce.isIE&&o=="scroll"){o="auto"}if(tinymce.isIE&&(h=="visible"||h=="scroll")){h="auto"}if(o=="0px"){o=""}b.setStyle(b.doc.body,"overflow","hidden");k.style.overflow="hidden";d=b.getViewPort();b.win.scrollTo(0,0);if(tinymce.isIE){d.h-=1}if(tinymce.isIE6||document.compatMode=="BackCompat"){e="absolute;top:"+d.y}else{e="fixed;top:0"}n=b.add(b.doc.body,"div",{id:"mce_fullscreen_container",style:"position:"+e+";left:0;width:"+d.w+"px;height:"+d.h+"px;z-index:200000;"});b.add(n,"div",{id:"mce_fullscreen"});tinymce.each(i.settings,function(s,t){m[t]=s});m.id="mce_fullscreen";m.width=n.clientWidth;m.height=n.clientHeight-15;m.fullscreen_is_enabled=true;m.fullscreen_editor_id=i.id;m.theme_advanced_resizing=false;m.save_onsavecallback=function(){i.setContent(tinyMCE.get(m.id).getContent());i.execCommand("mceSave")};tinymce.each(i.getParam("fullscreen_settings"),function(t,s){m[s]=t});l.fullscreenSettings={bookmark:i.selection.getBookmark(),fullscreen_overflow:o,fullscreen_html_overflow:h,fullscreen_scrollx:g,fullscreen_scrolly:f};if(m.theme_advanced_toolbar_location==="external"){m.theme_advanced_toolbar_location="top"}tinyMCE.oldSettings=tinyMCE.settings;l.fullscreenEditor=new tinymce.Editor("mce_fullscreen",m);l.fullscreenEditor.onInit.add(function(){l.loadState(l.fullscreenEditor)});l.fullscreenEditor.render();l.fullscreenElement=new tinymce.dom.Element("mce_fullscreen_container");l.fullscreenElement.update();l.resizeFunc=tinymce.dom.Event.add(b.win,"resize",function(){var v=tinymce.DOM.getViewPort(),t=l.fullscreenEditor,s,u;s=t.dom.getSize(t.getContainer().getElementsByTagName("table")[0]);u=t.dom.getSize(t.getContainer().getElementsByTagName("iframe")[0]);t.theme.resizeTo(v.w-s.w+u.w,v.h-s.h+u.h)})}});i.addButton("fullscreen",{title:"fullscreen.desc",cmd:"mceFullScreen"});i.onNodeChange.add(function(q,p){p.setActive("fullscreen",q.getParam("fullscreen_is_enabled"))});l.loadState=function(p){if(!(p&&l.fullscreenSettings)){throw"No fullscreen editor to load to"}a(i,p,l.fullscreenSettings.bookmark);p.focus()};l.saveState=function(q){if(!(q&&l.fullscreenSettings)){throw"No fullscreen editor to restore from"}var p=l.fullscreenSettings;a(q,i,q.selection.getBookmark());if(!i.getParam("fullscreen_new_window")){tinymce.dom.Event.remove(b.win,"resize",l.resizeFunc);delete l.resizeFunc;b.remove("mce_fullscreen_container");b.doc.documentElement.style.overflow=p.fullscreen_html_overflow;b.setStyle(b.doc.body,"overflow",p.fullscreen_overflow);b.win.scrollTo(p.fullscreen_scrollx,p.fullscreen_scrolly)}tinyMCE.settings=tinyMCE.oldSettings;delete tinyMCE.oldSettings;delete l.fullscreenEditor;delete l.fullscreenElement;delete l.fullscreenSettings;b.win.setTimeout(function(){i.selection.moveToBookmark(j);i.focus()},10)}},getInfo:function(){return{longname:"Fullscreen",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("fullscreen",tinymce.plugins.FullScreenPlugin)})(); +(function(){tinymce.create("tinymce.plugins.IESpell",{init:function(a,b){var c=this,d;if(!tinymce.isIE){return}c.editor=a;a.addCommand("mceIESpell",function(){try{d=new ActiveXObject("ieSpell.ieSpellExtension");d.CheckDocumentNode(a.getDoc().documentElement)}catch(f){if(f.number==-2146827859){a.windowManager.confirm(a.getLang("iespell.download"),function(e){if(e){window.open("http://www.iespell.com/download.php","ieSpellDownload","")}})}else{a.windowManager.alert("Error Loading ieSpell: Exception "+f.number)}}});a.addButton("iespell",{title:"iespell.iespell_desc",cmd:"mceIESpell"})},getInfo:function(){return{longname:"IESpell (IE Only)",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/iespell",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("iespell",tinymce.plugins.IESpell)})(); +(function(){var d=tinymce.DOM,b=tinymce.dom.Element,a=tinymce.dom.Event,e=tinymce.each,c=tinymce.is;tinymce.create("tinymce.plugins.InlinePopups",{init:function(f,g){f.onBeforeRenderUI.add(function(){f.windowManager=new tinymce.InlineWindowManager(f);d.loadCSS(g+"/skins/"+(f.settings.inlinepopups_skin||"clearlooks2")+"/window.css")})},getInfo:function(){return{longname:"InlinePopups",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.create("tinymce.InlineWindowManager:tinymce.WindowManager",{InlineWindowManager:function(f){var g=this;g.parent(f);g.zIndex=300000;g.count=0;g.windows={}},open:function(s,j){var z=this,i,k="",r=z.editor,g=0,v=0,h,m,o,q,l,x,y,n;s=s||{};j=j||{};if(!s.inline){return z.parent(s,j)}n=z._frontWindow();if(n&&d.get(n.id+"_ifr")){n.focussedElement=d.get(n.id+"_ifr").contentWindow.document.activeElement}if(!s.type){z.bookmark=r.selection.getBookmark(1)}i=d.uniqueId("mce_inlinepopups_");h=d.getViewPort();s.width=parseInt(s.width||320);s.height=parseInt(s.height||240)+(tinymce.isIE?8:0);s.min_width=parseInt(s.min_width||150);s.min_height=parseInt(s.min_height||100);s.max_width=parseInt(s.max_width||2000);s.max_height=parseInt(s.max_height||2000);s.left=s.left||Math.round(Math.max(h.x,h.x+(h.w/2)-(s.width/2)));s.top=s.top||Math.round(Math.max(h.y,h.y+(h.h/2)-(s.height/2)));s.movable=s.resizable=true;j.mce_width=s.width;j.mce_height=s.height;j.mce_inline=true;j.mce_window_id=i;j.mce_auto_focus=s.auto_focus;z.features=s;z.params=j;z.onOpen.dispatch(z,s,j);if(s.type){k+=" mceModal";if(s.type){k+=" mce"+s.type.substring(0,1).toUpperCase()+s.type.substring(1)}s.resizable=false}if(s.statusbar){k+=" mceStatusbar"}if(s.resizable){k+=" mceResizable"}if(s.minimizable){k+=" mceMinimizable"}if(s.maximizable){k+=" mceMaximizable"}if(s.movable){k+=" mceMovable"}z._addAll(d.doc.body,["div",{id:i,role:"dialog","aria-labelledby":s.type?i+"_content":i+"_title","class":(r.settings.inlinepopups_skin||"clearlooks2")+(tinymce.isIE&&window.getSelection?" ie9":""),style:"width:100px;height:100px"},["div",{id:i+"_wrapper","class":"mceWrapper"+k},["div",{id:i+"_top","class":"mceTop"},["div",{"class":"mceLeft"}],["div",{"class":"mceCenter"}],["div",{"class":"mceRight"}],["span",{id:i+"_title"},s.title||""]],["div",{id:i+"_middle","class":"mceMiddle"},["div",{id:i+"_left","class":"mceLeft",tabindex:"0"}],["span",{id:i+"_content"}],["div",{id:i+"_right","class":"mceRight",tabindex:"0"}]],["div",{id:i+"_bottom","class":"mceBottom"},["div",{"class":"mceLeft"}],["div",{"class":"mceCenter"}],["div",{"class":"mceRight"}],["span",{id:i+"_status"},"Content"]],["a",{"class":"mceMove",tabindex:"-1",href:"javascript:;"}],["a",{"class":"mceMin",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceMax",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceMed",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceClose",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{id:i+"_resize_n","class":"mceResize mceResizeN",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_s","class":"mceResize mceResizeS",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_w","class":"mceResize mceResizeW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_e","class":"mceResize mceResizeE",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_nw","class":"mceResize mceResizeNW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_ne","class":"mceResize mceResizeNE",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_sw","class":"mceResize mceResizeSW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_se","class":"mceResize mceResizeSE",tabindex:"-1",href:"javascript:;"}]]]);d.setStyles(i,{top:-10000,left:-10000});if(tinymce.isGecko){d.setStyle(i,"overflow","auto")}if(!s.type){g+=d.get(i+"_left").clientWidth;g+=d.get(i+"_right").clientWidth;v+=d.get(i+"_top").clientHeight;v+=d.get(i+"_bottom").clientHeight}d.setStyles(i,{top:s.top,left:s.left,width:s.width+g,height:s.height+v});y=s.url||s.file;if(y){if(tinymce.relaxedDomain){y+=(y.indexOf("?")==-1?"?":"&")+"mce_rdomain="+tinymce.relaxedDomain}y=tinymce._addVer(y)}if(!s.type){d.add(i+"_content","iframe",{id:i+"_ifr",src:'javascript:""',frameBorder:0,style:"border:0;width:10px;height:10px"});d.setStyles(i+"_ifr",{width:s.width,height:s.height});d.setAttrib(i+"_ifr","src",y)}else{d.add(i+"_wrapper","a",{id:i+"_ok","class":"mceButton mceOk",href:"javascript:;",onmousedown:"return false;"},"Ok");if(s.type=="confirm"){d.add(i+"_wrapper","a",{"class":"mceButton mceCancel",href:"javascript:;",onmousedown:"return false;"},"Cancel")}d.add(i+"_middle","div",{"class":"mceIcon"});d.setHTML(i+"_content",s.content.replace("\n","
"));a.add(i,"keyup",function(f){var p=27;if(f.keyCode===p){s.button_func(false);return a.cancel(f)}});a.add(i,"keydown",function(f){var t,p=9;if(f.keyCode===p){t=d.select("a.mceCancel",i+"_wrapper")[0];if(t&&t!==f.target){t.focus()}else{d.get(i+"_ok").focus()}return a.cancel(f)}})}o=a.add(i,"mousedown",function(t){var u=t.target,f,p;f=z.windows[i];z.focus(i);if(u.nodeName=="A"||u.nodeName=="a"){if(u.className=="mceClose"){z.close(null,i);return a.cancel(t)}else{if(u.className=="mceMax"){f.oldPos=f.element.getXY();f.oldSize=f.element.getSize();p=d.getViewPort();p.w-=2;p.h-=2;f.element.moveTo(p.x,p.y);f.element.resizeTo(p.w,p.h);d.setStyles(i+"_ifr",{width:p.w-f.deltaWidth,height:p.h-f.deltaHeight});d.addClass(i+"_wrapper","mceMaximized")}else{if(u.className=="mceMed"){f.element.moveTo(f.oldPos.x,f.oldPos.y);f.element.resizeTo(f.oldSize.w,f.oldSize.h);f.iframeElement.resizeTo(f.oldSize.w-f.deltaWidth,f.oldSize.h-f.deltaHeight);d.removeClass(i+"_wrapper","mceMaximized")}else{if(u.className=="mceMove"){return z._startDrag(i,t,u.className)}else{if(d.hasClass(u,"mceResize")){return z._startDrag(i,t,u.className.substring(13))}}}}}}});q=a.add(i,"click",function(f){var p=f.target;z.focus(i);if(p.nodeName=="A"||p.nodeName=="a"){switch(p.className){case"mceClose":z.close(null,i);return a.cancel(f);case"mceButton mceOk":case"mceButton mceCancel":s.button_func(p.className=="mceButton mceOk");return a.cancel(f)}}});a.add([i+"_left",i+"_right"],"focus",function(p){var t=d.get(i+"_ifr");if(t){var f=t.contentWindow.document.body;var u=d.select(":input:enabled,*[tabindex=0]",f);if(p.target.id===(i+"_left")){u[u.length-1].focus()}else{u[0].focus()}}else{d.get(i+"_ok").focus()}});x=z.windows[i]={id:i,mousedown_func:o,click_func:q,element:new b(i,{blocker:1,container:r.getContainer()}),iframeElement:new b(i+"_ifr"),features:s,deltaWidth:g,deltaHeight:v};x.iframeElement.on("focus",function(){z.focus(i)});if(z.count==0&&z.editor.getParam("dialog_type","modal")=="modal"){d.add(d.doc.body,"div",{id:"mceModalBlocker","class":(z.editor.settings.inlinepopups_skin||"clearlooks2")+"_modalBlocker",style:{zIndex:z.zIndex-1}});d.show("mceModalBlocker");d.setAttrib(d.doc.body,"aria-hidden","true")}else{d.setStyle("mceModalBlocker","z-index",z.zIndex-1)}if(tinymce.isIE6||/Firefox\/2\./.test(navigator.userAgent)||(tinymce.isIE&&!d.boxModel)){d.setStyles("mceModalBlocker",{position:"absolute",left:h.x,top:h.y,width:h.w-2,height:h.h-2})}d.setAttrib(i,"aria-hidden","false");z.focus(i);z._fixIELayout(i,1);if(d.get(i+"_ok")){d.get(i+"_ok").focus()}z.count++;return x},focus:function(h){var g=this,f;if(f=g.windows[h]){f.zIndex=this.zIndex++;f.element.setStyle("zIndex",f.zIndex);f.element.update();h=h+"_wrapper";d.removeClass(g.lastId,"mceFocus");d.addClass(h,"mceFocus");g.lastId=h;if(f.focussedElement){f.focussedElement.focus()}else{if(d.get(h+"_ok")){d.get(f.id+"_ok").focus()}else{if(d.get(f.id+"_ifr")){d.get(f.id+"_ifr").focus()}}}}},_addAll:function(k,h){var g,l,f=this,j=tinymce.DOM;if(c(h,"string")){k.appendChild(j.doc.createTextNode(h))}else{if(h.length){k=k.appendChild(j.create(h[0],h[1]));for(g=2;gf){g=h;f=h.zIndex}});return g},setTitle:function(f,g){var h;f=this._findId(f);if(h=d.get(f+"_title")){h.innerHTML=d.encode(g)}},alert:function(g,f,j){var i=this,h;h=i.open({title:i,type:"alert",button_func:function(k){if(f){f.call(k||i,k)}i.close(null,h.id)},content:d.encode(i.editor.getLang(g,g)),inline:1,width:400,height:130})},confirm:function(g,f,j){var i=this,h;h=i.open({title:i,type:"confirm",button_func:function(k){if(f){f.call(k||i,k)}i.close(null,h.id)},content:d.encode(i.editor.getLang(g,g)),inline:1,width:400,height:130})},_findId:function(f){var g=this;if(typeof(f)=="string"){return f}e(g.windows,function(h){var i=d.get(h.id+"_ifr");if(i&&f==i.contentWindow){f=h.id;return false}});return f},_fixIELayout:function(i,h){var f,g;if(!tinymce.isIE6){return}e(["n","s","w","e","nw","ne","sw","se"],function(j){var k=d.get(i+"_resize_"+j);d.setStyles(k,{width:h?k.clientWidth:"",height:h?k.clientHeight:"",cursor:d.getStyle(k,"cursor",1)});d.setStyle(i+"_bottom","bottom","-1px");k=0});if(f=this.windows[i]){f.element.hide();f.element.show();e(d.select("div,a",i),function(k,j){if(k.currentStyle.backgroundImage!="none"){g=new Image();g.src=k.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/,"$1")}});d.get(i).style.filter=""}}});tinymce.PluginManager.add("inlinepopups",tinymce.plugins.InlinePopups)})(); +(function(){tinymce.create("tinymce.plugins.AutoResizePlugin",{init:function(a,c){var d=this,e=0;if(a.getParam("fullscreen_is_enabled")){return}function b(){var j,i=a.getDoc(),f=i.body,l=i.documentElement,h=tinymce.DOM,k=d.autoresize_min_height,g;g=tinymce.isIE?f.scrollHeight:(tinymce.isWebKit&&f.clientHeight==0?0:f.offsetHeight);if(g>d.autoresize_min_height){k=g}if(d.autoresize_max_height&&g>d.autoresize_max_height){k=d.autoresize_max_height;f.style.overflowY="auto";l.style.overflowY="auto"}else{f.style.overflowY="hidden";l.style.overflowY="hidden";f.scrollTop=0}if(k!==e){j=k-e;h.setStyle(h.get(a.id+"_ifr"),"height",k+"px");e=k;if(tinymce.isWebKit&&j<0){b()}}}d.editor=a;d.autoresize_min_height=parseInt(a.getParam("autoresize_min_height",a.getElement().offsetHeight));d.autoresize_max_height=parseInt(a.getParam("autoresize_max_height",0));a.onInit.add(function(f){f.dom.setStyle(f.getBody(),"paddingBottom",f.getParam("autoresize_bottom_margin",50)+"px")});a.onChange.add(b);a.onSetContent.add(b);a.onPaste.add(b);a.onKeyUp.add(b);a.onPostRender.add(b);if(a.getParam("autoresize_on_init",true)){a.onLoad.add(b);a.onLoadContent.add(b)}a.addCommand("mceAutoResize",b)},getInfo:function(){return{longname:"Auto Resize",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autoresize",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("autoresize",tinymce.plugins.AutoResizePlugin)})(); +(function(){var a=tinymce.dom.Event,c=tinymce.each,b=tinymce.DOM;tinymce.create("tinymce.plugins.ContextMenu",{init:function(f){var i=this,g,d,j,e;i.editor=f;d=f.settings.contextmenu_never_use_native;i.onContextMenu=new tinymce.util.Dispatcher(this);e=function(k){h(f,k)};g=f.onContextMenu.add(function(k,l){if((j!==0?j:l.ctrlKey)&&!d){return}a.cancel(l);if(l.target.nodeName=="IMG"){k.selection.select(l.target)}i._getMenu(k).showMenu(l.clientX||l.pageX,l.clientY||l.pageY);a.add(k.getDoc(),"click",e);k.nodeChanged()});f.onRemove.add(function(){if(i._menu){i._menu.removeAll()}});function h(k,l){j=0;if(l&&l.button==2){j=l.ctrlKey;return}if(i._menu){i._menu.removeAll();i._menu.destroy();a.remove(k.getDoc(),"click",e);i._menu=null}}f.onMouseDown.add(h);f.onKeyDown.add(h);f.onKeyDown.add(function(k,l){if(l.shiftKey&&!l.ctrlKey&&!l.altKey&&l.keyCode===121){a.cancel(l);g(k,l)}})},getInfo:function(){return{longname:"Contextmenu",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/contextmenu",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_getMenu:function(e){var g=this,d=g._menu,j=e.selection,f=j.isCollapsed(),h=j.getNode()||e.getBody(),i,k;if(d){d.removeAll();d.destroy()}k=b.getPos(e.getContentAreaContainer());d=e.controlManager.createDropMenu("contextmenu",{offset_x:k.x+e.getParam("contextmenu_offset_x",0),offset_y:k.y+e.getParam("contextmenu_offset_y",0),constrain:1,keyboard_focus:true});g._menu=d;d.add({title:"advanced.cut_desc",icon:"cut",cmd:"Cut"}).setDisabled(f);d.add({title:"advanced.copy_desc",icon:"copy",cmd:"Copy"}).setDisabled(f);d.add({title:"advanced.paste_desc",icon:"paste",cmd:"Paste"});if((h.nodeName=="A"&&!e.dom.getAttrib(h,"name"))||!f){d.addSeparator();d.add({title:"advanced.link_desc",icon:"link",cmd:e.plugins.advlink?"mceAdvLink":"mceLink",ui:true});d.add({title:"advanced.unlink_desc",icon:"unlink",cmd:"UnLink"})}d.addSeparator();d.add({title:"advanced.image_desc",icon:"image",cmd:e.plugins.advimage?"mceAdvImage":"mceImage",ui:true});d.addSeparator();i=d.addMenu({title:"contextmenu.align"});i.add({title:"contextmenu.left",icon:"justifyleft",cmd:"JustifyLeft"});i.add({title:"contextmenu.center",icon:"justifycenter",cmd:"JustifyCenter"});i.add({title:"contextmenu.right",icon:"justifyright",cmd:"JustifyRight"});i.add({title:"contextmenu.full",icon:"justifyfull",cmd:"JustifyFull"});g.onContextMenu.dispatch(g,d,h,f);return d}});tinymce.PluginManager.add("contextmenu",tinymce.plugins.ContextMenu)})(); +(function(){var a=tinymce.each;tinymce.create("tinymce.plugins.AdvListPlugin",{init:function(b,c){var d=this;d.editor=b;function e(g){var f=[];a(g.split(/,/),function(h){f.push({title:"advlist."+(h=="default"?"def":h.replace(/-/g,"_")),styles:{listStyleType:h=="default"?"":h}})});return f}d.numlist=b.getParam("advlist_number_styles")||e("default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman");d.bullist=b.getParam("advlist_bullet_styles")||e("default,circle,disc,square");if(tinymce.isIE&&/MSIE [2-7]/.test(navigator.userAgent)){d.isIE7=true}},createControl:function(d,b){var f=this,e,i,g=f.editor;if(d=="numlist"||d=="bullist"){if(f[d][0].title=="advlist.def"){i=f[d][0]}function c(j,l){var k=true;a(l.styles,function(n,m){if(g.dom.getStyle(j,m)!=n){k=false;return false}});return k}function h(){var k,l=g.dom,j=g.selection;k=l.getParent(j.getNode(),"ol,ul");if(!k||k.nodeName==(d=="bullist"?"OL":"UL")||c(k,i)){g.execCommand(d=="bullist"?"InsertUnorderedList":"InsertOrderedList")}if(i){k=l.getParent(j.getNode(),"ol,ul");if(k){l.setStyles(k,i.styles);k.removeAttribute("data-mce-style")}}g.focus()}e=b.createSplitButton(d,{title:"advanced."+d+"_desc","class":"mce_"+d,onclick:function(){h()}});e.onRenderMenu.add(function(j,k){k.onHideMenu.add(function(){if(f.bookmark){g.selection.moveToBookmark(f.bookmark);f.bookmark=0}});k.onShowMenu.add(function(){var n=g.dom,m=n.getParent(g.selection.getNode(),"ol,ul"),l;if(m||i){l=f[d];a(k.items,function(o){var p=true;o.setSelected(0);if(m&&!o.isDisabled()){a(l,function(q){if(q.id==o.id){if(!c(m,q)){p=false;return false}}});if(p){o.setSelected(1)}}});if(!m){k.items[i.id].setSelected(1)}}g.focus();if(tinymce.isIE){f.bookmark=g.selection.getBookmark(1)}});k.add({id:g.dom.uniqueId(),title:"advlist.types","class":"mceMenuItemTitle",titleItem:true}).setDisabled(1);a(f[d],function(l){if(f.isIE7&&l.styles.listStyleType=="lower-greek"){return}l.id=g.dom.uniqueId();k.add({id:l.id,title:l.title,onclick:function(){i=l;h()}})})});return e}},getInfo:function(){return{longname:"Advanced lists",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlist",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("advlist",tinymce.plugins.AdvListPlugin)})(); +(function(){tinymce.create("tinymce.plugins.AutolinkPlugin",{init:function(a,b){var c=this;a.onKeyDown.addToTop(function(d,f){if(f.keyCode==13){return c.handleEnter(d)}});if(tinyMCE.isIE){return}a.onKeyPress.add(function(d,f){if(f.which==41){return c.handleEclipse(d)}});a.onKeyUp.add(function(d,f){if(f.keyCode==32){return c.handleSpacebar(d)}})},handleEclipse:function(a){this.parseCurrentLine(a,-1,"(",true)},handleSpacebar:function(a){this.parseCurrentLine(a,0,"",true)},handleEnter:function(a){this.parseCurrentLine(a,-1,"",false)},parseCurrentLine:function(i,d,b,g){var a,f,c,n,k,m,h,e,j;a=i.selection.getRng(true).cloneRange();if(a.startOffset<5){e=a.endContainer.previousSibling;if(e==null){if(a.endContainer.firstChild==null||a.endContainer.firstChild.nextSibling==null){return}e=a.endContainer.firstChild.nextSibling}j=e.length;a.setStart(e,j);a.setEnd(e,j);if(a.endOffset<5){return}f=a.endOffset;n=e}else{n=a.endContainer;if(n.nodeType!=3&&n.firstChild){while(n.nodeType!=3&&n.firstChild){n=n.firstChild}if(n.nodeType==3){a.setStart(n,0);a.setEnd(n,n.nodeValue.length)}}if(a.endOffset==1){f=2}else{f=a.endOffset-1-d}}c=f;do{a.setStart(n,f>=2?f-2:0);a.setEnd(n,f>=1?f-1:0);f-=1}while(a.toString()!=" "&&a.toString()!=""&&a.toString().charCodeAt(0)!=160&&(f-2)>=0&&a.toString()!=b);if(a.toString()==b||a.toString().charCodeAt(0)==160){a.setStart(n,f);a.setEnd(n,c);f+=1}else{if(a.startOffset==0){a.setStart(n,0);a.setEnd(n,c)}else{a.setStart(n,f);a.setEnd(n,c)}}var m=a.toString();if(m.charAt(m.length-1)=="."){a.setEnd(n,c-1)}m=a.toString();h=m.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+-]+@)(.+)$/i);if(h){if(h[1]=="www."){h[1]="http://www."}else{if(/@$/.test(h[1])&&!/^mailto:/.test(h[1])){h[1]="mailto:"+h[1]}}k=i.selection.getBookmark();i.selection.setRng(a);tinyMCE.execCommand("createlink",false,h[1]+h[2]);i.selection.moveToBookmark(k);i.nodeChanged();if(tinyMCE.isWebKit){i.selection.collapse(false);var l=Math.min(n.length,c+1);a.setStart(n,l);a.setEnd(n,l);i.selection.setRng(a)}}},getInfo:function(){return{longname:"Autolink",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autolink",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("autolink",tinymce.plugins.AutolinkPlugin)})(); +(function(){tinymce.create("tinymce.plugins.Directionality",{init:function(b,c){var d=this;d.editor=b;function a(e){var h=b.dom,g,f=b.selection.getSelectedBlocks();if(f.length){g=h.getAttrib(f[0],"dir");tinymce.each(f,function(i){if(!h.getParent(i.parentNode,"*[dir='"+e+"']",h.getRoot())){if(g!=e){h.setAttrib(i,"dir",e)}else{h.setAttrib(i,"dir",null)}}});b.nodeChanged()}}b.addCommand("mceDirectionLTR",function(){a("ltr")});b.addCommand("mceDirectionRTL",function(){a("rtl")});b.addButton("ltr",{title:"directionality.ltr_desc",cmd:"mceDirectionLTR"});b.addButton("rtl",{title:"directionality.rtl_desc",cmd:"mceDirectionRTL"});b.onNodeChange.add(d._nodeChange,d)},getInfo:function(){return{longname:"Directionality",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_nodeChange:function(b,a,e){var d=b.dom,c;e=d.getParent(e,d.isBlock);if(!e){a.setDisabled("ltr",1);a.setDisabled("rtl",1);return}c=d.getAttrib(e,"dir");a.setActive("ltr",c=="ltr");a.setDisabled("ltr",0);a.setActive("rtl",c=="rtl");a.setDisabled("rtl",0)}});tinymce.PluginManager.add("directionality",tinymce.plugins.Directionality)})(); +(function(a){a.create("tinymce.plugins.EmotionsPlugin",{init:function(b,c){b.addCommand("mceEmotion",function(){b.windowManager.open({file:c+"/emotions.htm",width:250+parseInt(b.getLang("emotions.delta_width",0)),height:160+parseInt(b.getLang("emotions.delta_height",0)),inline:1},{plugin_url:c})});b.addButton("emotions",{title:"emotions.emotions_desc",cmd:"mceEmotion"})},getInfo:function(){return{longname:"Emotions",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/emotions",version:a.majorVersion+"."+a.minorVersion}}});a.PluginManager.add("emotions",a.plugins.EmotionsPlugin)})(tinymce); +(function(i){var k=i.DOM,h=i.dom.Event,c=i.extend,f=i.each,a=i.util.Cookie,e,d=i.explode;var g=function(m,n){var o=n.theme_advanced_default_font_size;var l=n.theme_advanced_default_font_family;if(o){m.style.fontSize=o}if(l){m.style.fontFamily=l}};var j=function(m){var n=m.theme_advanced_default_font_size;var l=m.theme_advanced_default_font_family;return !!(n||l)};function b(r,o){var m,n,q=r.dom,l="",p,t;previewStyles=r.settings.preview_styles;if(previewStyles===false){return""}if(!previewStyles){previewStyles="font-family font-size font-weight text-decoration text-transform color background-color"}function s(u){return u.replace(/%(\w+)/g,"")}m=o.block||o.inline||"span";n=q.create(m);f(o.styles,function(v,u){v=s(v);if(v){q.setStyle(n,u,v)}});f(o.attributes,function(v,u){v=s(v);if(v){q.setAttrib(n,u,v)}});f(o.classes,function(u){u=s(u);if(!q.hasClass(n,u)){q.addClass(n,u)}});q.setStyles(n,{position:"absolute",left:-65535});r.getBody().appendChild(n);p=q.getStyle(r.getBody(),"fontSize",true);p=/px$/.test(p)?parseInt(p,10):0;f(previewStyles.split(" "),function(u){var v=q.getStyle(n,u,true);if(u=="background-color"&&/transparent|rgba\s*\([^)]+,\s*0\)/.test(v)){v=q.getStyle(r.getBody(),u,true);if(q.toHex(v).toLowerCase()=="#ffffff"){return}}if(u=="font-size"){if(/em|%$/.test(v)){if(p===0){return}v=parseFloat(v,10)/(/%$/.test(v)?100:1);v=(v*p)+"px"}}l+=u+":"+v+";"});q.remove(n);return l}i.ThemeManager.requireLangPack("advanced");i.create("tinymce.themes.AdvancedTheme",{sizes:[8,10,12,14,18,24,36],controls:{bold:["bold_desc","Bold"],italic:["italic_desc","Italic"],underline:["underline_desc","Underline"],strikethrough:["striketrough_desc","Strikethrough"],justifyleft:["justifyleft_desc","JustifyLeft"],justifycenter:["justifycenter_desc","JustifyCenter"],justifyright:["justifyright_desc","JustifyRight"],justifyfull:["justifyfull_desc","JustifyFull"],bullist:["bullist_desc","InsertUnorderedList"],numlist:["numlist_desc","InsertOrderedList"],outdent:["outdent_desc","Outdent"],indent:["indent_desc","Indent"],cut:["cut_desc","Cut"],copy:["copy_desc","Copy"],paste:["paste_desc","Paste"],undo:["undo_desc","Undo"],redo:["redo_desc","Redo"],link:["link_desc","mceLink"],unlink:["unlink_desc","unlink"],image:["image_desc","mceImage"],cleanup:["cleanup_desc","mceCleanup"],help:["help_desc","mceHelp"],code:["code_desc","mceCodeEditor"],hr:["hr_desc","InsertHorizontalRule"],removeformat:["removeformat_desc","RemoveFormat"],sub:["sub_desc","subscript"],sup:["sup_desc","superscript"],forecolor:["forecolor_desc","ForeColor"],forecolorpicker:["forecolor_desc","mceForeColor"],backcolor:["backcolor_desc","HiliteColor"],backcolorpicker:["backcolor_desc","mceBackColor"],charmap:["charmap_desc","mceCharMap"],visualaid:["visualaid_desc","mceToggleVisualAid"],anchor:["anchor_desc","mceInsertAnchor"],newdocument:["newdocument_desc","mceNewDocument"],blockquote:["blockquote_desc","mceBlockQuote"]},stateControls:["bold","italic","underline","strikethrough","bullist","numlist","justifyleft","justifycenter","justifyright","justifyfull","sub","sup","blockquote"],init:function(m,n){var p=this,q,l,r;p.editor=m;p.url=n;p.onResolveName=new i.util.Dispatcher(this);q=m.settings;m.forcedHighContrastMode=m.settings.detect_highcontrast&&p._isHighContrast();m.settings.skin=m.forcedHighContrastMode?"highcontrast":m.settings.skin;if(!q.theme_advanced_buttons1){q=c({theme_advanced_buttons1:"bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect",theme_advanced_buttons2:"bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code",theme_advanced_buttons3:"hr,removeformat,visualaid,|,sub,sup,|,charmap"},q)}p.settings=q=c({theme_advanced_path:true,theme_advanced_toolbar_location:"top",theme_advanced_blockformats:"p,address,pre,h1,h2,h3,h4,h5,h6",theme_advanced_toolbar_align:"left",theme_advanced_statusbar_location:"bottom",theme_advanced_fonts:"Andale Mono=andale mono,monospace;Arial=arial,helvetica,sans-serif;Arial Black=arial black,sans-serif;Book Antiqua=book antiqua,palatino,serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,palatino,serif;Helvetica=helvetica,arial,sans-serif;Impact=impact,sans-serif;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco,monospace;Times New Roman=times new roman,times,serif;Trebuchet MS=trebuchet ms,geneva,sans-serif;Verdana=verdana,geneva,sans-serif;Webdings=webdings;Wingdings=wingdings,zapf dingbats",theme_advanced_more_colors:1,theme_advanced_row_height:23,theme_advanced_resize_horizontal:1,theme_advanced_resizing_use_cookie:1,theme_advanced_font_sizes:"1,2,3,4,5,6,7",theme_advanced_font_selector:"span",theme_advanced_show_current_color:0,readonly:m.settings.readonly},q);if(!q.font_size_style_values){q.font_size_style_values="8pt,10pt,12pt,14pt,18pt,24pt,36pt"}if(i.is(q.theme_advanced_font_sizes,"string")){q.font_size_style_values=i.explode(q.font_size_style_values);q.font_size_classes=i.explode(q.font_size_classes||"");r={};m.settings.theme_advanced_font_sizes=q.theme_advanced_font_sizes;f(m.getParam("theme_advanced_font_sizes","","hash"),function(t,s){var o;if(s==t&&t>=1&&t<=7){s=t+" ("+p.sizes[t-1]+"pt)";o=q.font_size_classes[t-1];t=q.font_size_style_values[t-1]||(p.sizes[t-1]+"pt")}if(/^\s*\./.test(t)){o=t.replace(/\./g,"")}r[s]=o?{"class":o}:{fontSize:t}});q.theme_advanced_font_sizes=r}if((l=q.theme_advanced_path_location)&&l!="none"){q.theme_advanced_statusbar_location=q.theme_advanced_path_location}if(q.theme_advanced_statusbar_location=="none"){q.theme_advanced_statusbar_location=0}if(m.settings.content_css!==false){m.contentCSS.push(m.baseURI.toAbsolute(n+"/skins/"+m.settings.skin+"/content.css"))}m.onInit.add(function(){if(!m.settings.readonly){m.onNodeChange.add(p._nodeChanged,p);m.onKeyUp.add(p._updateUndoStatus,p);m.onMouseUp.add(p._updateUndoStatus,p);m.dom.bind(m.dom.getRoot(),"dragend",function(){p._updateUndoStatus(m)})}g(m.getBody(),m.settings)});m.onSetProgressState.add(function(t,o,u){var v,w=t.id,s;if(o){p.progressTimer=setTimeout(function(){v=t.getContainer();v=v.insertBefore(k.create("DIV",{style:"position:relative"}),v.firstChild);s=k.get(t.id+"_tbl");k.add(v,"div",{id:w+"_blocker","class":"mceBlocker",style:{width:s.clientWidth+2,height:s.clientHeight+2}});k.add(v,"div",{id:w+"_progress","class":"mceProgress",style:{left:s.clientWidth/2,top:s.clientHeight/2}})},u||0)}else{k.remove(w+"_blocker");k.remove(w+"_progress");clearTimeout(p.progressTimer)}});k.loadCSS(q.editor_css?m.documentBaseURI.toAbsolute(q.editor_css):n+"/skins/"+m.settings.skin+"/ui.css");if(q.skin_variant){k.loadCSS(n+"/skins/"+m.settings.skin+"/ui_"+q.skin_variant+".css")}},_isHighContrast:function(){var l,m=k.add(k.getRoot(),"div",{style:"background-color: rgb(171,239,86);"});l=(k.getStyle(m,"background-color",true)+"").toLowerCase().replace(/ /g,"");k.remove(m);return l!="rgb(171,239,86)"&&l!="#abef56"},createControl:function(p,l){var m,o;if(o=l.createControl(p)){return o}switch(p){case"styleselect":return this._createStyleSelect();case"formatselect":return this._createBlockFormats();case"fontselect":return this._createFontSelect();case"fontsizeselect":return this._createFontSizeSelect();case"forecolor":return this._createForeColorMenu();case"backcolor":return this._createBackColorMenu()}if((m=this.controls[p])){return l.createButton(p,{title:"advanced."+m[0],cmd:m[1],ui:m[2],value:m[3]})}},execCommand:function(n,m,o){var l=this["_"+n];if(l){l.call(this,m,o);return true}return false},_importClasses:function(n){var l=this.editor,m=l.controlManager.get("styleselect");if(m.getLength()==0){f(l.dom.getClasses(),function(s,p){var r="style_"+p,q;q={inline:"span",attributes:{"class":s["class"]},selector:"*"};l.formatter.register(r,q);m.add(s["class"],r,{style:function(){return b(l,q)}})})}},_createStyleSelect:function(q){var o=this,l=o.editor,m=l.controlManager,p;p=m.createListBox("styleselect",{title:"advanced.style_select",onselect:function(s){var t,n=[],r;f(p.items,function(u){n.push(u.value)});l.focus();l.undoManager.add();t=l.formatter.matchAll(n);i.each(t,function(u){if(!s||u==s){if(u){l.formatter.remove(u)}r=true}});if(!r){l.formatter.apply(s)}l.undoManager.add();l.nodeChanged();return false}});l.onPreInit.add(function(){var r=0,n=l.getParam("style_formats");if(n){f(n,function(s){var t,u=0;f(s,function(){u++});if(u>1){t=s.name=s.name||"style_"+(r++);l.formatter.register(t,s);p.add(s.title,t,{style:function(){return b(l,s)}})}else{p.add(s.title)}})}else{f(l.getParam("theme_advanced_styles","","hash"),function(v,u){var t,s;if(v){t="style_"+(r++);s={inline:"span",classes:v,selector:"*"};l.formatter.register(t,s);p.add(o.editor.translate(u),t,{style:function(){return b(l,s)}})}})}});if(p.getLength()==0){p.onPostRender.add(function(r,s){if(!p.NativeListBox){h.add(s.id+"_text","focus",o._importClasses,o);h.add(s.id+"_text","mousedown",o._importClasses,o);h.add(s.id+"_open","focus",o._importClasses,o);h.add(s.id+"_open","mousedown",o._importClasses,o)}else{h.add(s.id,"focus",o._importClasses,o)}})}return p},_createFontSelect:function(){var n,m=this,l=m.editor;n=l.controlManager.createListBox("fontselect",{title:"advanced.fontdefault",onselect:function(o){var p=n.items[n.selectedIndex];if(!o&&p){l.execCommand("FontName",false,p.value);return}l.execCommand("FontName",false,o);n.select(function(q){return o==q});if(p&&p.value==o){n.select(null)}return false}});if(n){f(l.getParam("theme_advanced_fonts",m.settings.theme_advanced_fonts,"hash"),function(p,o){n.add(l.translate(o),p,{style:p.indexOf("dings")==-1?"font-family:"+p:""})})}return n},_createFontSizeSelect:function(){var o=this,m=o.editor,p,n=0,l=[];p=m.controlManager.createListBox("fontsizeselect",{title:"advanced.font_size",onselect:function(q){var r=p.items[p.selectedIndex];if(!q&&r){r=r.value;if(r["class"]){m.formatter.toggle("fontsize_class",{value:r["class"]});m.undoManager.add();m.nodeChanged()}else{m.execCommand("FontSize",false,r.fontSize)}return}if(q["class"]){m.focus();m.undoManager.add();m.formatter.toggle("fontsize_class",{value:q["class"]});m.undoManager.add();m.nodeChanged()}else{m.execCommand("FontSize",false,q.fontSize)}p.select(function(s){return q==s});if(r&&(r.value.fontSize==q.fontSize||r.value["class"]&&r.value["class"]==q["class"])){p.select(null)}return false}});if(p){f(o.settings.theme_advanced_font_sizes,function(r,q){var s=r.fontSize;if(s>=1&&s<=7){s=o.sizes[parseInt(s)-1]+"pt"}p.add(q,r,{style:"font-size:"+s,"class":"mceFontSize"+(n++)+(" "+(r["class"]||""))})})}return p},_createBlockFormats:function(){var n,l={p:"advanced.paragraph",address:"advanced.address",pre:"advanced.pre",h1:"advanced.h1",h2:"advanced.h2",h3:"advanced.h3",h4:"advanced.h4",h5:"advanced.h5",h6:"advanced.h6",div:"advanced.div",blockquote:"advanced.blockquote",code:"advanced.code",dt:"advanced.dt",dd:"advanced.dd",samp:"advanced.samp"},m=this;n=m.editor.controlManager.createListBox("formatselect",{title:"advanced.block",onselect:function(o){m.editor.execCommand("FormatBlock",false,o);return false}});if(n){f(m.editor.getParam("theme_advanced_blockformats",m.settings.theme_advanced_blockformats,"hash"),function(p,o){n.add(m.editor.translate(o!=p?o:l[p]),p,{"class":"mce_formatPreview mce_"+p,style:function(){return b(m.editor,{block:p})}})})}return n},_createForeColorMenu:function(){var q,m=this,n=m.settings,p={},l;if(n.theme_advanced_more_colors){p.more_colors_func=function(){m._mceColorPicker(0,{color:q.value,func:function(o){q.setColor(o)}})}}if(l=n.theme_advanced_text_colors){p.colors=l}if(n.theme_advanced_default_foreground_color){p.default_color=n.theme_advanced_default_foreground_color}p.title="advanced.forecolor_desc";p.cmd="ForeColor";p.scope=this;q=m.editor.controlManager.createColorSplitButton("forecolor",p);return q},_createBackColorMenu:function(){var q,m=this,n=m.settings,p={},l;if(n.theme_advanced_more_colors){p.more_colors_func=function(){m._mceColorPicker(0,{color:q.value,func:function(o){q.setColor(o)}})}}if(l=n.theme_advanced_background_colors){p.colors=l}if(n.theme_advanced_default_background_color){p.default_color=n.theme_advanced_default_background_color}p.title="advanced.backcolor_desc";p.cmd="HiliteColor";p.scope=this;q=m.editor.controlManager.createColorSplitButton("backcolor",p);return q},renderUI:function(q){var u,r,v,y=this,w=y.editor,z=y.settings,x,m,l;if(w.settings){w.settings.aria_label=z.aria_label+w.getLang("advanced.help_shortcut")}u=m=k.create("span",{role:"application","aria-labelledby":w.id+"_voice",id:w.id+"_parent","class":"mceEditor "+w.settings.skin+"Skin"+(z.skin_variant?" "+w.settings.skin+"Skin"+y._ufirst(z.skin_variant):"")+(w.settings.directionality=="rtl"?" mceRtl":"")});k.add(u,"span",{"class":"mceVoiceLabel",style:"display:none;",id:w.id+"_voice"},z.aria_label);if(!k.boxModel){u=k.add(u,"div",{"class":"mceOldBoxModel"})}u=x=k.add(u,"table",{role:"presentation",id:w.id+"_tbl","class":"mceLayout",cellSpacing:0,cellPadding:0});u=v=k.add(u,"tbody");switch((z.theme_advanced_layout_manager||"").toLowerCase()){case"rowlayout":r=y._rowLayout(z,v,q);break;case"customlayout":r=w.execCallback("theme_advanced_custom_layout",z,v,q,m);break;default:r=y._simpleLayout(z,v,q,m)}u=q.targetNode;l=x.rows;k.addClass(l[0],"mceFirst");k.addClass(l[l.length-1],"mceLast");f(k.select("tr",v),function(o){k.addClass(o.firstChild,"mceFirst");k.addClass(o.childNodes[o.childNodes.length-1],"mceLast")});if(k.get(z.theme_advanced_toolbar_container)){k.get(z.theme_advanced_toolbar_container).appendChild(m)}else{k.insertAfter(m,u)}h.add(w.id+"_path_row","click",function(n){n=n.target;if(n.nodeName=="A"){y._sel(n.className.replace(/^.*mcePath_([0-9]+).*$/,"$1"));return false}});if(!w.getParam("accessibility_focus")){h.add(k.add(m,"a",{href:"#"},""),"focus",function(){tinyMCE.get(w.id).focus()})}if(z.theme_advanced_toolbar_location=="external"){q.deltaHeight=0}y.deltaHeight=q.deltaHeight;q.targetNode=null;w.onKeyDown.add(function(p,n){var s=121,o=122;if(n.altKey){if(n.keyCode===s){if(i.isWebKit){window.focus()}y.toolbarGroup.focus();return h.cancel(n)}else{if(n.keyCode===o){k.get(p.id+"_path_row").focus();return h.cancel(n)}}}});w.addShortcut("alt+0","","mceShortcuts",y);return{iframeContainer:r,editorContainer:w.id+"_parent",sizeContainer:x,deltaHeight:q.deltaHeight}},getInfo:function(){return{longname:"Advanced theme",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",version:i.majorVersion+"."+i.minorVersion}},resizeBy:function(l,m){var n=k.get(this.editor.id+"_ifr");this.resizeTo(n.clientWidth+l,n.clientHeight+m)},resizeTo:function(l,p,n){var m=this.editor,o=this.settings,q=k.get(m.id+"_tbl"),r=k.get(m.id+"_ifr");l=Math.max(o.theme_advanced_resizing_min_width||100,l);p=Math.max(o.theme_advanced_resizing_min_height||100,p);l=Math.min(o.theme_advanced_resizing_max_width||65535,l);p=Math.min(o.theme_advanced_resizing_max_height||65535,p);k.setStyle(q,"height","");k.setStyle(r,"height",p);if(o.theme_advanced_resize_horizontal){k.setStyle(q,"width","");k.setStyle(r,"width",l);if(l"));k.setHTML(p,w.join(""))},_addStatusBar:function(u,m){var p,y=this,v=y.editor,z=y.settings,l,w,x,q;p=k.add(u,"tr");p=q=k.add(p,"td",{"class":"mceStatusbar"});p=k.add(p,"div",{id:v.id+"_path_row",role:"group","aria-labelledby":v.id+"_path_voice"});if(z.theme_advanced_path){k.add(p,"span",{id:v.id+"_path_voice"},v.translate("advanced.path"));k.add(p,"span",{},": ")}else{k.add(p,"span",{}," ")}if(z.theme_advanced_resizing){k.add(q,"a",{id:v.id+"_resize",href:"javascript:;",onclick:"return false;","class":"mceResize",tabIndex:"-1"});if(z.theme_advanced_resizing_use_cookie){v.onPostRender.add(function(){var n=a.getHash("TinyMCE_"+v.id+"_size"),r=k.get(v.id+"_tbl");if(!n){return}y.resizeTo(n.cw,n.ch)})}v.onPostRender.add(function(){h.add(v.id+"_resize","click",function(n){n.preventDefault()});h.add(v.id+"_resize","mousedown",function(G){var t,r,s,o,F,C,D,I,n,H,A;function B(J){J.preventDefault();n=D+(J.screenX-F);H=I+(J.screenY-C);y.resizeTo(n,H)}function E(J){h.remove(k.doc,"mousemove",t);h.remove(v.getDoc(),"mousemove",r);h.remove(k.doc,"mouseup",s);h.remove(v.getDoc(),"mouseup",o);n=D+(J.screenX-F);H=I+(J.screenY-C);y.resizeTo(n,H,true);v.nodeChanged()}G.preventDefault();F=G.screenX;C=G.screenY;A=k.get(y.editor.id+"_ifr");D=n=A.clientWidth;I=H=A.clientHeight;t=h.add(k.doc,"mousemove",B);r=h.add(v.getDoc(),"mousemove",B);s=h.add(k.doc,"mouseup",E);o=h.add(v.getDoc(),"mouseup",E)})})}m.deltaHeight-=21;p=u=null},_updateUndoStatus:function(m){var l=m.controlManager,n=m.undoManager;l.setDisabled("undo",!n.hasUndo()&&!n.typing);l.setDisabled("redo",!n.hasRedo())},_nodeChanged:function(u,z,I,y,J){var D=this,H,K=0,C,L,E=D.settings,B,q,A,G,r,o,m;i.each(D.stateControls,function(n){z.setActive(n,u.queryCommandState(D.controls[n][1]))});var x=function(t,n){var p,t,s=n;if(typeof(n)=="string"){s=function(v){return v.nodeName==n}}for(p=0;p0){L.mark(p)}})}if(L=z.get("formatselect")){H=w(u.dom.isBlock);if(H){L.select(H.nodeName.toLowerCase())}}l(function(s){var p;if(s.nodeName==="SPAN"){if(!B&&s.className){B=s.className}}p=u.dom.is(s,E.theme_advanced_font_selector);if(p||j(u.settings)){if(!q&&s.style.fontSize){q=s.style.fontSize}if(!A&&s.style.fontFamily){A=s.style.fontFamily.replace(/[\"\']+/g,"").replace(/^([^,]+).*/,"$1").toLowerCase()}if(!G&&s.style.color){G=s.style.color}if(!r&&s.style.backgroundColor){r=s.style.backgroundColor}}return false});if(L=z.get("fontselect")){L.select(function(n){return n.replace(/^([^,]+).*/,"$1").toLowerCase()==A})}if(L=z.get("fontsizeselect")){if(E.theme_advanced_runtime_fontsize&&!q&&!B){q=u.dom.getStyle(I,"fontSize",true)}L.select(function(n){if(n.fontSize&&n.fontSize===q){return true}if(n["class"]&&n["class"]===B){return true}})}if(E.theme_advanced_show_current_color){function F(p,n){if(L=z.get(p)){if(!n){n=L.settings.default_color}if(n!==L.value){L.displayColor(n)}}}F("forecolor",G);F("backcolor",r)}if(E.theme_advanced_show_current_color){function F(p,n){if(L=z.get(p)){if(!n){n=L.settings.default_color}if(n!==L.value){L.displayColor(n)}}}F("forecolor",G);F("backcolor",r)}if(E.theme_advanced_path&&E.theme_advanced_statusbar_location){H=k.get(u.id+"_path")||k.add(u.id+"_path_row","span",{id:u.id+"_path"});if(D.statusKeyboardNavigation){D.statusKeyboardNavigation.destroy();D.statusKeyboardNavigation=null}k.setHTML(H,"");w(function(M){var p=M.nodeName.toLowerCase(),s,v,t="";if(M.nodeType!=1||p==="br"||M.getAttribute("data-mce-bogus")||k.hasClass(M,"mceItemHidden")||k.hasClass(M,"mceItemRemoved")){return}if(i.isIE&&M.scopeName!=="HTML"&&M.scopeName){p=M.scopeName+":"+p}p=p.replace(/mce\:/g,"");switch(p){case"b":p="strong";break;case"i":p="em";break;case"img":if(C=k.getAttrib(M,"src")){t+="src: "+C+" "}break;case"a":if(C=k.getAttrib(M,"name")){t+="name: "+C+" ";p+="#"+C}if(C=k.getAttrib(M,"href")){t+="href: "+C+" "}break;case"font":if(C=k.getAttrib(M,"face")){t+="font: "+C+" "}if(C=k.getAttrib(M,"size")){t+="size: "+C+" "}if(C=k.getAttrib(M,"color")){t+="color: "+C+" "}break;case"span":if(C=k.getAttrib(M,"style")){t+="style: "+C+" "}break}if(C=k.getAttrib(M,"id")){t+="id: "+C+" "}if(C=M.className){C=C.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g,"");if(C){t+="class: "+C+" ";if(u.dom.isBlock(M)||p=="img"||p=="span"){p+="."+C}}}p=p.replace(/(html:)/g,"");p={name:p,node:M,title:t};D.onResolveName.dispatch(D,p);t=p.title;p=p.name;v=k.create("a",{href:"javascript:;",role:"button",onmousedown:"return false;",title:t,"class":"mcePath_"+(K++)},p);if(H.hasChildNodes()){H.insertBefore(k.create("span",{"aria-hidden":"true"},"\u00a0\u00bb "),H.firstChild);H.insertBefore(v,H.firstChild)}else{H.appendChild(v)}},u.getBody());if(k.select("a",H).length>0){D.statusKeyboardNavigation=new i.ui.KeyboardNavigation({root:u.id+"_path_row",items:k.select("a",H),excludeFromTabOrder:true,onCancel:function(){u.focus()}},k)}}},_sel:function(l){this.editor.execCommand("mceSelectNodeDepth",false,l)},_mceInsertAnchor:function(n,m){var l=this.editor;l.windowManager.open({url:this.url+"/anchor.htm",width:320+parseInt(l.getLang("advanced.anchor_delta_width",0)),height:90+parseInt(l.getLang("advanced.anchor_delta_height",0)),inline:true},{theme_url:this.url})},_mceCharMap:function(){var l=this.editor;l.windowManager.open({url:this.url+"/charmap.htm",width:550+parseInt(l.getLang("advanced.charmap_delta_width",0)),height:265+parseInt(l.getLang("advanced.charmap_delta_height",0)),inline:true},{theme_url:this.url})},_mceHelp:function(){var l=this.editor;l.windowManager.open({url:this.url+"/about.htm",width:480,height:380,inline:true},{theme_url:this.url})},_mceShortcuts:function(){var l=this.editor;l.windowManager.open({url:this.url+"/shortcuts.htm",width:480,height:380,inline:true},{theme_url:this.url})},_mceColorPicker:function(n,m){var l=this.editor;m=m||{};l.windowManager.open({url:this.url+"/color_picker.htm",width:375+parseInt(l.getLang("advanced.colorpicker_delta_width",0)),height:250+parseInt(l.getLang("advanced.colorpicker_delta_height",0)),close_previous:false,inline:true},{input_color:m.color,func:m.func,theme_url:this.url})},_mceCodeEditor:function(m,n){var l=this.editor;l.windowManager.open({url:this.url+"/source_editor.htm",width:parseInt(l.getParam("theme_advanced_source_editor_width",720)),height:parseInt(l.getParam("theme_advanced_source_editor_height",580)),inline:true,resizable:true,maximizable:true},{theme_url:this.url})},_mceImage:function(m,n){var l=this.editor;if(l.dom.getAttrib(l.selection.getNode(),"class","").indexOf("mceItem")!=-1){return}l.windowManager.open({url:this.url+"/image.htm",width:355+parseInt(l.getLang("advanced.image_delta_width",0)),height:275+parseInt(l.getLang("advanced.image_delta_height",0)),inline:true},{theme_url:this.url})},_mceLink:function(m,n){var l=this.editor;l.windowManager.open({url:this.url+"/link.htm",width:310+parseInt(l.getLang("advanced.link_delta_width",0)),height:200+parseInt(l.getLang("advanced.link_delta_height",0)),inline:true},{theme_url:this.url})},_mceNewDocument:function(){var l=this.editor;l.windowManager.confirm("advanced.newdocument",function(m){if(m){l.execCommand("mceSetContent",false,"")}})},_mceForeColor:function(){var l=this;this._mceColorPicker(0,{color:l.fgColor,func:function(m){l.fgColor=m;l.editor.execCommand("ForeColor",false,m)}})},_mceBackColor:function(){var l=this;this._mceColorPicker(0,{color:l.bgColor,func:function(m){l.bgColor=m;l.editor.execCommand("HiliteColor",false,m)}})},_ufirst:function(l){return l.substring(0,1).toUpperCase()+l.substring(1)}});i.ThemeManager.add("advanced",i.themes.AdvancedTheme)}(tinymce)); +(function(){tinymce.create("tinymce.plugins.AdvancedHRPlugin",{init:function(a,b){a.addCommand("mceAdvancedHr",function(){a.windowManager.open({file:b+"/rule.htm",width:250+parseInt(a.getLang("advhr.delta_width",0)),height:160+parseInt(a.getLang("advhr.delta_height",0)),inline:1},{plugin_url:b})});a.addButton("advhr",{title:"advhr.advhr_desc",cmd:"mceAdvancedHr"});a.onNodeChange.add(function(d,c,e){c.setActive("advhr",e.nodeName=="HR")});a.onClick.add(function(c,d){d=d.target;if(d.nodeName==="HR"){c.selection.select(d)}})},getInfo:function(){return{longname:"Advanced HR",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advhr",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("advhr",tinymce.plugins.AdvancedHRPlugin)})(); +(function(){tinymce.create("tinymce.plugins.AdvancedLinkPlugin",{init:function(a,b){this.editor=a;a.addCommand("mceAdvLink",function(){var c=a.selection;if(c.isCollapsed()&&!a.dom.getParent(c.getNode(),"A")){return}a.windowManager.open({file:b+"/link.htm",width:480+parseInt(a.getLang("advlink.delta_width",0)),height:400+parseInt(a.getLang("advlink.delta_height",0)),inline:1},{plugin_url:b})});a.addButton("link",{title:"advlink.link_desc",cmd:"mceAdvLink"});a.addShortcut("ctrl+k","advlink.advlink_desc","mceAdvLink");a.onNodeChange.add(function(d,c,f,e){c.setDisabled("link",e&&f.nodeName!="A");c.setActive("link",f.nodeName=="A"&&!f.name)})},getInfo:function(){return{longname:"Advanced link",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlink",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("advlink",tinymce.plugins.AdvancedLinkPlugin)})(); +(function(){tinymce.create("tinymce.plugins.AdvancedImagePlugin",{init:function(a,b){a.addCommand("mceAdvImage",function(){if(a.dom.getAttrib(a.selection.getNode(),"class","").indexOf("mceItem")!=-1){return}a.windowManager.open({file:b+"/image.htm",width:480+parseInt(a.getLang("advimage.delta_width",0)),height:385+parseInt(a.getLang("advimage.delta_height",0)),inline:1},{plugin_url:b})});a.addButton("image",{title:"advimage.image_desc",cmd:"mceAdvImage"})},getInfo:function(){return{longname:"Advanced image",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advimage",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("advimage",tinymce.plugins.AdvancedImagePlugin)})(); +(function(){tinymce.create("tinymce.plugins.Nonbreaking",{init:function(a,b){var c=this;c.editor=a;a.addCommand("mceNonBreaking",function(){a.execCommand("mceInsertContent",false,(a.plugins.visualchars&&a.plugins.visualchars.state)?' ':" ")});a.addButton("nonbreaking",{title:"nonbreaking.nonbreaking_desc",cmd:"mceNonBreaking"});if(a.getParam("nonbreaking_force_tab")){a.onKeyDown.add(function(d,f){if(f.keyCode==9){f.preventDefault();d.execCommand("mceNonBreaking");d.execCommand("mceNonBreaking");d.execCommand("mceNonBreaking")}})}},getInfo:function(){return{longname:"Nonbreaking space",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/nonbreaking",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("nonbreaking",tinymce.plugins.Nonbreaking)})(); +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + +// Kludges for bugs and behavior differences that can't be feature +// detected are enabled based on userAgent etc sniffing. +var userAgent = navigator.userAgent +var platform = navigator.platform + +var gecko = /gecko\/\d/i.test(userAgent) +var ie_upto10 = /MSIE \d/.test(userAgent) +var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) +var edge = /Edge\/(\d+)/.exec(userAgent) +var ie = ie_upto10 || ie_11up || edge +var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]) +var webkit = !edge && /WebKit\//.test(userAgent) +var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) +var chrome = !edge && /Chrome\//.test(userAgent) +var presto = /Opera\//.test(userAgent) +var safari = /Apple Computer/.test(navigator.vendor) +var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) +var phantom = /PhantomJS/.test(userAgent) + +var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) +var android = /Android/.test(userAgent) +// This is woefully incomplete. Suggestions for alternative methods welcome. +var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) +var mac = ios || /Mac/.test(platform) +var chromeOS = /\bCrOS\b/.test(userAgent) +var windows = /win/i.test(platform) + +var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) +if (presto_version) { presto_version = Number(presto_version[1]) } +if (presto_version && presto_version >= 15) { presto = false; webkit = true } +// Some browsers use the wrong event properties to signal cmd/ctrl on OS X +var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) +var captureRightClick = gecko || (ie && ie_version >= 9) + +function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +var rmClass = function(node, cls) { + var current = node.className + var match = classTest(cls).exec(current) + if (match) { + var after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + { e.removeChild(e.firstChild) } + return e +} + +function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) +} + +function elt(tag, content, className, style) { + var e = document.createElement(tag) + if (className) { e.className = className } + if (style) { e.style.cssText = style } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)) } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } } + return e +} +// wrapper for elt, which removes the elt from the accessibility tree +function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style) + e.setAttribute("role", "presentation") + return e +} + +var range +if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} } +else { range = function(node, start, end) { + var r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} } + +function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host } + if (child == parent) { return true } + } while (child = child.parentNode) +} + +function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + var activeElement + try { + activeElement = document.activeElement + } catch(e) { + activeElement = document.body || null + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + { activeElement = activeElement.shadowRoot.activeElement } + return activeElement +} + +function addClass(node, cls) { + var current = node.className + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls } +} +function joinClasses(a, b) { + var as = a.split(" ") + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } } + return b +} + +var selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } } +else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select() } catch(_e) {} } } + +function bind(f) { + var args = Array.prototype.slice.call(arguments, 1) + return function(){return f.apply(null, args)} +} + +function copyObj(obj, target, overwrite) { + if (!target) { target = {} } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop] } } + return target +} + +// Counts the column offset in a string, taking tabs into account. +// Used mostly to find indentation. +function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/) + if (end == -1) { end = string.length } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i) + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i + n += tabSize - (n % tabSize) + i = nextTab + 1 + } +} + +var Delayed = function() {this.id = null}; +Delayed.prototype.set = function (ms, f) { + clearTimeout(this.id) + this.id = setTimeout(f, ms) +}; + +function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 +} + +// Number of pixels added to scroller and sizer to hide scrollbar +var scrollerGap = 30 + +// Returned or thrown by various protocols to signal 'I'm not +// handling this'. +var Pass = {toString: function(){return "CodeMirror.Pass"}} + +// Reused option objects for setSelection & friends +var sel_dontScroll = {scroll: false}; +var sel_mouse = {origin: "*mouse"}; +var sel_move = {origin: "+move"}; +// The inverse of countColumn -- find the offset that corresponds to +// a particular column. +function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos) + if (nextTab == -1) { nextTab = string.length } + var skipped = nextTab - pos + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos + col += tabSize - (col % tabSize) + pos = nextTab + 1 + if (col >= goal) { return pos } + } +} + +var spaceStrs = [""] +function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " ") } + return spaceStrs[n] +} + +function lst(arr) { return arr[arr.length-1] } + +function map(array, f) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) } + return out +} + +function insertSorted(array, value, score) { + var pos = 0, priority = score(value) + while (pos < array.length && score(array[pos]) <= priority) { pos++ } + array.splice(pos, 0, value) +} + +function nothing() {} + +function createObj(base, props) { + var inst + if (Object.create) { + inst = Object.create(base) + } else { + nothing.prototype = base + inst = new nothing() + } + if (props) { copyObj(props, inst) } + return inst +} + +var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/ +function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) +} +function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) +} + +function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true +} + +// Extending unicode characters. A series of a non-extending char + +// any number of extending chars is treated as a single unit as far +// as editing and measuring is concerned. This is not fully correct, +// since some scripts/fonts/browsers also treat other configurations +// of code points as a group. +var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/ +function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + +// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. +function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir } + return pos +} + +// Returns the value from the range [`from`; `to`] that satisfies +// `pred` and is closest to `from`. Assumes that at least `to` satisfies `pred`. +function findFirst(pred, from, to) { + for (;;) { + if (Math.abs(from - to) <= 1) { return pred(from) ? from : to } + var mid = Math.floor((from + to) / 2) + if (pred(mid)) { to = mid } + else { from = mid } + } +} + +// The display handles the DOM integration, both for input reading +// and content drawing. It holds references to DOM nodes and +// display-related state. + +function Display(place, doc, input) { + var d = this + this.input = input + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") + d.scrollbarFiller.setAttribute("cm-not-content", "true") + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") + d.gutterFiller.setAttribute("cm-not-content", "true") + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = eltP("div", null, "CodeMirror-code") + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") + d.cursorDiv = elt("div", null, "CodeMirror-cursors") + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure") + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure") + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none") + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines") + // Moved around its parent to cover visible view. + d.mover = elt("div", [lines], null, "position: relative") + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer") + d.sizerWidth = null + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters") + d.lineGutter = null + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") + d.scroller.setAttribute("tabIndex", "-1") + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper) } + else { place(d.wrapper) } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first + d.reportedViewFrom = d.reportedViewTo = doc.first + // Information about the rendered lines. + d.view = [] + d.renderedView = null + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null + // Empty space (in pixels) above the view + d.viewOffset = 0 + d.lastWrapHeight = d.lastWrapWidth = 0 + d.updateLineNumbers = null + + d.nativeBarWidth = d.barHeight = d.barWidth = 0 + d.scrollbarsClipped = false + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null + d.maxLineLength = 0 + d.maxLineChanged = false + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null + + // True when shift is held down. + d.shift = false + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null + + d.activeTouch = null + + input.init(d) +} + +// Find the line object corresponding to the given line number. +function getLine(doc, n) { + n -= doc.first + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize() + if (n < sz) { chunk = child; break } + n -= sz + } + } + return chunk.lines[n] +} + +// Get the part of a document between two positions, as an array of +// strings. +function getBetween(doc, start, end) { + var out = [], n = start.line + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text + if (n == end.line) { text = text.slice(0, end.ch) } + if (n == start.line) { text = text.slice(start.ch) } + out.push(text) + ++n + }) + return out +} +// Get the lines between from and to, as array of strings. +function getLines(doc, from, to) { + var out = [] + doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value + return out +} + +// Update the height of a line, propagating the height change +// upwards to parent nodes. +function updateLineHeight(line, height) { + var diff = height - line.height + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } } +} + +// Given a line object, find its line number by walking up through +// its parent links. +function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line) + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize() + } + } + return no + cur.first +} + +// Find the line at the given vertical position, using the height +// information in the document tree. +function lineAtHeight(chunk, h) { + var n = chunk.first + outer: do { + for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { + var child = chunk.children[i$1], ch = child.height + if (h < ch) { chunk = child; continue outer } + h -= ch + n += child.chunkSize() + } + return n + } while (!chunk.lines) + var i = 0 + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height + if (h < lh) { break } + h -= lh + } + return n + i +} + +function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} + +function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)) +} + +// A Pos instance represents a position within the text. +function Pos(line, ch, sticky) { + if ( sticky === void 0 ) sticky = null; + + if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } + this.line = line + this.ch = ch + this.sticky = sticky +} + +// Compare two positions, return 0 if they are the same, a negative +// number when a is less, and a positive number otherwise. +function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + +function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } + +function copyPos(x) {return Pos(x.line, x.ch)} +function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } +function minPos(a, b) { return cmp(a, b) < 0 ? a : b } + +// Most of the external API clips given positions to make sure they +// actually exist within the document. +function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} +function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1 + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) +} +function clipToLen(pos, linelen) { + var ch = pos.ch + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } +} +function clipPosArray(doc, array) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) } + return out +} + +// Optimize some code when these features are not used. +var sawReadOnlySpans = false; +var sawCollapsedSpans = false; +function seeReadOnlySpans() { + sawReadOnlySpans = true +} + +function seeCollapsedSpans() { + sawCollapsedSpans = true +} + +// TEXTMARKER SPANS + +function MarkedSpan(marker, from, to) { + this.marker = marker + this.from = from; this.to = to +} + +// Search an array of spans for a span matching the given marker. +function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.marker == marker) { return span } + } } +} +// Remove a span from an array, returning undefined if no spans are +// left (we don't store arrays for lines without spans). +function removeMarkedSpan(spans, span) { + var r + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } } + return r +} +// Add a span to a line. +function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span] + span.marker.attachLine(line) +} + +// Used for the algorithm that adjusts markers for a change in the +// document. These functions cut an array of spans at a given +// character position, returning an array of remaining chunks (or +// undefined if nothing remains). +function markedSpansBefore(old, startCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh) + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)) + } + } } + return nw +} +function markedSpansAfter(old, endCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh) + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)) + } + } } + return nw +} + +// Given a change object, compute the new set of marker spans that +// cover the line in which the change took place. Removes spans +// entirely within the change, reconnects spans belonging to the +// same marker that appear on both sides of the change, and cuts off +// spans partially within the change. Returns an array of span +// arrays with one element for each line in (after) the change. +function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0 + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert) + var last = markedSpansAfter(oldLast, endCh, isInsert) + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0) + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i] + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker) + if (!found) { span.to = startCh } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset } + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1] + if (span$1.to != null) { span$1.to += offset } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker) + if (!found$1) { + span$1.from = offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } else { + span$1.from += offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } + } + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first) } + if (last && last != first) { last = clearEmptySpans(last) } + + var newMarkers = [first] + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } } + for (var i$3 = 0; i$3 < gap; ++i$3) + { newMarkers.push(gapMarkers) } + newMarkers.push(last) + } + return newMarkers +} + +// Remove spans that are empty and don't have a clearWhenEmpty +// option of false. +function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1) } + } + if (!spans.length) { return null } + return spans +} + +// Used to 'clip' out readOnly ranges when making a change. +function removeReadOnlyRanges(doc, from, to) { + var markers = null + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark) } + } } + }) + if (!markers) { return null } + var parts = [{from: from, to: to}] + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0) + for (var j = 0; j < parts.length; ++j) { + var p = parts[j] + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to) + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}) } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}) } + parts.splice.apply(parts, newParts) + j += newParts.length - 3 + } + } + return parts +} + +// Connect or disconnect spans from a line. +function detachMarkedSpans(line) { + var spans = line.markedSpans + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line) } + line.markedSpans = null +} +function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line) } + line.markedSpans = spans +} + +// Helpers used when computing which overlapping collapsed span +// counts as the larger one. +function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } +function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + +// Returns a number indicating which of two overlapping collapsed +// spans is larger (and thus includes the other). Falls back to +// comparing ids when the spans cover exactly the same range. +function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find() + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b) + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b) + if (toCmp) { return toCmp } + return b.id - a.id +} + +// Find out whether a line ends or starts in a collapsed span. If +// so, return the marker for that span. +function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker } + } } + return found +} +function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } +function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + +// Test whether there exists a collapsed span that partially +// overlaps (covers the start or end, but not both) of a new span. +// Such overlap is not allowed. +function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo) + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i] + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0) + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker) + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker) + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } +} + +// A visual line is a line as drawn on the screen. Folding, for +// example, can cause multiple logical lines to appear on the same +// visual line. This finds the start of the visual line that the +// given line is part of (usually that is the line itself). +function visualLine(line) { + var merged + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line } + return line +} + +function visualLineEnd(line) { + var merged + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return line +} + +// Returns an array of logical lines that continue the visual line +// started by the argument, or undefined if there are no such lines. +function visualLineContinued(line) { + var merged, lines + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line) + } + return lines +} + +// Get the line number of the start of the visual line that the +// given line number is part of. +function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line) + if (line == vis) { return lineN } + return lineNo(vis) +} + +// Get the line number of the start of the next visual line after +// the given line. +function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return lineNo(line) + 1 +} + +// Compute whether a line is hidden. Lines count as hidden when they +// are part of a visual line that starts with another line, or when +// they are entirely covered by collapsed, non-widget span. +function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } +} +function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true) + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i] + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } +} + +// Find the height above the given line. +function heightAtLine(lineObj) { + lineObj = visualLine(lineObj) + + var h = 0, chunk = lineObj.parent + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i] + if (line == lineObj) { break } + else { h += line.height } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1] + if (cur == chunk) { break } + else { h += cur.height } + } + } + return h +} + +// Compute the character length of a line, taking into account +// collapsed ranges (see markText) that might hide parts, and join +// other lines onto it. +function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true) + cur = found.from.line + len += found.from.ch - found.to.ch + } + cur = line + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true) + len -= cur.text.length - found$1.from.ch + cur = found$1.to.line + len += cur.text.length - found$1.to.ch + } + return len +} + +// Find the longest line in the document. +function findMaxLine(cm) { + var d = cm.display, doc = cm.doc + d.maxLine = getLine(doc, doc.first) + d.maxLineLength = lineLength(d.maxLine) + d.maxLineChanged = true + doc.iter(function (line) { + var len = lineLength(line) + if (len > d.maxLineLength) { + d.maxLineLength = len + d.maxLine = line + } + }) +} + +// BIDI HELPERS + +function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr") } + var found = false + for (var i = 0; i < order.length; ++i) { + var part = order[i] + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr") + found = true + } + } + if (!found) { f(from, to, "ltr") } +} + +var bidiOther = null +function getBidiPartAt(order, ch, sticky) { + var found + bidiOther = null + for (var i = 0; i < order.length; ++i) { + var cur = order[i] + if (cur.from < ch && cur.to > ch) { return i } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { found = i } + else { bidiOther = i } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { found = i } + else { bidiOther = i } + } + } + return found != null ? found : bidiOther +} + +// Bidirectional ordering algorithm +// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm +// that this (partially) implements. + +// One-char codes used for character types: +// L (L): Left-to-Right +// R (R): Right-to-Left +// r (AL): Right-to-Left Arabic +// 1 (EN): European Number +// + (ES): European Number Separator +// % (ET): European Number Terminator +// n (AN): Arabic Number +// , (CS): Common Number Separator +// m (NSM): Non-Spacing Mark +// b (BN): Boundary Neutral +// s (B): Paragraph Separator +// t (S): Segment Separator +// w (WS): Whitespace +// N (ON): Other Neutrals + +// Returns null if characters are ordered as they appear +// (left-to-right), or an array of sections ({from, to, level} +// objects) in the order in which they occur visually. +var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" + // Character types for codepoints 0x600 to 0x6f9 + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/ + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/ + + function BidiSpan(level, from, to) { + this.level = level + this.from = from; this.to = to + } + + return function(str, direction) { + var outerType = direction == "ltr" ? "L" : "R" + + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } + var len = str.length, types = [] + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))) } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1] + if (type == "m") { types[i$1] = prev } + else { prev = type } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2] + if (type$1 == "1" && cur == "r") { types[i$2] = "n" } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3] + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 } + prev$1 = type$2 + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4] + if (type$3 == ",") { types[i$4] = "N" } + else if (type$3 == "%") { + var end = (void 0) + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N" + for (var j = i$4; j < end; ++j) { types[j] = replace } + i$4 = end - 1 + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5] + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" } + else if (isStrong.test(type$4)) { cur$1 = type$4 } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = (void 0) + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L" + var after = (end$1 < len ? types[end$1] : outerType) == "L" + var replace$1 = before == after ? (before ? "L" : "R") : outerType + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 } + i$6 = end$1 - 1 + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7 + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)) + } else { + var pos = i$7, at = order.length + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) } + var nstart = j$2 + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)) + pos = j$2 + } else { ++j$2 } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) } + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length + order.unshift(new BidiSpan(0, 0, m[0].length)) + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length + order.push(new BidiSpan(0, len - m[0].length, len)) + } + + return direction == "rtl" ? order.reverse() : order + } +})() + +// Get the bidi ordering for the given line (and cache it). Returns +// false for lines that are fully left-to-right, and an array of +// BidiSpan objects otherwise. +function getOrder(line, direction) { + var order = line.order + if (order == null) { order = line.order = bidiOrdering(line.text, direction) } + return order +} + +function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir) + return target < 0 || target > line.text.length ? null : target +} + +function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir) + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") +} + +function endOfLine(visually, cm, lineObj, lineNo, dir) { + if (visually) { + var order = getOrder(lineObj, cm.doc.direction) + if (order) { + var part = dir < 0 ? lst(order) : order[0] + var moveInStorageOrder = (dir < 0) == (part.level == 1) + var sticky = moveInStorageOrder ? "after" : "before" + var ch + // With a wrapped rtl chunk (possibly spanning multiple bidi parts), + // it could be that the last bidi part is not on the last visual line, + // since visual lines contain content order-consecutive chunks. + // Thus, in rtl, we are looking for the first (content-order) character + // in the rtl chunk that is on the last line (that is, the same line + // as the last (content-order) character). + if (part.level > 0) { + var prep = prepareMeasureForLine(cm, lineObj) + ch = dir < 0 ? lineObj.text.length - 1 : 0 + var targetTop = measureCharPrepared(cm, prep, ch).top + ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch) + if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1, true) } + } else { ch = dir < 0 ? part.to : part.from } + return new Pos(lineNo, ch, sticky) + } + } + return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") +} + +function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction) + if (!bidi) { return moveLogically(line, start, dir) } + if (start.ch >= line.text.length) { + start.ch = line.text.length + start.sticky = "before" + } else if (start.ch <= 0) { + start.ch = 0 + start.sticky = "after" + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos] + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, + // nothing interesting happens. + return moveLogically(line, start, dir) + } + + var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); } + var prep + var getWrappedLineExtent = function (ch) { + if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } + prep = prep || prepareMeasureForLine(cm, line) + return wrappedLineExtentChar(cm, line, prep, ch) + } + var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch) + + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = (part.level == 1) == (dir < 0) + var ch = mv(start, moveInStorageOrder ? 1 : -1) + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { + // Case 2: We move within an rtl part or in an rtl editor on the same visual line + var sticky = moveInStorageOrder ? "before" : "after" + return new Pos(start.line, ch, sticky) + } + } + + // Case 3: Could not move within this bidi part in this visual line, so leave + // the current bidi part + + var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { + var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder + ? new Pos(start.line, mv(ch, 1), "before") + : new Pos(start.line, ch, "after"); } + + for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { + var part = bidi[partPos] + var moveInStorageOrder = (dir > 0) == (part.level != 1) + var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1) + if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } + ch = moveInStorageOrder ? part.from : mv(part.to, -1) + if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } + } + } + + // Case 3a: Look for other bidi parts on the same visual line + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent) + if (res) { return res } + + // Case 3b: Look for other bidi parts on the next visual line + var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1) + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)) + if (res) { return res } + } + + // Case 4: Nowhere to move + return null +} + +// EVENT HANDLING + +// Lightweight event framework. on/off also work on DOM nodes, +// registering native DOM handlers. + +var noHandlers = [] + +var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false) + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f) + } else { + var map = emitter._handlers || (emitter._handlers = {}) + map[type] = (map[type] || noHandlers).concat(f) + } +} + +function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers +} + +function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false) + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f) + } else { + var map = emitter._handlers, arr = map && map[type] + if (arr) { + var index = indexOf(arr, f) + if (index > -1) + { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) } + } + } +} + +function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type) + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2) + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) } +} + +// The DOM events that CodeMirror handles can be overridden by +// registering a (non-DOM) handler on the editor for the event name, +// and preventDefault-ing the event in that handler. +function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} } + signal(cm, override || e.type, cm, e) + return e_defaultPrevented(e) || e.codemirrorIgnore +} + +function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]) } } +} + +function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 +} + +// Add on and off methods to a constructor's prototype, to make +// registering events on such objects more convenient. +function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f)} + ctor.prototype.off = function(type, f) {off(this, type, f)} +} + +// Due to the fact that we still support jurassic IE versions, some +// compatibility wrappers are needed. + +function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault() } + else { e.returnValue = false } +} +function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation() } + else { e.cancelBubble = true } +} +function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false +} +function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)} + +function e_target(e) {return e.target || e.srcElement} +function e_button(e) { + var b = e.which + if (b == null) { + if (e.button & 1) { b = 1 } + else if (e.button & 2) { b = 3 } + else if (e.button & 4) { b = 2 } + } + if (mac && e.ctrlKey && b == 1) { b = 3 } + return b +} + +// Detect drag-and-drop +var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div') + return "draggable" in div || "dragDrop" in div +}() + +var zwspSupported +function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b") + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") + node.setAttribute("cm-text", "") + return node +} + +// Feature-detect IE's crummy client rect reporting for bidi text +var badBidiRects +function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) + var r0 = range(txt, 0, 1).getBoundingClientRect() + var r1 = range(txt, 1, 2).getBoundingClientRect() + removeChildren(measure) + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) +} + +// See if "".split is the broken IE version, if so, provide an +// alternative way to split lines. +var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length + while (pos <= l) { + var nl = string.indexOf("\n", pos) + if (nl == -1) { nl = string.length } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) + var rt = line.indexOf("\r") + if (rt != -1) { + result.push(line.slice(0, rt)) + pos += rt + 1 + } else { + result.push(line) + pos = nl + 1 + } + } + return result +} : function (string) { return string.split(/\r\n?|\n/); } + +var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } +} : function (te) { + var range + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 0 +} + +var hasCopyEvent = (function () { + var e = elt("div") + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;") + return typeof e.oncopy == "function" +})() + +var badZoomedRects = null +function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")) + var normal = node.getBoundingClientRect() + var fromRange = range(node, 0, 1).getBoundingClientRect() + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 +} + +var modes = {}; +var mimeModes = {}; +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2) } + modes[name] = mode +} + +function defineMIME(mime, spec) { + mimeModes[mime] = spec +} + +// Given a MIME type, a {name, ...options} config object, or a name +// string, return a mode config object. +function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec] + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name] + if (typeof found == "string") { found = {name: found} } + spec = createObj(found, spec) + spec.name = found.name + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } +} + +// Given a mode spec (anything that resolveMode accepts), find and +// initialize an actual mode object. +function getMode(options, spec) { + spec = resolveMode(spec) + var mfactory = modes[spec.name] + if (!mfactory) { return getMode(options, "text/plain") } + var modeObj = mfactory(options, spec) + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name] + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] } + modeObj[prop] = exts[prop] + } + } + modeObj.name = spec.name + if (spec.helperType) { modeObj.helperType = spec.helperType } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1] } } + + return modeObj +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +var modeExtensions = {} +function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) + copyObj(properties, exts) +} + +function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {} + for (var n in state) { + var val = state[n] + if (val instanceof Array) { val = val.concat([]) } + nstate[n] = val + } + return nstate +} + +// Given a mode and a state (for that mode), find the inner mode and +// state at the position that the state refers to. +function innerMode(mode, state) { + var info + while (mode.innerMode) { + info = mode.innerMode(state) + if (!info || info.mode == mode) { break } + state = info.state + mode = info.mode + } + return info || {mode: mode, state: state} +} + +function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true +} + +// STRING STREAM + +// Fed to the mode parsers, provides helper functions to make +// parsers more succinct. + +var StringStream = function(string, tabSize) { + this.pos = this.start = 0 + this.string = string + this.tabSize = tabSize || 8 + this.lastColumnPos = this.lastColumnValue = 0 + this.lineStart = 0 +}; + +StringStream.prototype.eol = function () {return this.pos >= this.string.length}; +StringStream.prototype.sol = function () {return this.pos == this.lineStart}; +StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; +StringStream.prototype.next = function () { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } +}; +StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos) + var ok + if (typeof match == "string") { ok = ch == match } + else { ok = ch && (match.test ? match.test(ch) : match(ch)) } + if (ok) {++this.pos; return ch} +}; +StringStream.prototype.eatWhile = function (match) { + var start = this.pos + while (this.eat(match)){} + return this.pos > start +}; +StringStream.prototype.eatSpace = function () { + var this$1 = this; + + var start = this.pos + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos } + return this.pos > start +}; +StringStream.prototype.skipToEnd = function () {this.pos = this.string.length}; +StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos) + if (found > -1) {this.pos = found; return true} +}; +StringStream.prototype.backUp = function (n) {this.pos -= n}; +StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue) + this.lastColumnPos = this.start + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) +}; +StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) +}; +StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; } + var substr = this.string.substr(this.pos, pattern.length) + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length } + return true + } + } else { + var match = this.string.slice(this.pos).match(pattern) + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length } + return match + } +}; +StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; +StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n + try { return inner() } + finally { this.lineStart -= n } +}; + +// Compute a style array (an array starting with a mode generation +// -- for invalidation -- followed by pairs of end positions and +// style strings), which is used to highlight the tokens on the +// line. +function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {} + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd) + + // Run overlays, adjust style array. + var loop = function ( o ) { + var overlay = cm.state.overlays[o], i = 1, at = 0 + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i] + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end) } + i += 2 + at = Math.min(end, i_end) + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style) + i = start + 2 + } else { + for (; start < i; start += 2) { + var cur = st[start+1] + st[start+1] = (cur ? cur + " " : "") + "overlay " + style + } + } + }, lineClasses) + }; + + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} +} + +function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)) + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state) + line.stateAfter = state + line.styles = result.styles + if (result.classes) { line.styleClasses = result.classes } + else if (line.styleClasses) { line.styleClasses = null } + if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ } + } + return line.styles +} + +function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display + if (!doc.mode.startState) { return true } + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter + if (!state) { state = startState(doc.mode) } + else { state = copyState(doc.mode, state) } + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state) + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo + line.stateAfter = save ? copyState(doc.mode, state) : null + ++pos + }) + if (precise) { doc.frontier = pos } + return state +} + +// Lightweight form of highlight -- proceed over this line and +// update state, but don't save a style array. Used for lines that +// aren't currently visible. +function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode + var stream = new StringStream(text, cm.options.tabSize) + stream.start = stream.pos = startAt || 0 + if (text == "") { callBlankLine(mode, state) } + while (!stream.eol()) { + readToken(mode, stream, state) + stream.start = stream.pos + } +} + +function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state) + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } +} + +function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) { inner[0] = innerMode(mode, state).mode } + var style = mode.token(stream, state) + if (stream.pos > stream.start) { return style } + } + throw new Error("Mode " + mode.name + " failed to advance stream.") +} + +// Utility for getTokenAt and getLineTokens +function takeToken(cm, pos, precise, asArray) { + var getObj = function (copy) { return ({ + start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state + }); } + + var doc = cm.doc, mode = doc.mode, style + pos = clipPos(doc, pos) + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise) + var stream = new StringStream(line.text, cm.options.tabSize), tokens + if (asArray) { tokens = [] } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos + style = readToken(mode, stream, state) + if (asArray) { tokens.push(getObj(true)) } + } + return asArray ? tokens : getObj() +} + +function extractLineClasses(type, output) { + if (type) { for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/) + if (!lineClass) { break } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length) + var prop = lineClass[1] ? "bgClass" : "textClass" + if (output[prop] == null) + { output[prop] = lineClass[2] } + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2] } + } } + return type +} + +// Run the given mode's parser over a line, calling f for each token. +function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans } + var curStart = 0, curStyle = null + var stream = new StringStream(text, cm.options.tabSize), style + var inner = cm.options.addModeClass && [null] + if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false + if (forceToEnd) { processLine(cm, text, state, stream.pos) } + stream.pos = text.length + style = null + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses) + } + if (inner) { + var mName = inner[0].name + if (mName) { style = "m-" + (style ? mName + " " + style : mName) } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000) + f(curStart, curStyle) + } + curStyle = style + } + stream.start = stream.pos + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000) + f(pos, curStyle) + curStart = pos + } +} + +// Finds the line to start with when starting a parse. Tries to +// find a line with a stateAfter, so that it can start with a +// valid state. If that fails, it returns the line with the +// smallest indentation, which tends to need the least context to +// parse correctly. +function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1) + if (line.stateAfter && (!precise || search <= doc.frontier)) { return search } + var indented = countColumn(line.text, null, cm.options.tabSize) + if (minline == null || minindent > indented) { + minline = search - 1 + minindent = indented + } + } + return minline +} + +// LINE DATA STRUCTURE + +// Line objects. These hold state related to a line, including +// highlighting info (the styles array). +var Line = function(text, markedSpans, estimateHeight) { + this.text = text + attachMarkedSpans(this, markedSpans) + this.height = estimateHeight ? estimateHeight(this) : 1 +}; + +Line.prototype.lineNo = function () { return lineNo(this) }; +eventMixin(Line) + +// Change the content (text, markers) of a line. Automatically +// invalidates cached information and tries to re-estimate the +// line's height. +function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + if (line.order != null) { line.order = null } + detachMarkedSpans(line) + attachMarkedSpans(line, markedSpans) + var estHeight = estimateHeight ? estimateHeight(line) : 1 + if (estHeight != line.height) { updateLineHeight(line, estHeight) } +} + +// Detach a line from the document tree and its markers. +function cleanUpLine(line) { + line.parent = null + detachMarkedSpans(line) +} + +// Convert a style as returned by a mode (either null, or a string +// containing one or more styles) to a CSS style. This is cached, +// and also looks for line-wide styles. +var styleToClassCache = {}; +var styleToClassCacheWithMode = {}; +function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) +} + +// Render the DOM representation of the text of a line. Also builds +// up a 'line map', which points at the DOM nodes that represent +// specific stretches of text, and is used by the measuring code. +// The returned object contains the DOM node, this map, and +// information about line-wide styles that were set by the mode. +function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null) + var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")} + lineView.measure = {} + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0) + builder.pos = 0 + builder.addToken = buildToken + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order) } + builder.map = [] + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map + lineView.measure.cache = {} + } else { + ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack" } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre) + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") } + + return builder +} + +function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar") + token.title = "\\u" + ch.charCodeAt(0).toString(16) + token.setAttribute("aria-label", token.title) + return token +} + +// Build up the DOM representation for a single token, and add it to +// the line map. Takes care to render special characters separately. +function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text + var special = builder.cm.state.specialChars, mustWrap = false + var content + if (!special.test(text)) { + builder.col += text.length + content = document.createTextNode(displayText) + builder.map.push(builder.pos, builder.pos + text.length, content) + if (ie && ie_version < 9) { mustWrap = true } + builder.pos += text.length + } else { + content = document.createDocumentFragment() + var pos = 0 + while (true) { + special.lastIndex = pos + var m = special.exec(text) + var skipped = m ? m.index - pos : text.length - pos + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) } + else { content.appendChild(txt) } + builder.map.push(builder.pos, builder.pos + skipped, txt) + builder.col += skipped + builder.pos += skipped + } + if (!m) { break } + pos += skipped + 1 + var txt$1 = (void 0) + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) + txt$1.setAttribute("role", "presentation") + txt$1.setAttribute("cm-text", "\t") + builder.col += tabWidth + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) + txt$1.setAttribute("cm-text", m[0]) + builder.col += 1 + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]) + txt$1.setAttribute("cm-text", m[0]) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) } + else { content.appendChild(txt$1) } + builder.col += 1 + } + builder.map.push(builder.pos, builder.pos + 1, txt$1) + builder.pos++ + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || "" + if (startStyle) { fullStyle += startStyle } + if (endStyle) { fullStyle += endStyle } + var token = elt("span", [content], fullStyle, css) + if (title) { token.title = title } + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = "" + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i) + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0" } + result += ch + spaceBefore = ch == " " + } + return result +} + +// Work around nonsense dimensions being reported for stretches of +// right-to-left text. +function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border" + var start = builder.pos, end = start + text.length + for (;;) { + // Find the part that overlaps with the start of this text + var part = (void 0) + for (var i = 0; i < order.length; i++) { + part = order[i] + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + startStyle = null + text = text.slice(part.to - start) + start = part.to + } + } +} + +function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")) } + widget.setAttribute("cm-marker", marker.id) + } + if (widget) { + builder.cm.display.input.setUneditable(widget) + builder.content.appendChild(widget) + } + builder.pos += size + builder.trailingSpace = false +} + +// Outputs a number of spans to make up a line, taking highlighting +// and marked text into account. +function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0 + if (!spans) { + for (var i$1 = 1; i$1 < styles.length; i$1+=2) + { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + collapsed = null; nextChange = Infinity + var foundBookmarks = [], endStyles = (void 0) + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m) + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to + spanEndStyle = "" + } + if (m.className) { spanStyle += " " + m.className } + if (m.css) { css = (css ? css + ";" : "") + m.css } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) } + if (m.title && !title) { title = m.title } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from + } + } + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } } + + if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) + { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null) + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false } + } + } + if (pos >= len) { break } + + var upto = Math.min(len, nextChange) + while (true) { + if (text) { + var end = pos + text.length + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css) + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end + spanStartStyle = "" + } + text = allText.slice(at, at = styles[i++]) + style = interpretTokenStyle(styles[i++], builder.cm.options) + } + } +} + + +// These objects are used to represent the visible (currently drawn) +// part of the document. A LineView may correspond to multiple +// logical lines, if those are connected by collapsed ranges. +function LineView(doc, line, lineN) { + // The starting line + this.line = line + // Continuing lines, if any + this.rest = visualLineContinued(line) + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 + this.node = this.text = null + this.hidden = lineIsHidden(doc, line) +} + +// Create a range of LineView objects for the given lines. +function buildViewArray(cm, from, to) { + var array = [], nextPos + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos) + nextPos = pos + view.size + array.push(view) + } + return array +} + +var operationGroup = null + +function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op) + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + } + } +} + +function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0 + do { + for (; i < callbacks.length; i++) + { callbacks[i].call(null) } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j] + if (op.cursorActivityHandlers) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } } + } + } while (i < callbacks.length) +} + +function finishOperation(op, endCb) { + var group = op.ownsGroup + if (!group) { return } + + try { fireCallbacksForOps(group) } + finally { + operationGroup = null + endCb(group) + } +} + +var orphanDelayedCallbacks = null + +// Often, we want to signal events at a point where we are in the +// middle of some work, but don't want the handler to start calling +// other methods on the editor, which might be in an inconsistent +// state or simply not expect any other events to happen. +// signalLater looks whether there are any handlers, and schedules +// them to be executed when the last operation ends, or, if no +// operation is active, when a timeout fires. +function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type) + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list + if (operationGroup) { + list = operationGroup.delayedCallbacks + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks + } else { + list = orphanDelayedCallbacks = [] + setTimeout(fireOrphanDelayed, 0) + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }) + }; + + for (var i = 0; i < arr.length; ++i) + loop( i ); +} + +function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks + orphanDelayedCallbacks = null + for (var i = 0; i < delayed.length; ++i) { delayed[i]() } +} + +// When an aspect of a line changes, a string is added to +// lineView.changes. This updates the relevant part of the line's +// DOM structure. +function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j] + if (type == "text") { updateLineText(cm, lineView) } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) } + else if (type == "class") { updateLineClasses(cm, lineView) } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims) } + } + lineView.changes = null +} + +// Lines with gutter elements, widgets or a background class need to +// be wrapped, and have the extra elements added to the wrapper div +function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative") + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) } + lineView.node.appendChild(lineView.text) + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 } + } + return lineView.node +} + +function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass + if (cls) { cls += " CodeMirror-linebackground" } + if (lineView.background) { + if (cls) { lineView.background.className = cls } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null } + } else if (cls) { + var wrap = ensureLineWrapped(lineView) + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild) + cm.display.input.setUneditable(lineView.background) + } +} + +// Wrapper around buildLineContent which will reuse the structure +// in display.externalMeasured when possible. +function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null + lineView.measure = ext.measure + return ext.built + } + return buildLineContent(cm, lineView) +} + +// Redraw the line's text. Interacts with the background and text +// classes because the mode may output tokens that influence these +// classes. +function updateLineText(cm, lineView) { + var cls = lineView.text.className + var built = getLineContent(cm, lineView) + if (lineView.text == lineView.node) { lineView.node = built.pre } + lineView.text.parentNode.replaceChild(built.pre, lineView.text) + lineView.text = built.pre + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass + lineView.textClass = built.textClass + updateLineClasses(cm, lineView) + } else if (cls) { + lineView.text.className = cls + } +} + +function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView) + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass } + else if (lineView.node != lineView.text) + { lineView.node.className = "" } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass + lineView.text.className = textClass || "" +} + +function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter) + lineView.gutter = null + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground) + lineView.gutterBackground = null + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView) + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(lineView.gutterBackground) + wrap.insertBefore(lineView.gutterBackground, lineView.text) + } + var markers = lineView.line.gutterMarkers + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView) + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(gutterWrap) + wrap$1.insertBefore(gutterWrap, lineView.text) + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + { lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) } + if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id] + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) } + } } + } +} + +function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null } + for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { + next = node.nextSibling + if (node.className == "CodeMirror-linewidget") + { lineView.node.removeChild(node) } + } + insertLineWidgets(cm, lineView, dims) +} + +// Build a line's DOM representation from scratch +function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView) + lineView.text = lineView.node = built.pre + if (built.bgClass) { lineView.bgClass = built.bgClass } + if (built.textClass) { lineView.textClass = built.textClass } + + updateLineClasses(cm, lineView) + updateLineGutter(cm, lineView, lineN, dims) + insertLineWidgets(cm, lineView, dims) + return lineView.node +} + +// A lineView may contain multiple logical lines (when merged by +// collapsed spans). The widgets for all of them need to be drawn. +function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true) + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } } +} + +function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView) + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget") + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") } + positionLineWidget(widget, node, lineView, dims) + cm.display.input.setUneditable(node) + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text) } + else + { wrap.appendChild(node) } + signalLater(widget, "redraw") + } +} + +function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + ;(lineView.alignable || (lineView.alignable = [])).push(node) + var width = dims.wrapperWidth + node.style.left = dims.fixedPos + "px" + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth + node.style.paddingLeft = dims.gutterTotalWidth + "px" + } + node.style.width = width + "px" + } + if (widget.coverGutter) { + node.style.zIndex = 5 + node.style.position = "relative" + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" } + } +} + +function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;" + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)) + } + return widget.height = widget.node.parentNode.offsetHeight +} + +// Return true when the given mouse event happened in a widget +function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } +} + +// POSITION MEASUREMENT + +function paddingTop(display) {return display.lineSpace.offsetTop} +function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} +function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")) + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)} + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data } + return data +} + +function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } +function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth +} +function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight +} + +// Ensure the lineView.wrapping.heights array is populated. This is +// an array of bottom offsets for the lines that make up a drawn +// line. When lineWrapping is on, there might be more than one +// height. +function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping + var curWidth = wrapping && displayWidth(cm) + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = [] + if (wrapping) { + lineView.measure.width = curWidth + var rects = lineView.text.firstChild.getClientRects() + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1] + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top) } + } + } + heights.push(rect.bottom - rect.top) + } +} + +// Find a line map (mapping character offsets to text nodes) and a +// measurement cache for the given line number. (A line view might +// contain multiple lines when collapsed ranges are present.) +function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + { return {map: lineView.measure.map, cache: lineView.measure.cache} } + for (var i = 0; i < lineView.rest.length; i++) + { if (lineView.rest[i] == line) + { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } + for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) + { if (lineNo(lineView.rest[i$1]) > lineN) + { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } +} + +// Render a line into the hidden node display.externalMeasured. Used +// when measurement is needed for a line that's not in the viewport. +function updateExternalMeasurement(cm, line) { + line = visualLine(line) + var lineN = lineNo(line) + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN) + view.lineN = lineN + var built = view.built = buildLineContent(cm, view) + view.text = built.pre + removeChildrenAndAdd(cm.display.lineMeasure, built.pre) + return view +} + +// Get a {top, bottom, left, right} box (in line-local coordinates) +// for a given character. +function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) +} + +// Find a line view that corresponds to the given line number. +function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } +} + +// Measurement can be split in two steps, the set-up work that +// applies to the whole line, and the measurement of the actual +// character. Functions like coordsChar, that need to do a lot of +// measurements in a row, can thus ensure that the set-up work is +// only done once. +function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line) + var view = findViewForLine(cm, lineN) + if (view && !view.text) { + view = null + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)) + cm.curOp.forceUpdate = true + } + if (!view) + { view = updateExternalMeasurement(cm, line) } + + var info = mapFromLineView(view, line, lineN) + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } +} + +// Given a prepared measurement object, measures the position of an +// actual character (or fetches it from the cache). +function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1 } + var key = ch + (bias || ""), found + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key] + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect() } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect) + prepared.hasHeights = true + } + found = measureCharInner(cm, prepared, ch, bias) + if (!found.bogus) { prepared.cache[key] = found } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} +} + +var nullRect = {left: 0, right: 0, top: 0, bottom: 0} + +function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse, mStart, mEnd + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + mStart = map[i] + mEnd = map[i + 1] + if (ch < mStart) { + start = 0; end = 1 + collapse = "left" + } else if (ch < mEnd) { + start = ch - mStart + end = start + 1 + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart + start = end - 1 + if (ch >= mEnd) { collapse = "right" } + } + if (start != null) { + node = map[i + 2] + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias } + if (bias == "left" && start == 0) + { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2] + collapse = "left" + } } + if (bias == "right" && start == mEnd - mStart) + { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2] + collapse = "right" + } } + break + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} +} + +function getUsefulRect(rects, bias) { + var rect = nullRect + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect +} + +function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias) + var node = place.node, start = place.start, end = place.end, collapse = place.collapse + + var rect + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect() } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) } + if (rect.left || rect.right || start == 0) { break } + end = start + start = start - 1 + collapse = "right" + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right" } + var rects + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0] } + else + { rect = node.getBoundingClientRect() } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0] + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} } + else + { rect = nullRect } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top + var mid = (rtop + rbot) / 2 + var heights = prepared.view.measure.heights + var i = 0 + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i] + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot} + if (!rect.left && !rect.right) { result.bogus = true } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot } + + return result +} + +// Work around problem with bounding client rects on ranges being +// returned incorrectly when zoomed on IE10 and below. +function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI + var scaleY = screen.logicalYDPI / screen.deviceYDPI + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} +} + +function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {} + lineView.measure.heights = null + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { lineView.measure.caches[i] = {} } } + } +} + +function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null + removeChildren(cm.display.lineMeasure) + for (var i = 0; i < cm.display.view.length; i++) + { clearLineMeasurementCacheFor(cm.display.view[i]) } +} + +function clearCaches(cm) { + clearLineMeasurementCache(cm) + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true } + cm.display.lineNumChars = null +} + +function pageScrollX() { + // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 + // which causes page_Offset and bounding client rects to use + // different reference viewports and invalidate our calculations. + if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft +} +function pageScrollY() { + if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } + return window.pageYOffset || (document.documentElement || document.body).scrollTop +} + +// Converts a {top, bottom, left, right} box from line-local +// coordinates into another coordinate system. Context may be one of +// "line", "div" (display.lineDiv), "local"./null (editor), "window", +// or "page". +function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]) + rect.top += size; rect.bottom += size + } } } + if (context == "line") { return rect } + if (!context) { context = "local" } + var yOff = heightAtLine(lineObj) + if (context == "local") { yOff += paddingTop(cm.display) } + else { yOff -= cm.display.viewOffset } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect() + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()) + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()) + rect.left += xOff; rect.right += xOff + } + rect.top += yOff; rect.bottom += yOff + return rect +} + +// Coverts a box from "div" coords to another coordinate system. +// Context may be "window", "page", "div", or "local"./null. +function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX() + top -= pageScrollY() + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect() + left += localBox.left + top += localBox.top + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect() + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} +} + +function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line) } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) +} + +// Returns a box for a given cursor position, which may have an +// 'other' property containing the position of the secondary cursor +// on a bidi boundary. +// A cursor Pos(line, char, "before") is on the same visual line as `char - 1` +// and after `char - 1` in writing order of `char - 1` +// A cursor Pos(line, char, "after") is on the same visual line as `char` +// and before `char` in writing order of `char` +// Examples (upper-case letters are RTL, lower-case are LTR): +// Pos(0, 1, ...) +// before after +// ab a|b a|b +// aB a|B aB| +// Ab |Ab A|b +// AB B|A B|A +// Every position after the last character on a line is considered to stick +// to the last character on the line. +function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line) + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight) + if (right) { m.left = m.right; } else { m.right = m.left } + return intoCoordSystem(cm, lineObj, m, context) + } + var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky + if (ch >= lineObj.text.length) { + ch = lineObj.text.length + sticky = "before" + } else if (ch <= 0) { + ch = 0 + sticky = "after" + } + if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } + + function getBidi(ch, partPos, invert) { + var part = order[partPos], right = (part.level % 2) != 0 + return get(invert ? ch - 1 : ch, right != invert) + } + var partPos = getBidiPartAt(order, ch, sticky) + var other = bidiOther + var val = getBidi(ch, partPos, sticky == "before") + if (other != null) { val.other = getBidi(ch, other, sticky != "before") } + return val +} + +// Used to cheaply estimate the coordinates for a position. Used for +// intermediate scroll updates. +function estimateCoords(cm, pos) { + var left = 0 + pos = clipPos(cm.doc, pos) + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch } + var lineObj = getLine(cm.doc, pos.line) + var top = heightAtLine(lineObj) + paddingTop(cm.display) + return {left: left, right: left, top: top, bottom: top + lineObj.height} +} + +// Positions returned by coordsChar contain some extra information. +// xRel is the relative x position of the input coordinates compared +// to the found position (so xRel > 0 means the coordinates are to +// the right of the character position, for example). When outside +// is true, that means the coordinates lie outside the line's +// vertical range. +function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky) + pos.xRel = xRel + if (outside) { pos.outside = true } + return pos +} + +// Compute the character position closest to the given coordinates. +// Input must be lineSpace-local ("div" coordinate system). +function coordsChar(cm, x, y) { + var doc = cm.doc + y += cm.display.viewOffset + if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1 + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } + if (x < 0) { x = 0 } + + var lineObj = getLine(doc, lineN) + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y) + var merged = collapsedSpanAtEnd(lineObj) + var mergedPos = merged && merged.find(0, true) + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + { lineN = lineNo(lineObj = mergedPos.to.line) } + else + { return found } + } +} + +function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); } + var end = lineObj.text.length + var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0) + end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end) + return {begin: begin, end: end} +} + +function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) +} + +function coordsCharInner(cm, lineObj, lineNo, x, y) { + y -= heightAtLine(lineObj) + var begin = 0, end = lineObj.text.length + var preparedMeasure = prepareMeasureForLine(cm, lineObj) + var pos + var order = getOrder(lineObj, cm.doc.direction) + if (order) { + if (cm.options.lineWrapping) { + ;var assign; + ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign)) + } + pos = new Pos(lineNo, begin) + var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left + var dir = beginLeft < x ? 1 : -1 + var prevDiff, diff = beginLeft - x, prevPos + do { + prevDiff = diff + prevPos = pos + pos = moveVisually(cm, lineObj, pos, dir) + if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) { + pos = prevPos + break + } + diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x + } while ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff))) + if (Math.abs(diff) > Math.abs(prevDiff)) { + if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") } + pos = prevPos + } + } else { + var ch = findFirst(function (ch) { + var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line") + if (box.top > y) { + // For the cursor stickiness + end = Math.min(ch, end) + return true + } + else if (box.bottom <= y) { return false } + else if (box.left > x) { return true } + else if (box.right < x) { return false } + else { return (x - box.left < box.right - x) } + }, begin, end) + ch = skipExtendingChars(lineObj.text, ch, 1) + pos = new Pos(lineNo, ch, ch == end ? "before" : "after") + } + var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure) + if (y < coords.top || coords.bottom < y) { pos.outside = true } + pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0) + return pos +} + +var measureText +// Compute the default text height. +function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre") + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")) + measureText.appendChild(elt("br")) + } + measureText.appendChild(document.createTextNode("x")) + } + removeChildrenAndAdd(display.measure, measureText) + var height = measureText.offsetHeight / 50 + if (height > 3) { display.cachedTextHeight = height } + removeChildren(display.measure) + return height || 1 +} + +// Compute the default character width. +function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx") + var pre = elt("pre", [anchor]) + removeChildrenAndAdd(display.measure, pre) + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10 + if (width > 2) { display.cachedCharWidth = width } + return width || 10 +} + +// Do a bulk-read of the DOM positions and sizes needed to draw the +// view, so that we don't interleave reading and writing to the DOM. +function getDimensions(cm) { + var d = cm.display, left = {}, width = {} + var gutterLeft = d.gutters.clientLeft + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft + width[cm.options.gutters[i]] = n.clientWidth + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} +} + +// Computes display.scroller.scrollLeft + display.gutters.offsetWidth, +// but using getBoundingClientRect to get a sub-pixel-accurate +// result. +function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left +} + +// Returns a function that estimates the height of a line, to use as +// first approximation until the line becomes visible (and is thus +// properly measurable). +function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3) + return function (line) { + if (lineIsHidden(cm.doc, line)) { return 0 } + + var widgetsHeight = 0 + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } +} + +function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm) + doc.iter(function (line) { + var estHeight = est(line) + if (estHeight != line.height) { updateLineHeight(line, estHeight) } + }) +} + +// Given a mouse event, find the corresponding position. If liberal +// is false, it checks whether a gutter or scrollbar was clicked, +// and returns null if it was. forRect is used by rectangular +// selections, and tries to estimate a character position even for +// coordinates beyond the right of the text. +function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect() + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top } + catch (e) { return null } + var coords = coordsChar(cm, x, y), line + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)) + } + return coords +} + +// Find the view element corresponding to a given line. Return null +// when the line isn't visible. +function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom + if (n < 0) { return null } + var view = cm.display.view + for (var i = 0; i < view.length; i++) { + n -= view[i].size + if (n < 0) { return i } + } +} + +function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()) +} + +function prepareSelection(cm, primary) { + var doc = cm.doc, result = {} + var curFragment = result.cursors = document.createDocumentFragment() + var selFragment = result.selection = document.createDocumentFragment() + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) { continue } + var range = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var collapsed = range.empty() + if (collapsed || cm.options.showCursorWhenSelecting) + { drawSelectionCursor(cm, range.head, curFragment) } + if (!collapsed) + { drawSelectionRange(cm, range, selFragment) } + } + return result +} + +// Draws a cursor for the given range +function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) + cursor.style.left = pos.left + "px" + cursor.style.top = pos.top + "px" + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) + otherCursor.style.display = "" + otherCursor.style.left = pos.other.left + "px" + otherCursor.style.top = pos.other.top + "px" + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" + } +} + +// Draws the given range as a highlighted selection +function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc + var fragment = document.createDocumentFragment() + var padding = paddingH(cm.display), leftSide = padding.left + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right + + function add(left, top, width, bottom) { + if (top < 0) { top = 0 } + top = Math.round(top) + bottom = Math.round(bottom) + fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))) + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line) + var lineLen = lineObj.text.length + var start, end + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right + if (from == to) { + rightPos = leftPos + left = right = leftPos.left + } else { + rightPos = coords(to - 1, "right") + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp } + left = leftPos.left + right = rightPos.right + } + if (fromArg == null && from == 0) { left = leftSide } + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom) + left = leftSide + if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) } + } + if (toArg == null && to == lineLen) { right = rightSide } + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + { start = leftPos } + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + { end = rightPos } + if (left < leftSide + 1) { left = leftSide } + add(left, rightPos.top, right - left, rightPos.bottom) + }) + return {start: start, end: end} + } + + var sFrom = range.from(), sTo = range.to() + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch) + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) + var singleVLine = visualLine(fromLine) == visualLine(toLine) + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) + } + } + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top) } + } + + output.appendChild(fragment) +} + +// Cursor-blinking +function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display + clearInterval(display.blinker) + var on = true + display.cursorDiv.style.visibility = "" + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, + cm.options.cursorBlinkRate) } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden" } +} + +function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) } +} + +function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false + onBlur(cm) + } }, 100) +} + +function onFocus(cm, e) { + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e) + cm.state.focused = true + addClass(cm.display.wrapper, "CodeMirror-focused") + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset() + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730 + } + cm.display.input.receivedFocus() + } + restartBlink(cm) +} +function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e) + cm.state.focused = false + rmClass(cm.display.wrapper, "CodeMirror-focused") + } + clearInterval(cm.display.blinker) + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150) +} + +// Re-align line numbers and gutter marks to compensate for +// horizontal scrolling. +function alignHorizontally(cm) { + var display = cm.display, view = display.view + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft + var gutterW = display.gutters.offsetWidth, left = comp + "px" + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left } + if (view[i].gutterBackground) + { view[i].gutterBackground.style.left = left } + } + var align = view[i].alignable + if (align) { for (var j = 0; j < align.length; j++) + { align[j].style.left = left } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px" } +} + +// Used to ensure that the line number gutter is still the right +// size for the current document size. Returns true when an update +// is needed. +function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")) + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW + display.lineGutter.style.width = "" + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1 + display.lineNumWidth = display.lineNumInnerWidth + padding + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1 + display.lineGutter.style.width = display.lineNumWidth + "px" + updateGutterSpace(cm) + return true + } + return false +} + +// Read the actual heights of the rendered lines, and update their +// stored heights to match. +function updateHeightsInViewport(cm) { + var display = cm.display + var prevBottom = display.lineDiv.offsetTop + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height = (void 0) + if (cur.hidden) { continue } + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight + height = bot - prevBottom + prevBottom = bot + } else { + var box = cur.node.getBoundingClientRect() + height = box.bottom - box.top + } + var diff = cur.line.height - height + if (height < 2) { height = textHeight(display) } + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height) + updateWidgetHeight(cur.line) + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]) } } + } + } +} + +// Read and store the height of line widgets associated with the +// given line. +function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) + { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } } +} + +// Compute the lines that are visible in a given viewport (defaults +// the the current scroll position). viewport may contain top, +// height, and ensure (see op.scrollToPos) properties. +function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop + top = Math.floor(top - paddingTop(display)) + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line + if (ensureFrom < from) { + from = ensureFrom + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight) + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight) + to = ensureTo + } + } + return {from: from, to: Math.max(to, from + 1)} +} + +// Sync the scrollable area and scrollbars, ensure the viewport +// covers the visible area. +function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + cm.doc.scrollTop = val + if (!gecko) { updateDisplaySimple(cm, {top: val}) } + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val } + cm.display.scrollbars.setScrollTop(val) + if (gecko) { updateDisplaySimple(cm) } + startWorker(cm, 100) +} +// Sync scroller and scrollbar, ensure the gutter elements are +// aligned. +function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return } + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) + cm.doc.scrollLeft = val + alignHorizontally(cm) + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val } + cm.display.scrollbars.setScrollLeft(val) +} + +// Since the delta values reported on mouse wheel events are +// unstandardized between browsers and even browser versions, and +// generally horribly unpredictable, this code starts by measuring +// the scroll effect that the first few mouse wheel events have, +// and, from that, detects the way it can convert deltas to pixel +// offsets afterwards. +// +// The reason we want to know the amount a wheel event will scroll +// is that it gives us a chance to update the display before the +// actual scrolling happens, reducing flickering. + +var wheelSamples = 0; +var wheelPixelsPerUnit = null; +// Fill in a browser-detected starting value on browsers where we +// know one. These don't have to be accurate -- the result of them +// being wrong would just be a slight flicker on the first wheel +// scroll (if it is large enough). +if (ie) { wheelPixelsPerUnit = -.53 } +else if (gecko) { wheelPixelsPerUnit = 15 } +else if (chrome) { wheelPixelsPerUnit = -.7 } +else if (safari) { wheelPixelsPerUnit = -1/3 } + +function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail } + else if (dy == null) { dy = e.wheelDelta } + return {x: dx, y: dy} +} +function wheelEventPixels(e) { + var delta = wheelEventDelta(e) + delta.x *= wheelPixelsPerUnit + delta.y *= wheelPixelsPerUnit + return delta +} + +function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y + + var display = cm.display, scroll = display.scroller + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth + var canScrollY = scroll.scrollHeight > scroll.clientHeight + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur + break outer + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) } + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))) + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e) } + display.wheelStartX = null // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight + if (pixels < 0) { top = Math.max(0, top + pixels - 50) } + else { bot = Math.min(cm.doc.height, bot + pixels + 50) } + updateDisplaySimple(cm, {top: top, bottom: bot}) + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop + display.wheelDX = dx; display.wheelDY = dy + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX + var movedY = scroll.scrollTop - display.wheelStartY + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX) + display.wheelStartX = display.wheelStartY = null + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) + ++wheelSamples + }, 200) + } else { + display.wheelDX += dx; display.wheelDY += dy + } + } +} + +// SCROLLBARS + +// Prepare DOM reads needed to update the scrollbars. Done in one +// shot to minimize update/measure roundtrips. +function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth + var docH = Math.round(cm.doc.height + paddingVert(cm.display)) + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + } +} + +var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar") + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") + place(vert); place(horiz) + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") } + }) + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") } + }) + + this.checkedZeroWidth = false + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" } +}; + +NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1 + var needsV = measure.scrollHeight > measure.clientHeight + 1 + var sWidth = measure.nativeBarWidth + + if (needsV) { + this.vert.style.display = "block" + this.vert.style.bottom = needsH ? sWidth + "px" : "0" + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0) + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" + } else { + this.vert.style.display = "" + this.vert.firstChild.style.height = "0" + } + + if (needsH) { + this.horiz.style.display = "block" + this.horiz.style.right = needsV ? sWidth + "px" : "0" + this.horiz.style.left = measure.barLeft + "px" + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) + this.horiz.firstChild.style.width = + Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px" + } else { + this.horiz.style.display = "" + this.horiz.firstChild.style.width = "0" + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack() } + this.checkedZeroWidth = true + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} +}; + +NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") } +}; + +NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") } +}; + +NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px" + this.horiz.style.height = this.vert.style.width = w + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none" + this.disableHoriz = new Delayed + this.disableVert = new Delayed +}; + +NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto" + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // right corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect() + var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) + : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1) + if (elt != bar) { bar.style.pointerEvents = "none" } + else { delay.set(1000, maybeDisable) } + } + delay.set(1000, maybeDisable) +}; + +NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode + parent.removeChild(this.horiz) + parent.removeChild(this.vert) +}; + +var NullScrollbars = function () {}; + +NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; +NullScrollbars.prototype.setScrollLeft = function () {}; +NullScrollbars.prototype.setScrollTop = function () {}; +NullScrollbars.prototype.clear = function () {}; + +function updateScrollbars(cm, measure) { + if (!measure) { measure = measureForScrollbars(cm) } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight + updateScrollbarsInner(cm, measure) + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm) } + updateScrollbarsInner(cm, measureForScrollbars(cm)) + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight + } +} + +// Re-synchronize the fake scrollbars with the actual size of the +// content. +function updateScrollbarsInner(cm, measure) { + var d = cm.display + var sizes = d.scrollbars.update(measure) + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px" + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px" + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block" + d.scrollbarFiller.style.height = sizes.bottom + "px" + d.scrollbarFiller.style.width = sizes.right + "px" + } else { d.scrollbarFiller.style.display = "" } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block" + d.gutterFiller.style.height = sizes.bottom + "px" + d.gutterFiller.style.width = measure.gutterWidth + "px" + } else { d.gutterFiller.style.display = "" } +} + +var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} + +function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear() + if (cm.display.scrollbars.addClass) + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) } + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller) + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) } + }) + node.setAttribute("cm-not-content", "true") + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos) } + else { setScrollTop(cm, pos) } + }, cm) + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) } +} + +// SCROLLING THINGS INTO VIEW + +// If an editor sits on the top or bottom of the window, partially +// scrolled out of view, this ensures that the cursor is visible. +function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null + if (rect.top + box.top < 0) { doScroll = true } + else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")) + cm.display.lineSpace.appendChild(scrollNode) + scrollNode.scrollIntoView(doScroll) + cm.display.lineSpace.removeChild(scrollNode) + } +} + +// Scroll a given position into view (immediately), verifying that +// it actually became visible (as line heights are accurately +// measured, the position of something may 'drift' during drawing). +function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0 } + var rect + for (var limit = 0; limit < 5; limit++) { + var changed = false + var coords = cursorCoords(cm, pos) + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end) + rect = {left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin} + var scrollPos = calculateScrollPos(cm, rect) + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop) + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft) + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true } + } + if (!changed) { break } + } + return rect +} + +// Scroll a given set of coordinates into view (immediately). +function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect) + if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) } +} + +// Calculate a new scroll position needed to scroll the given +// rectangle into view. Returns an object with scrollTop and +// scrollLeft properties. When these are undefined, the +// vertical/horizontal position does not need to be adjusted. +function calculateScrollPos(cm, rect) { + var display = cm.display, snapMargin = textHeight(cm.display) + if (rect.top < 0) { rect.top = 0 } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop + var screen = displayHeight(cm), result = {} + if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen } + var docBottom = cm.doc.height + paddingVert(display) + var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top + } else if (rect.bottom > screentop + screen) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen) + if (newTop != screentop) { result.scrollTop = newTop } + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) + var tooWide = rect.right - rect.left > screenw + if (tooWide) { rect.right = rect.left + screenw } + if (rect.left < 10) + { result.scrollLeft = 0 } + else if (rect.left < screenleft) + { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) } + else if (rect.right > screenw + screenleft - 3) + { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw } + return result +} + +// Store a relative adjustment to the scroll position in the current +// operation (to be applied when the operation finishes). +function addToScrollPos(cm, left, top) { + if (left != null || top != null) { resolveScrollToPos(cm) } + if (left != null) + { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left } + if (top != null) + { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top } +} + +// Make sure that at the end of the operation the current cursor is +// shown. +function ensureCursorVisible(cm) { + resolveScrollToPos(cm) + var cur = cm.getCursor(), from = cur, to = cur + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur + to = Pos(cur.line, cur.ch + 1) + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin} +} + +// When an operation has its scrollToPos property set, and another +// scroll action is applied before the end of the operation, this +// 'simulates' scrolling that position into view in a cheap way, so +// that the effect of intermediate scroll commands is not ignored. +function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - range.margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + range.margin + }) + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop) + } +} + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +var nextOpId = 0 +// Start a new operation. +function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +function endOperation(cm) { + var op = cm.curOp + finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null } + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + var ops = group.ops + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]) } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]) } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]) } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]) } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]) } +} + +function endOperation_R1(op) { + var cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) { findMaxLine(cm) } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + var cm = op.cm, display = cm.display + if (op.updatedDisplay) { updateHeightsInViewport(cm) } + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 + cm.display.sizerWidth = op.adjustWidthTo + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection(op.focus) } +} + +function endOperation_W2(op) { + var cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) } + cm.display.maxLineChanged = false + } + + var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus) } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure) } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure) } + + if (op.selectionChanged) { restartBlink(cm) } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing) } + if (takeFocus) { ensureFocus(op.cm) } +} + +function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)) + display.scrollbars.setScrollTop(doc.scrollTop) + display.scroller.scrollTop = doc.scrollTop + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)) + display.scrollbars.setScrollLeft(doc.scrollLeft) + display.scroller.scrollLeft = doc.scrollLeft + alignHorizontally(cm) + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + maybeScrollWindow(cm, rect) + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs) } + if (op.update) + { op.update.finish() } +} + +// Run the given function in an operation +function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +function operation(cm, f) { + return function() { + if (cm.curOp) { return f.apply(cm, arguments) } + startOperation(cm) + try { return f.apply(cm, arguments) } + finally { endOperation(cm) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +function methodOp(f) { + return function() { + if (this.curOp) { return f.apply(this, arguments) } + startOperation(this) + try { return f.apply(this, arguments) } + finally { endOperation(this) } + } +} +function docMethodOp(f) { + return function() { + var cm = this.cm + if (!cm || cm.curOp) { return f.apply(this, arguments) } + startOperation(cm) + try { return f.apply(this, arguments) } + finally { endOperation(cm) } + } +} + +// Updates the display.view data structure for a given change to the +// document. From and to are in pre-change coordinates. Lendiff is +// the amount of lines added or subtracted by the change. This is +// used for changes that span multiple lines, or change the way +// lines are divided into visual lines. regLineChange (below) +// registers single-line changes. +function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first } + if (to == null) { to = cm.doc.first + cm.doc.size } + if (!lendiff) { lendiff = 0 } + + var display = cm.display + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from } + + cm.curOp.viewChanged = true + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm) } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm) + } else { + display.viewFrom += lendiff + display.viewTo += lendiff + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm) + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cut) { + display.view = display.view.slice(cut.index) + display.viewFrom = cut.lineN + display.viewTo += lendiff + } else { + resetView(cm) + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1) + if (cut$1) { + display.view = display.view.slice(0, cut$1.index) + display.viewTo = cut$1.lineN + } else { + resetView(cm) + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1) + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)) + display.viewTo += lendiff + } else { + resetView(cm) + } + } + + var ext = display.externalMeasured + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null } + } +} + +// Register a change to a single line. Type must be one of "text", +// "gutter", "class", "widget" +function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true + var display = cm.display, ext = cm.display.externalMeasured + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)] + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []) + if (indexOf(arr, type) == -1) { arr.push(type) } +} + +// Clear the view. +function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first + cm.display.view = [] + cm.display.viewOffset = 0 +} + +function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom + for (var i = 0; i < index; i++) + { n += view[i].size } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN + index++ + } else { + diff = n - oldN + } + oldN += diff; newN += diff + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { return null } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size + index += dir + } + return {index: index, lineN: newN} +} + +// Force the view to cover a given range, adding empty view element +// or clipping off existing ones as needed. +function adjustView(cm, from, to) { + var display = cm.display, view = display.view + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to) + display.viewFrom = from + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)) } + display.viewFrom = from + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)) } + } + display.viewTo = to +} + +// Count the number of lines in the view whose DOM representation is +// out of date (or nonexistent). +function countDirtyView(cm) { + var view = cm.display.view, dirty = 0 + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty } + } + return dirty +} + +// HIGHLIGHT WORKER + +function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)) } +} + +function highlightWorker(cm) { + var doc = cm.doc + if (doc.frontier < doc.first) { doc.frontier = doc.first } + if (doc.frontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)) + var changedLines = [] + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true) + line.styles = highlighted.styles + var oldCls = line.styleClasses, newCls = highlighted.classes + if (newCls) { line.styleClasses = newCls } + else if (oldCls) { line.styleClasses = null } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass) + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] } + if (ischange) { changedLines.push(doc.frontier) } + line.stateAfter = tooLong ? state : copyState(doc.mode, state) + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, state) } + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null + } + ++doc.frontier + if (+new Date > end) { + startWorker(cm, cm.options.workDelay) + return true + } + }) + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text") } + }) } +} + +// DISPLAY DRAWING + +var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display + + this.viewport = viewport + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport) + this.editorIsHidden = !display.wrapper.offsetWidth + this.wrapperHeight = display.wrapper.clientHeight + this.wrapperWidth = display.wrapper.clientWidth + this.oldDisplayWidth = displayWidth(cm) + this.force = force + this.dims = getDimensions(cm) + this.events = [] +}; + +DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments) } +}; +DisplayUpdate.prototype.finish = function () { + var this$1 = this; + + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this$1.events[i]) } +}; + +function maybeClipScrollbars(cm) { + var display = cm.display + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth + display.heightForcer.style.height = scrollGap(cm) + "px" + display.sizer.style.marginBottom = -display.nativeBarWidth + "px" + display.sizer.style.borderRightWidth = scrollGap(cm) + "px" + display.scrollbarsClipped = true + } +} + +// Does the actual updating of the line display. Bails out +// (returning false) when there is nothing to be done and forced is +// false. +function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc + + if (update.editorIsHidden) { + resetView(cm) + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm) + update.dims = getDimensions(cm) + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) + var to = Math.min(end, update.visible.to + cm.options.viewportMargin) + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from) + to = visualLineEndNo(cm.doc, to) + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth + adjustView(cm, from, to) + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px" + + var toUpdate = countDirtyView(cm) + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt() + if (toUpdate > 4) { display.lineDiv.style.display = "none" } + patchDisplay(cm, display.updateLineNumbers, update.dims) + if (toUpdate > 4) { display.lineDiv.style.display = "" } + display.renderedView = display.view + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() } + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv) + removeChildren(display.selectionDiv) + display.gutters.style.height = display.sizer.style.minHeight = 0 + + if (different) { + display.lastWrapHeight = update.wrapperHeight + display.lastWrapWidth = update.wrapperWidth + startWorker(cm, 400) + } + + display.updateLineNumbers = null + + return true +} + +function postUpdateDisplay(cm, update) { + var viewport = update.viewport + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport) + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + { break } + } + if (!updateDisplayIfNeeded(cm, update)) { break } + updateHeightsInViewport(cm) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + } + + update.signal(cm, "update", cm) + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo) + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo + } +} + +function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport) + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm) + postUpdateDisplay(cm, update) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.finish() + } +} + +// Sync the actual display DOM structure with display.view, removing +// nodes for lines that are no longer in view, and creating the ones +// that are not there yet, and updating the ones that are out of +// date. +function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers + var container = display.lineDiv, cur = container.firstChild + + function rm(node) { + var next = node.nextSibling + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none" } + else + { node.parentNode.removeChild(node) } + return next + } + + var view = display.view, lineN = display.viewFrom + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims) + container.insertBefore(node, cur) + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur) } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false } + updateLineForChanges(cm, lineView, lineN, dims) + } + if (updateNumber) { + removeChildren(lineView.lineNumber) + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) + } + cur = lineView.node.nextSibling + } + lineN += lineView.size + } + while (cur) { cur = rm(cur) } +} + +function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth + cm.display.sizer.style.marginLeft = width + "px" +} + +function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px" + cm.display.heightForcer.style.top = measure.docHeight + "px" + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px" +} + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters + removeChildren(gutters) + var i = 0 + for (; i < specs.length; ++i) { + var gutterClass = specs[i] + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt + gElt.style.width = (cm.display.lineNumWidth || 1) + "px" + } + } + gutters.style.display = i ? "" : "none" + updateGutterSpace(cm) +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers") + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]) + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0) + options.gutters.splice(found, 1) + } +} + +// Selection objects are immutable. A new one is created every time +// the selection changes. A selection is one or more non-overlapping +// (and non-touching) ranges, sorted, and an integer that indicates +// which one is the primary selection (the one that's scrolled into +// view, that getCursor returns, etc). +var Selection = function(ranges, primIndex) { + this.ranges = ranges + this.primIndex = primIndex +}; + +Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; + +Selection.prototype.equals = function (other) { + var this$1 = this; + + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this$1.ranges[i], there = other.ranges[i] + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } + } + return true +}; + +Selection.prototype.deepCopy = function () { + var this$1 = this; + + var out = [] + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) } + return new Selection(out, this.primIndex) +}; + +Selection.prototype.somethingSelected = function () { + var this$1 = this; + + for (var i = 0; i < this.ranges.length; i++) + { if (!this$1.ranges[i].empty()) { return true } } + return false +}; + +Selection.prototype.contains = function (pos, end) { + var this$1 = this; + + if (!end) { end = pos } + for (var i = 0; i < this.ranges.length; i++) { + var range = this$1.ranges[i] + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 +}; + +var Range = function(anchor, head) { + this.anchor = anchor; this.head = head +}; + +Range.prototype.from = function () { return minPos(this.anchor, this.head) }; +Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; +Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; + +// Take an unsorted, potentially overlapping set of ranges, and +// build a selection out of it. 'Consumes' ranges array (modifying +// it). +function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex] + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }) + primIndex = indexOf(ranges, prim) + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1] + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head + if (i <= primIndex) { --primIndex } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) + } + } + return new Selection(ranges, primIndex) +} + +function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) +} + +// Compute the position of the end of a change (its 'to' property +// refers to the pre-change end). +function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) +} + +// Adjust a position to refer to the post-change position of the +// same text, or the end of the change if the change covers it. +function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch } + return Pos(line, ch) +} + +function computeSelAfterChange(doc, change) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i] + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))) + } + return normalizeSelection(out, doc.sel.primIndex) +} + +function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } +} + +// Used by replaceSelections to allow moving the selection to the +// start or around the replaced test. Hint may be "start" or "around". +function computeReplacedSel(doc, changes, hint) { + var out = [] + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev + for (var i = 0; i < changes.length; i++) { + var change = changes[i] + var from = offsetPos(change.from, oldPrev, newPrev) + var to = offsetPos(changeEnd(change), oldPrev, newPrev) + oldPrev = change.to + newPrev = to + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0 + out[i] = new Range(inv ? to : from, inv ? from : to) + } else { + out[i] = new Range(from, from) + } + } + return new Selection(out, doc.sel.primIndex) +} + +// Used to get the editor into a consistent state again when options change. + +function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption) + resetModeState(cm) +} + +function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + }) + cm.doc.frontier = cm.doc.first + startWorker(cm, 100) + cm.state.modeGen++ + if (cm.curOp) { regChange(cm) } +} + +// DOCUMENT DATA STRUCTURE + +// By default, updates that start and end at the beginning of a line +// are treated specially, in order to make the association of line +// widgets and marker elements with the text behave more intuitive. +function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) +} + +// Perform a change on the document data structure. +function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight) + signalLater(line, "change", line, change) + } + function linesFor(start, end) { + var result = [] + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)) } + return result + } + + var from = change.from, to = change.to, text = change.text + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line) + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)) + doc.remove(text.length, doc.size - text.length) + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1) + update(lastLine, lastLine.text, lastSpans) + if (nlines) { doc.remove(from.line, nlines) } + if (added.length) { doc.insert(from.line, added) } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans) + } else { + var added$1 = linesFor(1, text.length - 1) + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)) + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + doc.insert(from.line + 1, added$1) + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)) + doc.remove(from.line + 1, nlines) + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans) + var added$2 = linesFor(1, text.length - 1) + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) } + doc.insert(from.line + 1, added$2) + } + + signalLater(doc, "change", doc, change) +} + +// Call f for all linked documents. +function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i] + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared) + propagate(rel.doc, doc, shared) + } } + } + propagate(doc, null, true) +} + +// Attach a document to an editor. +function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc + doc.cm = cm + estimateLineHeights(cm) + loadMode(cm) + setDirectionClass(cm) + if (!cm.options.lineWrapping) { findMaxLine(cm) } + cm.options.mode = doc.modeOption + regChange(cm) +} + +function setDirectionClass(cm) { + ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl") +} + +function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm) + regChange(cm) + }) +} + +function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = [] + this.undoDepth = Infinity + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0 + this.lastOp = this.lastSelOp = null + this.lastOrigin = this.lastSelOrigin = null + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1 +} + +// Create a history change event from an updateDoc-style change +// object. +function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)} + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1) + linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true) + return histChange +} + +// Pop all selection events off the end of a history array. Stop at +// a change event. +function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array) + if (last.ranges) { array.pop() } + else { break } + } +} + +// Find the top change event in the history. Pop off selection +// events that are in the way. +function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done) + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop() + return lst(hist.done) + } +} + +// Register a change in the history. Merges changes that are within +// a single operation, or are close together with an origin that +// allows merging (starting with "+") into a single event. +function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history + hist.undone.length = 0 + var time = +new Date, cur + var last + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes) + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change) + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)) + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done) + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done) } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation} + hist.done.push(cur) + while (hist.done.length > hist.undoDepth) { + hist.done.shift() + if (!hist.done[0].ranges) { hist.done.shift() } + } + } + hist.done.push(selAfter) + hist.generation = ++hist.maxGeneration + hist.lastModTime = hist.lastSelTime = time + hist.lastOp = hist.lastSelOp = opId + hist.lastOrigin = hist.lastSelOrigin = change.origin + + if (!last) { signal(doc, "historyAdded") } +} + +function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0) + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) +} + +// Called whenever the selection changes, sets the new selection as +// the pending selection in the history, and pushes the old pending +// selection into the 'done' array when it was significantly +// different (in number of selected ranges, emptiness, or time). +function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel } + else + { pushSelectionToHistory(sel, hist.done) } + + hist.lastSelTime = +new Date + hist.lastSelOrigin = origin + hist.lastSelOp = opId + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone) } +} + +function pushSelectionToHistory(sel, dest) { + var top = lst(dest) + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel) } +} + +// Used to store marked span information in the history. +function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0 + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans } + ++n + }) +} + +// When un/re-doing restores text containing marked spans, those +// that have been explicitly cleared should not be restored. +function removeClearedSpans(spans) { + if (!spans) { return null } + var out + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } } + else if (out) { out.push(spans[i]) } + } + return !out ? spans : out.length ? out : null +} + +// Retrieve and filter the old marked spans stored in a change event. +function getOldSpans(doc, change) { + var found = change["spans_" + doc.id] + if (!found) { return null } + var nw = [] + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])) } + return nw +} + +// Used for un/re-doing changes from the history. Combines the +// result of computing the existing spans with the set of spans that +// existed in the history (so that deleting around a span and then +// undoing brings back the span). +function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change) + var stretched = stretchSpansOverChange(doc, change) + if (!old) { return stretched } + if (!stretched) { return old } + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i] + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j] + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span) + } + } else if (stretchCur) { + old[i] = stretchCur + } + } + return old +} + +// Used both to provide a JSON-safe object in .getHistory, and, when +// detaching a document, to split the history in two +function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = [] + for (var i = 0; i < events.length; ++i) { + var event = events[i] + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event) + continue + } + var changes = event.changes, newChanges = [] + copy.push({changes: newChanges}) + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = (void 0) + newChanges.push({from: change.from, to: change.to, text: change.text}) + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop] + delete change[prop] + } + } } } + } + } + return copy +} + +// The 'scroll' parameter given to many of these indicated whether +// the new cursor position should be scrolled into view after +// modifying the selection. + +// If shift is held or the extend flag is set, extends a range to +// include a given position (and optionally a second position). +// Otherwise, simply returns the range between the given positions. +// Used for cursor motion and such. +function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor + if (other) { + var posBefore = cmp(head, anchor) < 0 + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head + head = other + } else if (posBefore != (cmp(head, other) < 0)) { + head = other + } + } + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } +} + +// Extend the primary selection range, discard the rest. +function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options) +} + +// Extend all selections (pos is an array of selections with length +// equal the number of selections) +function extendSelections(doc, heads, options) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) } + var newSel = normalizeSelection(out, doc.sel.primIndex) + setSelection(doc, newSel, options) +} + +// Updates a single range in the selection. +function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0) + ranges[i] = range + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options) +} + +// Reset the selection to a single range. +function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options) +} + +// Give beforeSelectionChange handlers a change to influence a +// selection update. +function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + var this$1 = this; + + this.ranges = [] + for (var i = 0; i < ranges.length; i++) + { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)) } + }, + origin: options && options.origin + } + signal(doc, "beforeSelectionChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) } + if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } + else { return sel } +} + +function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done) + if (last && last.ranges) { + done[done.length - 1] = sel + setSelectionNoUndo(doc, sel, options) + } else { + setSelection(doc, sel, options) + } +} + +// Set a new selection. +function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options) + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options) +} + +function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(doc, sel, options) } + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1) + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)) + + if (!(options && options.scroll === false) && doc.cm) + { ensureCursorVisible(doc.cm) } +} + +function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true + signalCursorActivity(doc.cm) + } + signalLater(doc, "cursorActivity", doc) +} + +// Verify that the selection does not partially select any atomic +// marked ranges. +function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll) +} + +// Return a selection that does not partially select any atomic +// ranges. +function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i) } + out[i] = new Range(newAnchor, newHead) + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel +} + +function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line) + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter") + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} + } + } + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = (void 0) + if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } + } + + var far = m.find(dir < 0 ? -1 : 1) + if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null) } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos +} + +// Ensure a given position is not inside an atomic range. +function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1 + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)) + if (!found) { + doc.cantEdit = true + return Pos(doc.first, 0) + } + return found +} + +function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } +} + +function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll) +} + +// UPDATING + +// Allow "beforeChange" event handlers to influence a change +function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + } + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from) } + if (to) { obj.to = clipPos(doc, to) } + if (text) { obj.text = text } + if (origin !== undefined) { obj.origin = origin } + } } + signal(doc, "beforeChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) } + + if (obj.canceled) { return null } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} +} + +// Apply a change to a document, and add it to the document's +// history, and propagating it to all linked documents. +function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } + if (doc.cm.state.suppressEdits) { return } + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true) + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to) + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) } + } else { + makeChangeInner(doc, change) + } +} + +function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change) + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN) + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)) + var rebased = [] + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)) + }) +} + +// Revert a change stored in a document's history. +function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0 + for (; i < source.length; i++) { + event = source[i] + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null + + for (;;) { + event = source.pop() + if (event.ranges) { + pushSelectionToHistory(event, dest) + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}) + return + } + selAfter = event + } + else { break } + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = [] + pushSelectionToHistory(selAfter, dest) + dest.push({changes: antiChanges, generation: hist.generation}) + hist.generation = event.generation || ++hist.maxGeneration + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange") + + var loop = function ( i ) { + var change = event.changes[i] + change.origin = type + if (filter && !filterChange(doc, change, false)) { + source.length = 0 + return {} + } + + antiChanges.push(historyChangeFromChange(doc, change)) + + var after = i ? computeSelAfterChange(doc, change) : lst(source) + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)) + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) } + var rebased = [] + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)) + }) + }; + + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } +} + +// Sub-views need their line numbers shifted when text is added +// above or below them in the parent document. +function shiftDoc(doc, distance) { + if (distance == 0) { return } + doc.first += distance + doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( + Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch) + ); }), doc.sel.primIndex) + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance) + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + { regLineChange(doc.cm, l, "gutter") } + } +} + +// More lower-level change function, handling only a single document +// (not linked ones). +function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)) + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line) + shiftDoc(doc, shift) + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin} + } + var last = doc.lastLine() + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin} + } + + change.removed = getBetween(doc, change.from, change.to) + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change) } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) } + else { updateDoc(doc, change, spans) } + setSelectionNoUndo(doc, selAfter, sel_dontScroll) +} + +// Handle the interaction of a change to a document with the editor +// that this document is part of. +function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to + + var recomputeMaxLength = false, checkWidthStart = from.line + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))) + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true + return true + } + }) + } + + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm) } + + updateDoc(doc, change, spans, estimateHeight(cm)) + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line) + if (len > display.maxLineLength) { + display.maxLine = line + display.maxLineLength = len + display.maxLineChanged = true + recomputeMaxLength = false + } + }) + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true } + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line) + startWorker(cm, 400) + + var lendiff = change.text.length - (to.line - from.line) - 1 + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm) } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text") } + else + { regChange(cm, from.line, to.line + 1, lendiff) } + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change") + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + } + if (changeHandler) { signalLater(cm, "change", cm, obj) } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) } + } + cm.display.selForContextMenu = null +} + +function replaceRange(doc, code, from, to, origin) { + if (!to) { to = from } + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp } + if (typeof code == "string") { code = doc.splitLines(code) } + makeChange(doc, {from: from, to: to, text: code, origin: origin}) +} + +// Rebasing/resetting history to deal with externally-sourced changes + +function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff + } else if (from < pos.line) { + pos.line = from + pos.ch = 0 + } +} + +// Tries to rebase an array of history events given a change in the +// document. If the change touches the same lines as the event, the +// event, and everything 'behind' it, is discarded. If the change is +// before the event, the event's positions are updated. Uses a +// copy-on-write scheme for the positions, to avoid having to +// reallocate them all on every rebase, but also avoid problems with +// shared position objects being unsafely updated. +function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff) + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff) + } + continue + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1] + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch) + cur.to = Pos(cur.to.line + diff, cur.to.ch) + } else if (from <= cur.to.line) { + ok = false + break + } + } + if (!ok) { + array.splice(0, i + 1) + i = 0 + } + } +} + +function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1 + rebaseHistArray(hist.done, from, to, diff) + rebaseHistArray(hist.undone, from, to, diff) +} + +// Utility for applying a change to a line by handle or number, +// returning the number and optionally registering the line as +// changed. +function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) } + else { no = lineNo(handle) } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) } + return line +} + +// The document is represented as a BTree consisting of leaves, with +// chunk of lines in them, and branches, with up to ten leaves or +// other branch nodes below them. The top node is always a branch +// node, and is the document object itself (meaning it has +// additional methods and properties). +// +// All nodes have parent links. The tree is used both to go from +// line numbers to line objects, and to go from objects to numbers. +// It also indexes by height, and is used to convert between height +// and line object, and to find the total height of the document. +// +// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + +var LeafChunk = function(lines) { + var this$1 = this; + + this.lines = lines + this.parent = null + var height = 0 + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this$1 + height += lines[i].height + } + this.height = height +}; + +LeafChunk.prototype.chunkSize = function () { return this.lines.length }; + +// Remove the n lines at offset 'at'. +LeafChunk.prototype.removeInner = function (at, n) { + var this$1 = this; + + for (var i = at, e = at + n; i < e; ++i) { + var line = this$1.lines[i] + this$1.height -= line.height + cleanUpLine(line) + signalLater(line, "delete") + } + this.lines.splice(at, n) +}; + +// Helper used to collapse a small branch into a single leaf. +LeafChunk.prototype.collapse = function (lines) { + lines.push.apply(lines, this.lines) +}; + +// Insert the given array of lines at offset 'at', count them as +// having the given height. +LeafChunk.prototype.insertInner = function (at, lines, height) { + var this$1 = this; + + this.height += height + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)) + for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 } +}; + +// Used to iterate over a part of the tree. +LeafChunk.prototype.iterN = function (at, n, op) { + var this$1 = this; + + for (var e = at + n; at < e; ++at) + { if (op(this$1.lines[at])) { return true } } +}; + +var BranchChunk = function(children) { + var this$1 = this; + + this.children = children + var size = 0, height = 0 + for (var i = 0; i < children.length; ++i) { + var ch = children[i] + size += ch.chunkSize(); height += ch.height + ch.parent = this$1 + } + this.size = size + this.height = height + this.parent = null +}; + +BranchChunk.prototype.chunkSize = function () { return this.size }; + +BranchChunk.prototype.removeInner = function (at, n) { + var this$1 = this; + + this.size -= n + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height + child.removeInner(at, rm) + this$1.height -= oldHeight - child.height + if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null } + if ((n -= rm) == 0) { break } + at = 0 + } else { at -= sz } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = [] + this.collapse(lines) + this.children = [new LeafChunk(lines)] + this.children[0].parent = this + } +}; + +BranchChunk.prototype.collapse = function (lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) } +}; + +BranchChunk.prototype.insertInner = function (at, lines, height) { + var this$1 = this; + + this.size += lines.length + this.height += height + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at <= sz) { + child.insertInner(at, lines, height) + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25 + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)) + child.height -= leaf.height + this$1.children.splice(++i, 0, leaf) + leaf.parent = this$1 + } + child.lines = child.lines.slice(0, remaining) + this$1.maybeSpill() + } + break + } + at -= sz + } +}; + +// When a node has grown, check whether it should be split. +BranchChunk.prototype.maybeSpill = function () { + if (this.children.length <= 10) { return } + var me = this + do { + var spilled = me.children.splice(me.children.length - 5, 5) + var sibling = new BranchChunk(spilled) + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children) + copy.parent = me + me.children = [copy, sibling] + me = copy + } else { + me.size -= sibling.size + me.height -= sibling.height + var myIndex = indexOf(me.parent.children, me) + me.parent.children.splice(myIndex + 1, 0, sibling) + } + sibling.parent = me.parent + } while (me.children.length > 10) + me.parent.maybeSpill() +}; + +BranchChunk.prototype.iterN = function (at, n, op) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var used = Math.min(n, sz - at) + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0 + } else { at -= sz } + } +}; + +// Line widgets are block elements displayed above or below a line. + +var LineWidget = function(doc, node, options) { + var this$1 = this; + + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this$1[opt] = options[opt] } } } + this.doc = doc + this.node = node +}; + +LineWidget.prototype.clear = function () { + var this$1 = this; + + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line) + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } } + if (!ws.length) { line.widgets = null } + var height = widgetHeight(this) + updateLineHeight(line, Math.max(0, line.height - height)) + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height) + regLineChange(cm, no, "widget") + }) + signalLater(cm, "lineWidgetCleared", cm, this, no) + } +}; + +LineWidget.prototype.changed = function () { + var this$1 = this; + + var oldH = this.height, cm = this.doc.cm, line = this.line + this.height = null + var diff = widgetHeight(this) - oldH + if (!diff) { return } + updateLineHeight(line, line.height + diff) + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true + adjustScrollWhenAboveVisible(cm, line, diff) + signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)) + }) + } +}; +eventMixin(LineWidget) + +function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollPos(cm, null, diff) } +} + +function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options) + var cm = doc.cm + if (cm && widget.noHScroll) { cm.display.alignWidgets = true } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []) + if (widget.insertAt == null) { widgets.push(widget) } + else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) } + widget.line = line + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop + updateLineHeight(line, line.height + widgetHeight(widget)) + if (aboveVisible) { addToScrollPos(cm, null, widget.height) } + cm.curOp.forceUpdate = true + } + return true + }) + signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) + return widget +} + +// TEXTMARKERS + +// Created with markText and setBookmark methods. A TextMarker is a +// handle that can be used to clear or find a marked position in the +// document. Line objects hold arrays (markedSpans) containing +// {from, to, marker} object pointing to such marker objects, and +// indicating that such a marker is present on that line. Multiple +// lines may point to the same marker when it spans across lines. +// The spans will have null for their from/to properties when the +// marker continues beyond the start/end of the line. Markers have +// links back to the lines they currently touch. + +// Collapsed markers have unique ids, in order to be able to order +// them, which is needed for uniquely determining an outer marker +// when they overlap (they may nest, but not partially overlap). +var nextMarkerId = 0 + +var TextMarker = function(doc, type) { + this.lines = [] + this.type = type + this.doc = doc + this.id = ++nextMarkerId +}; + +// Clear the marker. +TextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp + if (withOp) { startOperation(cm) } + if (hasHandler(this, "clear")) { + var found = this.find() + if (found) { signalLater(this, "clear", found.from, found.to) } + } + var min = null, max = null + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") } + else if (cm) { + if (span.to != null) { max = lineNo(line) } + if (span.from != null) { min = lineNo(line) } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span) + if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) + { updateLineHeight(line, textHeight(cm.display)) } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { + var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual) + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual + cm.display.maxLineLength = len + cm.display.maxLineChanged = true + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) } + this.lines.length = 0 + this.explicitlyCleared = true + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false + if (cm) { reCheckSelection(cm.doc) } + } + if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) } + if (withOp) { endOperation(cm) } + if (this.parent) { this.parent.clear() } +}; + +// Find the position of the marker in the document. Returns a {from, +// to} object by default. Side can be passed to get a specific side +// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the +// Pos objects returned contain a line object, rather than a line +// number (used to prevent looking up the same line twice). +TextMarker.prototype.find = function (side, lineObj) { + var this$1 = this; + + if (side == null && this.type == "bookmark") { side = 1 } + var from, to + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from) + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to) + if (side == 1) { return to } + } + } + return from && {from: from, to: to} +}; + +// Signals that the marker's widget changed, and surrounding layout +// should be recomputed. +TextMarker.prototype.changed = function () { + var this$1 = this; + + var pos = this.find(-1, true), widget = this, cm = this.doc.cm + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line) + var view = findViewForLine(cm, lineN) + if (view) { + clearLineMeasurementCacheFor(view) + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true + } + cm.curOp.updateMaxLine = true + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height + widget.height = null + var dHeight = widgetHeight(widget) - oldHeight + if (dHeight) + { updateLineHeight(line, line.height + dHeight) } + } + signalLater(cm, "markerChanged", cm, this$1) + }) +}; + +TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) } + } + this.lines.push(line) +}; + +TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1) + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) + } +}; +eventMixin(TextMarker) + +// Create a marker, wire it up to the right lines, and +function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to) + if (options) { copyObj(options, marker, false) } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget") + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") } + if (options.insertLeft) { marker.widgetNode.insertLeft = true } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + { throw new Error("Inserting collapsed marker partially overlapping an existing one") } + seeCollapsedSpans() + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) } + + var curLine = from.line, cm = doc.cm, updateMaxLine + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)) + ++curLine + }) + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) } + }) } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) } + + if (marker.readOnly) { + seeReadOnlySpans() + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory() } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId + marker.atomic = true + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1) } + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } } + if (marker.atomic) { reCheckSelection(cm.doc) } + signalLater(cm, "markerAdded", cm, marker) + } + return marker +} + +// SHARED TEXTMARKERS + +// A shared marker spans multiple linked documents. It is +// implemented as a meta-marker-object controlling multiple normal +// markers. +var SharedTextMarker = function(markers, primary) { + var this$1 = this; + + this.markers = markers + this.primary = primary + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this$1 } +}; + +SharedTextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true + for (var i = 0; i < this.markers.length; ++i) + { this$1.markers[i].clear() } + signalLater(this, "clear") +}; + +SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj) +}; +eventMixin(SharedTextMarker) + +function markTextShared(doc, from, to, options, type) { + options = copyObj(options) + options.shared = false + var markers = [markText(doc, from, to, options, type)], primary = markers[0] + var widget = options.widgetNode + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true) } + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)) + for (var i = 0; i < doc.linked.length; ++i) + { if (doc.linked[i].isParent) { return } } + primary = lst(markers) + }) + return new SharedTextMarker(markers, primary) +} + +function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) +} + +function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find() + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) + marker.markers.push(subMark) + subMark.parent = marker + } + } +} + +function detachSharedMarkers(markers) { + var loop = function ( i ) { + var marker = markers[i], linked = [marker.primary.doc] + linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }) + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j] + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null + marker.markers.splice(j--, 1) + } + } + }; + + for (var i = 0; i < markers.length; i++) loop( i ); +} + +var nextDocId = 0 +var Doc = function(text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } + if (firstLine == null) { firstLine = 0 } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]) + this.first = firstLine + this.scrollTop = this.scrollLeft = 0 + this.cantEdit = false + this.cleanGeneration = 1 + this.frontier = firstLine + var start = Pos(firstLine, 0) + this.sel = simpleSelection(start) + this.history = new History(null) + this.id = ++nextDocId + this.modeOption = mode + this.lineSep = lineSep + this.direction = (direction == "rtl") ? "rtl" : "ltr" + this.extend = false + + if (typeof text == "string") { text = this.splitLines(text) } + updateDoc(this, {from: start, to: start, text: text}) + setSelection(this, simpleSelection(start), sel_dontScroll) +} + +Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op) } + else { this.iterN(this.first, this.first + this.size, from) } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0 + for (var i = 0; i < lines.length; ++i) { height += lines[i].height } + this.insertInner(at - this.first, lines, height) + }, + remove: function(at, n) { this.removeInner(at - this.first, n) }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1 + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true) + if (this.cm) { this.cm.scrollTo(0, 0) } + setSelection(this, simpleSelection(top), sel_dontScroll) + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from) + to = to ? clipPos(this, to) : from + replaceRange(this, code, from, to, origin) + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line) } + return visualLine(line) + }, + + lineCount: function() {return this.size}, + firstLine: function() {return this.first}, + lastLine: function() {return this.first + this.size - 1}, + + clipPos: function(pos) {return clipPos(this, pos)}, + + getCursor: function(start) { + var range = this.sel.primary(), pos + if (start == null || start == "head") { pos = range.head } + else if (start == "anchor") { pos = range.anchor } + else if (start == "end" || start == "to" || start === false) { pos = range.to() } + else { pos = range.from() } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options) + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options) + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options) + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options) + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f) + extendSelections(this, clipPosArray(this, heads), options) + }), + setSelections: docMethodOp(function(ranges, primary, options) { + var this$1 = this; + + if (!ranges.length) { return } + var out = [] + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this$1, ranges[i].anchor), + clipPos(this$1, ranges[i].head)) } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) } + setSelection(this, normalizeSelection(out, primary), options) + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0) + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))) + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options) + }), + + getSelection: function(lineSep) { + var this$1 = this; + + var ranges = this.sel.ranges, lines + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + lines = lines ? lines.concat(sel) : sel + } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var this$1 = this; + + var parts = [], ranges = this.sel.ranges + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) } + parts[i] = sel + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = [] + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code } + this.replaceSelections(dup, collapse, origin || "+input") + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var this$1 = this; + + var changes = [], sel = this.sel + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin} + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse) + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this$1, changes[i$1]) } + if (newSel) { setSelectionReplaceHistory(this, newSel) } + else if (this.cm) { ensureCursorVisible(this.cm) } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}), + + setExtending: function(val) {this.extend = val}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0 + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } } + return {undo: done, redo: undone} + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration)}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true) + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null } + return this.history.generation + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration) + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)} + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration) + hist.done = copyHistoryArray(histData.done.slice(0), null, true) + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true) + }, + + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}) + markers[gutterID] = value + if (!value && isEmpty(markers)) { line.gutterMarkers = null } + return true + }) + }), + + clearGutter: docMethodOp(function(gutterID) { + var this$1 = this; + + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null } + return true + }) + } + }) + }), + + lineInfo: function(line) { + var n + if (typeof line == "number") { + if (!isLine(this, line)) { return null } + n = line + line = getLine(this, line) + if (!line) { return null } + } else { + n = lineNo(line) + if (n == null) { return null } + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + if (!line[prop]) { line[prop] = cls } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + var cur = line[prop] + if (!cur) { return false } + else if (cls == null) { line[prop] = null } + else { + var found = cur.match(classTest(cls)) + if (!found) { return false } + var end = found.index + found[0].length + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null + } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options) + }), + removeLineWidget: function(widget) { widget.clear() }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents} + pos = clipPos(this, pos) + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos) + var markers = [], spans = getLine(this, pos.line).markedSpans + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + { markers.push(span.marker.parent || span.marker) } + } } + return markers + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to) + var found = [], lineNo = from.line + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans + if (spans) { for (var i = 0; i < spans.length; i++) { + var span = spans[i] + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker) } + } } + ++lineNo + }) + return found + }, + getAllMarks: function() { + var markers = [] + this.iter(function (line) { + var sps = line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker) } } } + }) + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length + this.iter(function (line) { + var sz = line.text.length + sepSize + if (sz > off) { ch = off; return true } + off -= sz + ++lineNo + }) + return clipPos(this, Pos(lineNo, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords) + var index = coords.ch + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize + }) + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep, this.direction) + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft + doc.sel = this.sel + doc.extend = false + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth + doc.setHistory(this.getHistory()) + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {} } + var from = this.first, to = this.first + this.size + if (options.from != null && options.from > from) { from = options.from } + if (options.to != null && options.to < to) { to = options.to } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction) + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}) + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}] + copySharedMarkers(copy, findSharedMarkers(this)) + return copy + }, + unlinkDoc: function(other) { + var this$1 = this; + + if (other instanceof CodeMirror) { other = other.doc } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this$1.linked[i] + if (link.doc != other) { continue } + this$1.linked.splice(i, 1) + other.unlinkDoc(this$1) + detachSharedMarkers(findSharedMarkers(this$1)) + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id] + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true) + other.history = new History(null) + other.history.done = copyHistoryArray(this.history.done, splitIds) + other.history.undone = copyHistoryArray(this.history.undone, splitIds) + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f)}, + + getMode: function() {return this.mode}, + getEditor: function() {return this.cm}, + + splitLines: function(str) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" }, + + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { dir = "ltr" } + if (dir == this.direction) { return } + this.direction = dir + this.iter(function (line) { return line.order = null; }) + if (this.cm) { directionChanged(this.cm) } + }) +}) + +// Public alias. +Doc.prototype.eachLine = Doc.prototype.iter + +// Kludge to work around strange IE behavior where it'll sometimes +// re-fire a series of drag-related events right after the drop (#1551) +var lastDrop = 0 + +function onDrop(e) { + var cm = this + clearDragCursor(cm) + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e) + if (ie) { lastDrop = +new Date } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0 + var loadFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + { return } + + var reader = new FileReader + reader.onload = operation(cm, function () { + var content = reader.result + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" } + text[i] = content + if (++read == n) { + pos = clipPos(cm.doc, pos) + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"} + makeChange(cm.doc, change) + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))) + } + }) + reader.readAsText(file) + } + for (var i = 0; i < n; ++i) { loadFile(files[i], i) } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e) + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20) + return + } + try { + var text$1 = e.dataTransfer.getData("Text") + if (text$1) { + var selected + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections() } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)) + if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) + { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } } + cm.replaceSelection(text$1, "around", "paste") + cm.display.input.focus() + } + } + catch(e){} + } +} + +function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()) + e.dataTransfer.effectAllowed = "copyMove" + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;") + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + if (presto) { + img.width = img.height = 1 + cm.display.wrapper.appendChild(img) + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop + } + e.dataTransfer.setDragImage(img, 0, 0) + if (presto) { img.parentNode.removeChild(img) } + } +} + +function onDragOver(cm, e) { + var pos = posFromMouse(cm, e) + if (!pos) { return } + var frag = document.createDocumentFragment() + drawSelectionCursor(cm, pos, frag) + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors") + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv) + } + removeChildrenAndAdd(cm.display.dragCursor, frag) +} + +function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor) + cm.display.dragCursor = null + } +} + +// These must be handled carefully, because naively registering a +// handler for each editor will cause the editors to never be +// garbage collected. + +function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) { return } + var byClass = document.body.getElementsByClassName("CodeMirror") + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror + if (cm) { f(cm) } + } +} + +var globalsRegistered = false +function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers() + globalsRegistered = true +} +function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null + forEachCodeMirror(onResize) + }, 100) } + }) + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }) +} +// Called when the window resizes +function onResize(cm) { + var d = cm.display + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + { return } + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + d.scrollbarsClipped = false + cm.setSize() +} + +var keyNames = { + 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" +} + +// Number keys +for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) } +// Alphabetic keys +for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) } +// Function keys +for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 } + +var keyMap = {} + +keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" +} +// Note that the save and find-related commands aren't defined by +// default. User code or addons can define them. Unknown commands +// are simply ignored. +keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" +} +// Very basic readline/emacs-style bindings, which are standard on Mac. +keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" +} +keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] +} +keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault + +// KEYMAP DISPATCH + +function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/) + name = parts[parts.length - 1] + var alt, ctrl, shift, cmd + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i] + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true } + else if (/^a(lt)?$/i.test(mod)) { alt = true } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true } + else if (/^s(hift)?$/i.test(mod)) { shift = true } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name } + if (ctrl) { name = "Ctrl-" + name } + if (cmd) { name = "Cmd-" + name } + if (shift) { name = "Shift-" + name } + return name +} + +// This is a kludge to keep keymaps mostly working as raw objects +// (backwards compatibility) while at the same time support features +// like normalization and multi-stroke key bindings. It compiles a +// new normalized keymap, and then updates the old object to reflect +// this. +function normalizeKeyMap(keymap) { + var copy = {} + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname] + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName) + for (var i = 0; i < keys.length; i++) { + var val = (void 0), name = (void 0) + if (i == keys.length - 1) { + name = keys.join(" ") + val = value + } else { + name = keys.slice(0, i + 1).join(" ") + val = "..." + } + var prev = copy[name] + if (!prev) { copy[name] = val } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname] + } } + for (var prop in copy) { keymap[prop] = copy[prop] } + return keymap +} + +function lookupKey(key, map, handle, context) { + map = getKeyMap(map) + var found = map.call ? map.call(key, context) : map[key] + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + { return lookupKey(key, map.fallthrough, handle, context) } + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context) + if (result) { return result } + } + } +} + +// Modifier key presses don't count as 'real' key presses for the +// purpose of keymap fallthrough. +function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode] + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" +} + +// Look up the name of a key as indicated by an event object. +function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var base = keyNames[event.keyCode], name = base + if (name == null || event.altGraphKey) { return false } + if (event.altKey && base != "Alt") { name = "Alt-" + name } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name } + return name +} + +function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val +} + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]) + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop() + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from + break + } + } + kill.push(toKill) + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") } + ensureCursorVisible(cm) + }) +} + +// Commands are parameter-less actions that can be performed on an +// editor, mostly used for keybindings. +var commands = { + selectAll: selectAll, + singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, + killLine: function (cm) { return deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } + } else { + return {from: range.from(), to: range.to()} + } + }); }, + deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + }); }); }, + delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), to: range.from() + }); }); }, + delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var leftPos = cm.coordsChar({left: 0, top: top}, "div") + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + return {from: range.from(), to: rightPos } + }); }, + undo: function (cm) { return cm.undo(); }, + redo: function (cm) { return cm.redo(); }, + undoSelection: function (cm) { return cm.undoSelection(); }, + redoSelection: function (cm) { return cm.redoSelection(); }, + goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, + goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, + goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1} + ); }, + goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, + {origin: "+move", bias: 1} + ); }, + goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var pos = cm.coordsChar({left: 0, top: top}, "div") + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, sel_move); }, + goLineUp: function (cm) { return cm.moveV(-1, "line"); }, + goLineDown: function (cm) { return cm.moveV(1, "line"); }, + goPageUp: function (cm) { return cm.moveV(-1, "page"); }, + goPageDown: function (cm) { return cm.moveV(1, "page"); }, + goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, + goCharRight: function (cm) { return cm.moveH(1, "char"); }, + goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, + goColumnRight: function (cm) { return cm.moveH(1, "column"); }, + goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, + goGroupRight: function (cm) { return cm.moveH(1, "group"); }, + goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, + goWordRight: function (cm) { return cm.moveH(1, "word"); }, + delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, + delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, + delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, + delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, + delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, + delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, + indentAuto: function (cm) { return cm.indentSelection("smart"); }, + indentMore: function (cm) { return cm.indentSelection("add"); }, + indentLess: function (cm) { return cm.indentSelection("subtract"); }, + insertTab: function (cm) { return cm.replaceSelection("\t"); }, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from() + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) + spaces.push(spaceStr(tabSize - col % tabSize)) + } + cm.replaceSelections(spaces) + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add") } + else { cm.execCommand("insertTab") } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = [] + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1) + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose") + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text + if (prev) { + cur = new Pos(cur.line, 1) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose") + } + } + } + newSel.push(new Range(cur, cur)) + } + cm.setSelections(newSel) + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections() + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") } + sels = cm.listSelections() + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true) } + ensureCursorVisible(cm) + }); }, + openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, + toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } +} + + +function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN) + var visual = visualLine(line) + if (visual != line) { lineN = lineNo(visual) } + return endOfLine(true, cm, visual, lineN, 1) +} +function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN) + var visual = visualLineEnd(line) + if (visual != line) { lineN = lineNo(visual) } + return endOfLine(true, cm, line, lineN, -1) +} +function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line) + var line = getLine(cm.doc, start.line) + var order = getOrder(line, cm.doc.direction) + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)) + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) + } + return start +} + +// Run a handler that was bound to a key. +function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound] + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled() + var prevShift = cm.display.shift, done = false + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true } + if (dropShift) { cm.display.shift = false } + done = bound(cm) != Pass + } finally { + cm.display.shift = prevShift + cm.state.suppressEdits = false + } + return done +} + +function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm) + if (result) { return result } + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm) +} + +var stopSeq = new Delayed +function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq + if (seq) { + if (isModifierKey(name)) { return "handled" } + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null + cm.display.input.reset() + } + }) + name = seq + " " + name + } + var result = lookupKeyForEditor(cm, name, handle) + + if (result == "multi") + { cm.state.keySeq = name } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e) } + + if (result == "handled" || result == "multi") { + e_preventDefault(e) + restartBlink(cm) + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e) + return true + } + return !!result +} + +// Handle a key from the keydown event. +function handleKeyBinding(cm, e) { + var name = keyName(e, true) + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } +} + +// Handle a key from the keypress event +function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) +} + +var lastStoppedKey = null +function onKeyDown(e) { + var cm = this + cm.curOp.focus = activeElt() + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false } + var code = e.keyCode + cm.display.shift = code == 16 || e.shiftKey + var handled = handleKeyBinding(cm, e) + if (presto) { + lastStoppedKey = handled ? code : null + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut") } + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm) } +} + +function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv + addClass(lineDiv, "CodeMirror-crosshair") + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair") + off(document, "keyup", up) + off(document, "mouseover", up) + } + } + on(document, "keyup", up) + on(document, "mouseover", up) +} + +function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false } + signalDOMEvent(this, e) +} + +function onKeyPress(e) { + var cm = this + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode) + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e) +} + +// A mouse down can be a single click, double click, triple click, +// start of selection drag, start of text drag, new cursor +// (ctrl-click), rectangle drag (alt-drag), or xwin +// middle-click-paste. Or it might be a click on something we should +// not interfere with, such as a scrollbar or widget. +function onMouseDown(e) { + var cm = this, display = cm.display + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.input.ensurePolled() + display.shift = e.shiftKey + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false + setTimeout(function () { return display.scroller.draggable = true; }, 100) + } + return + } + if (clickInGutter(cm, e)) { return } + var start = posFromMouse(cm, e) + window.focus() + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + { cm.state.selectingText(e) } + else if (start) + { leftButtonDown(cm, e, start) } + else if (e_target(e) == display.scroller) + { e_preventDefault(e) } + break + case 2: + if (webkit) { cm.state.lastMiddleDown = +new Date } + if (start) { extendSelection(cm.doc, start) } + setTimeout(function () { return display.input.focus(); }, 20) + e_preventDefault(e) + break + case 3: + if (captureRightClick) { onContextMenu(cm, e) } + else { delayBlurEvent(cm) } + break + } +} + +var lastClick; +var lastDoubleClick; +function leftButtonDown(cm, e, start) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0) } + else { cm.curOp.focus = activeElt() } + + var now = +new Date, type + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple" + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double" + lastDoubleClick = {time: now, pos: start} + } else { + type = "single" + lastClick = {time: now, pos: start} + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + { leftButtonStartDrag(cm, e, start, modifier) } + else + { leftButtonSelect(cm, e, start, type, modifier) } +} + +// Start a text drag. When it ends, see if any dragging actually +// happen, and treat as a click if it didn't. +function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, moved = false + var dragEnd = operation(cm, function (e) { + if (webkit) { display.scroller.draggable = false } + cm.state.draggingText = false + off(document, "mouseup", dragEnd) + off(document, "mousemove", mouseMove) + off(display.scroller, "dragstart", dragStart) + off(display.scroller, "drop", dragEnd) + if (!moved) { + e_preventDefault(e) + if (!modifier) + { extendSelection(cm.doc, start) } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) } + else + { display.input.focus() } + } + }) + var mouseMove = function(e2) { + moved = moved || Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) >= 10 + } + var dragStart = function () { return moved = true; } + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true } + cm.state.draggingText = dragEnd + dragEnd.copy = mac ? e.altKey : e.ctrlKey + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop() } + on(document, "mouseup", dragEnd) + on(document, "mousemove", mouseMove) + on(display.scroller, "dragstart", dragStart) + on(display.scroller, "drop", dragEnd) + + delayBlurEvent(cm) + setTimeout(function () { return display.input.focus(); }, 20) +} + +// Normal selection, as opposed to text dragging. +function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc + e_preventDefault(e) + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start) + if (ourIndex > -1) + { ourRange = ranges[ourIndex] } + else + { ourRange = new Range(start, start) } + } else { + ourRange = doc.sel.primary() + ourIndex = doc.sel.primIndex + } + + if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { + type = "rect" + if (!addNew) { ourRange = new Range(start, start) } + start = posFromMouse(cm, e, true, true) + ourIndex = -1 + } else if (type == "double") { + var word = cm.findWordAt(start) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, word.anchor, word.head) } + else + { ourRange = word } + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, line.anchor, line.head) } + else + { ourRange = line } + } else { + ourRange = extendRange(doc, ourRange, start) + } + + if (!addNew) { + ourIndex = 0 + setSelection(doc, new Selection([ourRange], 0), sel_mouse) + startSel = doc.sel + } else if (ourIndex == -1) { + ourIndex = ranges.length + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}) + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}) + startSel = doc.sel + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse) + } + + var lastPos = start + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize) + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize) + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol) + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize) + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) } + } + if (!ranges.length) { ranges.push(new Range(start, start)) } + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}) + cm.scrollIntoView(pos) + } else { + var oldRange = ourRange + var anchor = oldRange.anchor, head = pos + if (type != "single") { + var range + if (type == "double") + { range = cm.findWordAt(pos) } + else + { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) } + if (cmp(range.anchor, anchor) > 0) { + head = range.head + anchor = minPos(oldRange.from(), range.anchor) + } else { + head = range.anchor + anchor = maxPos(oldRange.to(), range.head) + } + } + var ranges$1 = startSel.ranges.slice(0) + ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head) + setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse) + } + } + + var editorSize = display.wrapper.getBoundingClientRect() + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0 + + function extend(e) { + var curCount = ++counter + var cur = posFromMouse(cm, e, true, type == "rect") + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt() + extendTo(cur) + var visible = visibleLines(display, doc) + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0 + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside + extend(e) + }), 50) } + } + } + + function done(e) { + cm.state.selectingText = false + counter = Infinity + e_preventDefault(e) + display.input.focus() + off(document, "mousemove", move) + off(document, "mouseup", up) + doc.history.lastSelOrigin = null + } + + var move = operation(cm, function (e) { + if (!e_button(e)) { done(e) } + else { extend(e) } + }) + var up = operation(cm, done) + cm.state.selectingText = up + on(document, "mousemove", move) + on(document, "mouseup", up) +} + + +// Determines whether an event happened in the gutter, and fires the +// handlers for the corresponding event. +function gutterEvent(cm, e, type, prevent) { + var mX, mY + try { mX = e.clientX; mY = e.clientY } + catch(e) { return false } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e) } + + var display = cm.display + var lineBox = display.lineDiv.getBoundingClientRect() + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i] + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY) + var gutter = cm.options.gutters[i] + signal(cm, type, cm, line, gutter, e) + return e_defaultPrevented(e) + } + } +} + +function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) +} + +// CONTEXT MENU HANDLING + +// To make the context menu work, we need to briefly unhide the +// textarea (making it as unobtrusive as possible) to let the +// right-click take effect on it. +function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + cm.display.input.onContextMenu(e) +} + +function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) +} + +function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-") + clearCaches(cm) +} + +var Init = {toString: function(){return "CodeMirror.Init"}} + +var defaults = {} +var optionHandlers = {} + +function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle } + } + + CodeMirror.defineOption = option + + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true) + option("mode", null, function (cm, val) { + cm.doc.modeOption = val + loadMode(cm) + }, true) + + option("indentUnit", 2, loadMode, true) + option("indentWithTabs", false) + option("smartIndent", true) + option("tabSize", 4, function (cm) { + resetModeState(cm) + clearCaches(cm) + regChange(cm) + }, true) + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos) + if (found == -1) { break } + pos = found + val.length + newBreaks.push(Pos(lineNo, found)) + } + lineNo++ + }) + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) } + }) + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") + if (old != Init) { cm.refresh() } + }) + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true) + option("electricChars", true) + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true) + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true) + option("rtlMoveVisually", !windows) + option("wholeLineUpdateBefore", true) + + option("theme", "default", function (cm) { + themeChanged(cm) + guttersChanged(cm) + }, true) + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val) + var prev = old != Init && getKeyMap(old) + if (prev && prev.detach) { prev.detach(cm, next) } + if (next.attach) { next.attach(cm, prev || null) } + }) + option("extraKeys", null) + + option("lineWrapping", false, wrappingChanged, true) + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" + cm.refresh() + }, true) + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true) + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm) + updateScrollbars(cm) + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) + }, true) + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("firstLineNumber", 1, guttersChanged, true) + option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true) + option("showCursorWhenSelecting", false, updateSelection, true) + + option("resetSelectionOnContextMenu", true) + option("lineWiseCopyCut", true) + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm) + cm.display.input.blur() + cm.display.disabled = true + } else { + cm.display.disabled = false + } + cm.display.input.readOnlyChanged(val) + }) + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true) + option("dragDrop", true, dragDropChanged) + option("allowDropFileTypes", null) + + option("cursorBlinkRate", 530) + option("cursorScrollMargin", 0) + option("cursorHeight", 1, updateSelection, true) + option("singleCursorHeightPerLine", true, updateSelection, true) + option("workTime", 100) + option("workDelay", 100) + option("flattenSpans", true, resetModeState, true) + option("addModeClass", false, resetModeState, true) + option("pollInterval", 100) + option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }) + option("historyEventDelay", 1250) + option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true) + option("maxHighlightLength", 10000, resetModeState, true) + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition() } + }) + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }) + option("autofocus", null) + option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true) +} + +function guttersChanged(cm) { + updateGutters(cm) + regChange(cm) + alignHorizontally(cm) +} + +function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions + var toggle = value ? on : off + toggle(cm.display.scroller, "dragstart", funcs.start) + toggle(cm.display.scroller, "dragenter", funcs.enter) + toggle(cm.display.scroller, "dragover", funcs.over) + toggle(cm.display.scroller, "dragleave", funcs.leave) + toggle(cm.display.scroller, "drop", funcs.drop) + } +} + +function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap") + cm.display.sizer.style.minWidth = "" + cm.display.sizerWidth = null + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap") + findMaxLine(cm) + } + estimateLineHeights(cm) + regChange(cm) + clearCaches(cm) + setTimeout(function () { return updateScrollbars(cm); }, 100) +} + +// A CodeMirror instance represents an editor. This is the object +// that user code is usually dealing with. + +function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {} + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false) + setGuttersForLineNumbers(options) + + var doc = options.value + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) } + this.doc = doc + + var input = new CodeMirror.inputStyles[options.inputStyle](this) + var display = this.display = new Display(place, doc, input) + display.wrapper.CodeMirror = this + updateGutters(this) + themeChanged(this) + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap" } + initScrollbars(this) + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + } + + if (options.autofocus && !mobile) { display.input.focus() } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) } + + registerEventHandlers(this) + ensureGlobalHandlers() + + startOperation(this) + this.curOp.forceUpdate = true + attachDoc(this, doc) + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(bind(onFocus, this), 20) } + else + { onBlur(this) } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this$1, options[opt], Init) } } + maybeUpdateLineNumberWidth(this) + if (options.finishInit) { options.finishInit(this) } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) } + endOperation(this) + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto" } +} + +// The default configuration options. +CodeMirror.defaults = defaults +// Functions to run when options are changed. +CodeMirror.optionHandlers = optionHandlers + +// Attach the necessary event handlers when initializing the editor +function registerEventHandlers(cm) { + var d = cm.display + on(d.scroller, "mousedown", operation(cm, onMouseDown)) + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e) + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e) + var word = cm.findWordAt(pos) + extendSelection(cm.doc, word.anchor, word.head) + })) } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) } + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0} + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000) + prevTouch = d.activeTouch + prevTouch.end = +new Date + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0] + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { + d.input.ensurePolled() + clearTimeout(touchFinished) + var now = +new Date + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null} + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX + d.activeTouch.top = e.touches[0].pageY + } + } + }) + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true } + }) + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos) } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos) } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + cm.setSelection(range.anchor, range.head) + cm.focus() + e_preventDefault(e) + } + finishTouch() + }) + on(d.scroller, "touchcancel", finishTouch) + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop) + setScrollLeft(cm, d.scroller.scrollLeft, true) + signal(cm, "scroll", cm) + } + }) + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }) + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }) + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }) + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }} + } + + var inp = d.input.getField() + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }) + on(inp, "keydown", operation(cm, onKeyDown)) + on(inp, "keypress", operation(cm, onKeyPress)) + on(inp, "focus", function (e) { return onFocus(cm, e); }) + on(inp, "blur", function (e) { return onBlur(cm, e); }) +} + +var initHooks = [] +CodeMirror.defineInitHook = function (f) { return initHooks.push(f); } + +// Indent the given line. The how parameter can be "smart", +// "add"/null, "subtract", or "prev". When aggressive is false +// (typically set to true for forced single-line indents), empty +// lines are not indented, and places where the mode returns Pass +// are left alone. +function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state + if (how == null) { how = "add" } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev" } + else { state = getStateBefore(cm, n) } + } + + var tabSize = cm.options.tabSize + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) + if (line.stateAfter) { line.stateAfter = null } + var curSpaceString = line.text.match(/^\s*/)[0], indentation + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0 + how = "not" + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev" + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) } + else { indentation = 0 } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit + } else if (typeof how == "number") { + indentation = curSpace + how + } + indentation = Math.max(0, indentation) + + var indentString = "", pos = 0 + if (cm.options.indentWithTabs) + { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} } + if (pos < indentation) { indentString += spaceStr(indentation - pos) } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") + line.stateAfter = null + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { + var range = doc.sel.ranges[i$1] + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length) + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)) + break + } + } + } +} + +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +var lastCopied = null + +function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} + +function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc + cm.display.shift = false + if (!sel) { sel = doc.sel } + + var paste = cm.state.pasteIncoming || origin == "paste" + var textLines = splitLinesAuto(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])) } + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function (l) { return [l]; }) + } + } + + var updateInput + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range = sel.ranges[i$1] + var from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted) } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) } + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0) } + } + updateInput = cm.curOp.updateInput + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + { triggerElectric(cm, inserted) } + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) } + return true + } +} + +function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.head) + var indented = false + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + { indented = indentLine(cm, range.head.line, "smart") } + } + if (indented) { signalLater(cm, "electricInput", cm, range.head.line) } + } +} + +function copyableRanges(cm) { + var text = [], ranges = [] + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} + ranges.push(lineRange) + text.push(cm.getRange(lineRange.anchor, lineRange.head)) + } + return {text: text, ranges: ranges} +} + +function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + field.setAttribute("spellcheck", !!spellcheck) +} + +function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px" } + else { te.setAttribute("wrap", "off") } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black" } + disableBrowserMagic(te) + return div +} + +// The publicly visible API. Note that methodOp(f) means +// 'wrap f in an operation, performed on its `this` parameter'. + +// This is not the complete set of editor methods. Most of the +// methods defined on the Doc type are also injected into +// CodeMirror.prototype, for backwards compatibility and +// convenience. + +function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + var helpers = CodeMirror.helpers = {} + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus()}, + + setOption: function(option, value) { + var options = this.options, old = options[option] + if (options[option] == value && option != "mode") { return } + options[option] = value + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old) } + signal(this, "optionChange", this, option) + }, + + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1) + return true + } } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec) + if (mode.startState) { throw new Error("Overlays may not be stateful.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }) + this.state.modeGen++ + regChange(this) + }), + removeOverlay: methodOp(function(spec) { + var this$1 = this; + + var overlays = this.state.overlays + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1) + this$1.state.modeGen++ + regChange(this$1) + return + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" } + else { dir = dir ? "add" : "subtract" } + } + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) } + }), + indentSelection: methodOp(function(how) { + var this$1 = this; + + var ranges = this.doc.sel.ranges, end = -1 + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (!range.empty()) { + var from = range.from(), to = range.to() + var start = Math.max(end, from.line) + end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1 + for (var j = start; j < end; ++j) + { indentLine(this$1, j, how) } + var newRanges = this$1.doc.sel.ranges + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) } + } else if (range.head.line > end) { + indentLine(this$1, range.head.line, how, true) + end = range.head.line + if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) } + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos) + var styles = getLineStyles(this, getLine(this.doc, pos.line)) + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch + var type + if (ch == 0) { type = styles[2] } + else { for (;;) { + var mid = (before + after) >> 1 + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1 } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1 + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) + }, + + getModeAt: function(pos) { + var mode = this.doc.mode + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] + }, + + getHelpers: function(pos, type) { + var this$1 = this; + + var found = [] + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos) + if (typeof mode[type] == "string") { + if (help[mode[type]]) { found.push(help[mode[type]]) } + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]] + if (val) { found.push(val) } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]) + } else if (help[mode.name]) { + found.push(help[mode.name]) + } + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1] + if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) + { found.push(cur.val) } + } + return found + }, + + getStateAfter: function(line, precise) { + var doc = this.doc + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line) + return getStateBefore(this, line + 1, precise) + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary() + if (start == null) { pos = range.head } + else if (typeof start == "object") { pos = clipPos(this.doc, start) } + else { pos = start ? range.from() : range.to() } + return cursorCoords(this, pos, mode || "page") + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page") + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page") + return coordsChar(this, coords.left, coords.top) + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top + return lineAtHeight(this.doc, height + this.display.viewOffset) + }, + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1 + if (line < this.doc.first) { line = this.doc.first } + else if (line > last) { line = last; end = true } + lineObj = getLine(this.doc, line) + } else { + lineObj = line + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) + }, + + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display + pos = cursorCoords(this, clipPos(this.doc, pos)) + var top = pos.bottom, left = pos.left + node.style.position = "absolute" + node.setAttribute("cm-ignore-events", "true") + this.display.input.setUneditable(node) + display.sizer.appendChild(node) + if (vert == "over") { + top = pos.top + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth) + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + { top = pos.top - node.offsetHeight } + else if (pos.bottom + node.offsetHeight <= vspace) + { top = pos.bottom } + if (left + node.offsetWidth > hspace) + { left = hspace - node.offsetWidth } + } + node.style.top = top + "px" + node.style.left = node.style.right = "" + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth + node.style.right = "0px" + } else { + if (horiz == "left") { left = 0 } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 } + node.style.left = left + "px" + } + if (scroll) + { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) } + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text) }), + + findPosH: function(from, amount, unit, visually) { + var this$1 = this; + + var dir = 1 + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + cur = findPosH(this$1.doc, cur, dir, unit, visually) + if (cur.hitSide) { break } + } + return cur + }, + + moveH: methodOp(function(dir, unit) { + var this$1 = this; + + this.extendSelectionsBy(function (range) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.to() } + }, sel_move) + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete") } + else + { deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false) + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} + }) } + }), + + findPosV: function(from, amount, unit, goalColumn) { + var this$1 = this; + + var dir = 1, x = goalColumn + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this$1, cur, "div") + if (x == null) { x = coords.left } + else { coords.left = x } + cur = findPosV(this$1, coords, dir, unit) + if (cur.hitSide) { break } + } + return cur + }, + + moveV: methodOp(function(dir, unit) { + var this$1 = this; + + var doc = this.doc, goals = [] + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected() + doc.extendSelectionsBy(function (range) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div") + if (range.goalColumn != null) { headPos.left = range.goalColumn } + goals.push(headPos.left) + var pos = findPosV(this$1, headPos, dir, unit) + if (unit == "page" && range == doc.sel.primary()) + { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) } + return pos + }, sel_move) + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i] } } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text + var start = pos.ch, end = pos.ch + if (line) { + var helper = this.getHelper(pos, "wordChars") + if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end } + var startChar = line.charAt(start) + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } + : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); } + while (start > 0 && check(line.charAt(start - 1))) { --start } + while (end < line.length && check(line.charAt(end))) { ++end } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { return } + if (this.state.overwrite = !this.state.overwrite) + { addClass(this.display.cursorDiv, "CodeMirror-overwrite") } + else + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") } + + signal(this, "overwriteToggle", this, this.state.overwrite) + }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, + + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) { resolveScrollToPos(this) } + if (x != null) { this.curOp.scrollLeft = x } + if (y != null) { this.curOp.scrollTop = y } + }), + getScrollInfo: function() { + var scroller = this.display.scroller + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)} + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null} + if (margin == null) { margin = this.options.cursorScrollMargin } + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null} + } else if (range.from == null) { + range = {from: range, to: null} + } + if (!range.to) { range.to = range.from } + range.margin = margin || 0 + + if (range.from.line != null) { + resolveScrollToPos(this) + this.curOp.scrollToPos = range + } else { + var sPos = calculateScrollPos(this, { + left: Math.min(range.from.left, range.to.left), + top: Math.min(range.from.top, range.to.top) - range.margin, + right: Math.max(range.from.right, range.to.right), + bottom: Math.max(range.from.bottom, range.to.bottom) + range.margin + }) + this.scrollTo(sPos.scrollLeft, sPos.scrollTop) + } + }), + + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } + if (width != null) { this.display.wrapper.style.width = interpret(width) } + if (height != null) { this.display.wrapper.style.height = interpret(height) } + if (this.options.lineWrapping) { clearLineMeasurementCache(this) } + var lineNo = this.display.viewFrom + this.doc.iter(lineNo, this.display.viewTo, function (line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) + { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } + ++lineNo + }) + this.curOp.forceUpdate = true + signal(this, "refresh", this) + }), + + operation: function(f){return runInOp(this, f)}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight + regChange(this) + this.curOp.forceUpdate = true + clearCaches(this) + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop) + updateGutterSpace(this) + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + { estimateLineHeights(this) } + signal(this, "refresh", this) + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc + old.cm = null + attachDoc(this, doc) + clearCaches(this) + this.display.input.reset() + this.scrollTo(doc.scrollLeft, doc.scrollTop) + this.curOp.forceScroll = true + signalLater(this, "swapDoc", this, old) + return old + }), + + getInputField: function(){return this.display.input.getField()}, + getWrapperElement: function(){return this.display.wrapper}, + getScrollerElement: function(){return this.display.scroller}, + getGutterElement: function(){return this.display.gutters} + } + eventMixin(CodeMirror) + + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} } + helpers[type][name] = value + } + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value) + helpers[type]._global.push({pred: predicate, val: value}) + } +} + +// Used for horizontal relative motion. Dir is -1 or 1 (left or +// right), unit can be "char", "column" (like char, but doesn't +// cross line boundaries), "word" (across next word), or "group" (to +// the start of next group of word or non-word-non-whitespace +// chars). The visually param controls whether, in right-to-left +// text, direction 1 means to move towards the next index in the +// string, or towards the character to the right of the current +// position. The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos + var origDir = dir + var lineObj = getLine(doc, pos.line) + function findNextLine() { + var l = pos.line + dir + if (l < doc.first || l >= doc.first + doc.size) { return false } + pos = new Pos(l, pos.ch, pos.sticky) + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next + if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir) + } else { + next = moveLogically(lineObj, pos, dir) + } + if (next == null) { + if (!boundToLine && findNextLine()) + { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) } + else + { return false } + } else { + pos = next + } + return true + } + + if (unit == "char") { + moveOnce() + } else if (unit == "column") { + moveOnce(true) + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group" + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars") + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(pos.ch) || "\n" + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p" + if (group && !first && !type) { type = "s" } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"} + break + } + + if (type) { sawType = type } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, pos, oldPos, origDir, true) + if (equalCursorPos(oldPos, result)) { result.hitSide = true } + return result +} + +// For relative vertical movement. Dir may be -1 or 1. Unit can be +// "page" or "line". The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight) + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3) + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3 + } + var target + for (;;) { + target = coordsChar(cm, x, y) + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5 + } + return target +} + +// CONTENTEDITABLE INPUT STYLE + +var ContentEditableInput = function(cm) { + this.cm = cm + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null + this.polling = new Delayed() + this.composing = null + this.gracePeriod = false + this.readDOMTimeout = null +}; + +ContentEditableInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = input.cm + var div = input.div = display.lineDiv + disableBrowserMagic(div, cm.options.spellcheck) + + on(div, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) } + }) + + on(div, "compositionstart", function (e) { + this$1.composing = {data: e.data, done: false} + }) + on(div, "compositionupdate", function (e) { + if (!this$1.composing) { this$1.composing = {data: e.data, done: false} } + }) + on(div, "compositionend", function (e) { + if (this$1.composing) { + if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() } + this$1.composing.done = true + } + }) + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }) + + on(div, "input", function () { + if (!this$1.composing) { this$1.readFromDOMSoon() } + }) + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (e.type == "cut") { cm.replaceSelection("", null, "cut") } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll) + cm.replaceSelection("", null, "cut") + }) + } + } + if (e.clipboardData) { + e.clipboardData.clearData() + var content = lastCopied.text.join("\n") + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content) + if (e.clipboardData.getData("Text") == content) { + e.preventDefault() + return + } + } + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) + te.value = lastCopied.text.join("\n") + var hadFocus = document.activeElement + selectInput(te) + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge) + hadFocus.focus() + if (hadFocus == div) { input.showPrimarySelection() } + }, 50) + } + on(div, "copy", onCopyCut) + on(div, "cut", onCopyCut) +}; + +ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false) + result.focus = this.cm.state.focused + return result +}; + +ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection() } + this.showMultipleSelections(info) +}; + +ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary() + var from = prim.from(), to = prim.to() + + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges() + return + } + + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset) + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0) + { return } + + var view = cm.display.view + var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || + {node: view[0].measure.map[2], offset: 0} + var end = to.line < cm.display.viewTo && posToDOM(cm, to) + if (!end) { + var measure = view[view.length - 1].measure + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]} + } + + if (!start || !end) { + sel.removeAllRanges() + return + } + + var old = sel.rangeCount && sel.getRangeAt(0), rng + try { rng = range(start.node, start.offset, end.offset, end.node) } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset) + if (!rng.collapsed) { + sel.removeAllRanges() + sel.addRange(rng) + } + } else { + sel.removeAllRanges() + sel.addRange(rng) + } + if (old && sel.anchorNode == null) { sel.addRange(old) } + else if (gecko) { this.startGracePeriod() } + } + this.rememberSelection() +}; + +ContentEditableInput.prototype.startGracePeriod = function () { + var this$1 = this; + + clearTimeout(this.gracePeriod) + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) } + }, 20) +}; + +ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) +}; + +ContentEditableInput.prototype.rememberSelection = function () { + var sel = window.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset +}; + +ContentEditableInput.prototype.selectionInEditor = function () { + var sel = window.getSelection() + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer + return contains(this.div, node) +}; + +ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor()) + { this.showSelection(this.prepareSelection(), true) } + this.div.focus() + } +}; +ContentEditableInput.prototype.blur = function () { this.div.blur() }; +ContentEditableInput.prototype.getField = function () { return this.div }; + +ContentEditableInput.prototype.supportsTouch = function () { return true }; + +ContentEditableInput.prototype.receivedFocus = function () { + var input = this + if (this.selectionInEditor()) + { this.pollSelection() } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection() + input.polling.set(input.cm.options.pollInterval, poll) + } + } + this.polling.set(this.cm.options.pollInterval, poll) +}; + +ContentEditableInput.prototype.selectionChanged = function () { + var sel = window.getSelection() + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset +}; + +ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } + var sel = window.getSelection(), cm = this.cm + // On Android Chrome (version 56, at least), backspacing into an + // uneditable block element will put the cursor in that element, + // and then, because it's not editable, hide the virtual keyboard. + // Because Android doesn't allow us to actually detect backspace + // presses in a sane way, this code checks for when that happens + // and simulates a backspace press in this case. + if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}) + this.blur() + this.focus() + return + } + if (this.composing) { return } + this.rememberSelection() + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var head = domToPos(cm, sel.focusNode, sel.focusOffset) + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true } + }) } +}; + +ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout) + this.readDOMTimeout = null + } + + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() + var from = sel.from(), to = sel.to() + if (from.ch == 0 && from.line > cm.firstLine()) + { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) + { to = Pos(to.line + 1, 0) } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line) + fromNode = display.view[0].node + } else { + fromLine = lineNo(display.view[fromIndex].line) + fromNode = display.view[fromIndex - 1].node.nextSibling + } + var toIndex = findViewIndex(cm, to.line) + var toLine, toNode + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1 + toNode = display.lineDiv.lastChild + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1 + toNode = display.view[toIndex + 1].node.previousSibling + } + + if (!fromNode) { return false } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } + else { break } + } + + var cutFront = 0, cutEnd = 0 + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront } + var newBot = lst(newText), oldBot = lst(oldText) + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)) + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd } + // Try to move start of change to start of selection if ambiguous + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront-- + cutEnd++ + } + } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "") + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "") + + var chFrom = Pos(fromLine, cutFront) + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input") + return true + } +}; + +ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { return } + clearTimeout(this.readDOMTimeout) + this.composing = null + this.updateFromDOM() + this.div.blur() + this.div.focus() +}; +ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1 = this; + + if (this.readDOMTimeout != null) { return } + this.readDOMTimeout = setTimeout(function () { + this$1.readDOMTimeout = null + if (this$1.composing) { + if (this$1.composing.done) { this$1.composing = null } + else { return } + } + this$1.updateFromDOM() + }, 80) +}; + +ContentEditableInput.prototype.updateFromDOM = function () { + var this$1 = this; + + if (this.cm.isReadOnly() || !this.pollContent()) + { runInOp(this.cm, function () { return regChange(this$1.cm); }) } +}; + +ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false" +}; + +ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0) { return } + e.preventDefault() + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) } +}; + +ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor") +}; + +ContentEditableInput.prototype.onContextMenu = function () {}; +ContentEditableInput.prototype.resetPosition = function () {}; + +ContentEditableInput.prototype.needsContentAttribute = true + +function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line) + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line) + var info = mapFromLineView(view, line, pos.line) + + var order = getOrder(line, cm.doc.direction), side = "left" + if (order) { + var partPos = getBidiPartAt(order, pos.ch) + side = partPos % 2 ? "right" : "left" + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side) + result.offset = result.collapse == "right" ? result.end : result.start + return result +} + +function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) + { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } + return false +} + +function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + +function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator() + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep + closing = false + } + } + function addText(str) { + if (str) { + close() + text += str + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text") + if (cmText != null) { + addText(cmText || node.textContent.replace(/\u200b/g, "")) + return + } + var markerID = node.getAttribute("cm-marker"), range + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) + if (found.length && (range = found[0].find())) + { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + var isBlock = /^(pre|div|p)$/i.test(node.nodeName) + if (isBlock) { close() } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]) } + if (isBlock) { closing = true } + } else if (node.nodeType == 3) { + addText(node.nodeValue) + } + } + for (;;) { + walk(from) + if (from == to) { break } + from = from.nextSibling + } + return text +} + +function domToPos(cm, node, offset) { + var lineNode + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset] + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + node = null; offset = 0 + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { return null } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i] + if (lineView.node == lineNode) + { return locateNodeInLineView(lineView, node, offset) } + } +} + +function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true + node = wrapper.childNodes[offset] + offset = 0 + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild + if (offset) { offset = textNode.nodeValue.length } + } + while (topNode.parentNode != wrapper) { topNode = topNode.parentNode } + var measure = lineView.measure, maps = measure.maps + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i] + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + var ch = map[j] + offset + if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] } + return Pos(line, ch) + } + } + } + } + var found = find(textNode, topNode, offset) + if (found) { return badPos(found, bad) } + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0) + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1) + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length } + } +} + +// TEXTAREA INPUT STYLE + +var TextareaInput = function(cm) { + this.cm = cm + // See input.poll and input.reset + this.prevInput = "" + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false + // Self-resetting timeout for the poller + this.polling = new Delayed() + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false + this.composing = null +}; + +TextareaInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = this.cm + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea() + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild + display.wrapper.insertBefore(div, display.wrapper.firstChild) + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px" } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null } + input.poll() + }) + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = true + input.fastPoll() + }) + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (input.inaccurateSelection) { + input.prevInput = "" + input.inaccurateSelection = false + te.value = lastCopied.text.join("\n") + selectInput(te) + } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll) + } else { + input.prevInput = "" + te.value = ranges.text.join("\n") + selectInput(te) + } + } + if (e.type == "cut") { cm.state.cutIncoming = true } + } + on(te, "cut", prepareCopyCut) + on(te, "copy", prepareCopyCut) + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + cm.state.pasteIncoming = true + input.focus() + }) + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e) } + }) + + on(te, "compositionstart", function () { + var start = cm.getCursor("from") + if (input.composing) { input.composing.range.clear() } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + } + }) + on(te, "compositionend", function () { + if (input.composing) { + input.poll() + input.composing.range.clear() + input.composing = null + } + }) +}; + +TextareaInput.prototype.prepareSelection = function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc + var result = prepareSelection(cm) + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div") + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect() + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)) + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)) + } + + return result +}; + +TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, display = cm.display + removeChildrenAndAdd(display.cursorDiv, drawn.cursors) + removeChildrenAndAdd(display.selectionDiv, drawn.selection) + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px" + this.wrapper.style.left = drawn.teLeft + "px" + } +}; + +// Reset the input to correspond to the selection (or to be empty, +// when not typing and nothing is selected) +TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending) { return } + var minimal, selected, cm = this.cm, doc = cm.doc + if (cm.somethingSelected()) { + this.prevInput = "" + var range = doc.sel.primary() + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000) + var content = minimal ? "-" : selected || cm.getSelection() + this.textarea.value = content + if (cm.state.focused) { selectInput(this.textarea) } + if (ie && ie_version >= 9) { this.hasSelection = content } + } else if (!typing) { + this.prevInput = this.textarea.value = "" + if (ie && ie_version >= 9) { this.hasSelection = null } + } + this.inaccurateSelection = minimal +}; + +TextareaInput.prototype.getField = function () { return this.textarea }; + +TextareaInput.prototype.supportsTouch = function () { return false }; + +TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus() } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } +}; + +TextareaInput.prototype.blur = function () { this.textarea.blur() }; + +TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0 +}; + +TextareaInput.prototype.receivedFocus = function () { this.slowPoll() }; + +// Poll for input changes, using the normal rate of polling. This +// runs as long as the editor is focused. +TextareaInput.prototype.slowPoll = function () { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll() + if (this$1.cm.state.focused) { this$1.slowPoll() } + }) +}; + +// When an event has just come in that is likely to add or change +// something in the input textarea, we poll faster, to ensure that +// the change appears on the screen quickly. +TextareaInput.prototype.fastPoll = function () { + var missed = false, input = this + input.pollingFast = true + function p() { + var changed = input.poll() + if (!changed && !missed) {missed = true; input.polling.set(60, p)} + else {input.pollingFast = false; input.slowPoll()} + } + input.polling.set(20, p) +}; + +// Read input from the textarea, and update the document to match. +// When something is selected, it is present in the textarea, and +// selected (unless it is huge, in which case a placeholder is +// used). When nothing is selected, the cursor sits after previously +// seen text (can be empty), which is stored in prevInput (we must +// not reset the textarea when typing, because that breaks IME). +TextareaInput.prototype.poll = function () { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset() + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0) + if (first == 0x200b && !prevInput) { prevInput = "\u200b" } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length) + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null) + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" } + else { this$1.prevInput = text } + + if (this$1.composing) { + this$1.composing.range.clear() + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}) + } + }) + return true +}; + +TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { this.pollingFast = false } +}; + +TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { this.hasSelection = null } + this.fastPoll() +}; + +TextareaInput.prototype.onContextMenu = function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);" + var oldScrollY + if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712) + display.input.focus() + if (webkit) { window.scrollTo(null, oldScrollY) } + display.input.reset() + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " " } + input.contextMenuPending = true + display.selForContextMenu = cm.doc.sel + clearTimeout(display.detectingSelectAll) + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected() + var extval = "\u200b" + (selected ? te.value : "") + te.value = "\u21da" // Used to catch context-menu undo + te.value = extval + input.prevInput = selected ? "" : "\u200b" + te.selectionStart = 1; te.selectionEnd = extval.length + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel + } + } + function rehide() { + input.contextMenuPending = false + input.wrapper.style.cssText = oldWrapperCSS + te.style.cssText = oldCSS + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") { + operation(cm, selectAll)(cm) + } else if (i++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500) + } else { + display.selForContextMenu = null + display.input.reset() + } + } + display.detectingSelectAll = setTimeout(poll, 200) + } + } + + if (ie && ie_version >= 9) { prepareSelectAllHack() } + if (captureRightClick) { + e_stop(e) + var mouseup = function () { + off(window, "mouseup", mouseup) + setTimeout(rehide, 20) + } + on(window, "mouseup", mouseup) + } else { + setTimeout(rehide, 50) + } +}; + +TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { this.reset() } +}; + +TextareaInput.prototype.setUneditable = function () {}; + +TextareaInput.prototype.needsContentAttribute = false + +function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {} + options.value = textarea.value + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt() + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body + } + + function save() {textarea.value = cm.getValue()} + + var realSubmit + if (textarea.form) { + on(textarea.form, "submit", save) + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form + realSubmit = form.submit + try { + var wrappedSubmit = form.submit = function () { + save() + form.submit = realSubmit + form.submit() + form.submit = wrappedSubmit + } + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save + cm.getTextArea = function () { return textarea; } + cm.toTextArea = function () { + cm.toTextArea = isNaN // Prevent this from being ran twice + save() + textarea.parentNode.removeChild(cm.getWrapperElement()) + textarea.style.display = "" + if (textarea.form) { + off(textarea.form, "submit", save) + if (typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit } + } + } + } + + textarea.style.display = "none" + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options) + return cm +} + +function addLegacyProps(CodeMirror) { + CodeMirror.off = off + CodeMirror.on = on + CodeMirror.wheelEventPixels = wheelEventPixels + CodeMirror.Doc = Doc + CodeMirror.splitLines = splitLinesAuto + CodeMirror.countColumn = countColumn + CodeMirror.findColumn = findColumn + CodeMirror.isWordChar = isWordCharBasic + CodeMirror.Pass = Pass + CodeMirror.signal = signal + CodeMirror.Line = Line + CodeMirror.changeEnd = changeEnd + CodeMirror.scrollbarModel = scrollbarModel + CodeMirror.Pos = Pos + CodeMirror.cmpPos = cmp + CodeMirror.modes = modes + CodeMirror.mimeModes = mimeModes + CodeMirror.resolveMode = resolveMode + CodeMirror.getMode = getMode + CodeMirror.modeExtensions = modeExtensions + CodeMirror.extendMode = extendMode + CodeMirror.copyState = copyState + CodeMirror.startState = startState + CodeMirror.innerMode = innerMode + CodeMirror.commands = commands + CodeMirror.keyMap = keyMap + CodeMirror.keyName = keyName + CodeMirror.isModifierKey = isModifierKey + CodeMirror.lookupKey = lookupKey + CodeMirror.normalizeKeyMap = normalizeKeyMap + CodeMirror.StringStream = StringStream + CodeMirror.SharedTextMarker = SharedTextMarker + CodeMirror.TextMarker = TextMarker + CodeMirror.LineWidget = LineWidget + CodeMirror.e_preventDefault = e_preventDefault + CodeMirror.e_stopPropagation = e_stopPropagation + CodeMirror.e_stop = e_stop + CodeMirror.addClass = addClass + CodeMirror.contains = contains + CodeMirror.rmClass = rmClass + CodeMirror.keyNames = keyNames +} + +// EDITOR CONSTRUCTOR + +defineOptions(CodeMirror) + +addEditorMethods(CodeMirror) + +// Set up methods on CodeMirror's prototype to redirect to the editor's document. +var dontDelegate = "iter insert remove copy getEditor constructor".split(" ") +for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]) } } + +eventMixin(Doc) + +// INPUT HANDLING + +CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} + +// MODE DEFINITION AND QUERYING + +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name } + defineMode.apply(this, arguments) +} + +CodeMirror.defineMIME = defineMIME + +// Minimal default mode. +CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }) +CodeMirror.defineMIME("text/plain", "null") + +// EXTENSIONS + +CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func +} +CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func +} + +CodeMirror.fromTextArea = fromTextArea + +addLegacyProps(CodeMirror) + +CodeMirror.version = "5.25.2" + +return CodeMirror; + +}))); +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var HINT_ELEMENT_CLASS = "CodeMirror-hint"; + var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + + // This is the old interface, kept around for now to stay + // backwards-compatible. + CodeMirror.showHint = function(cm, getHints, options) { + if (!getHints) return cm.showHint(options); + if (options && options.async) getHints.async = true; + var newOpts = {hint: getHints}; + if (options) for (var prop in options) newOpts[prop] = options[prop]; + return cm.showHint(newOpts); + }; + + CodeMirror.defineExtension("showHint", function(options) { + options = parseOptions(this, this.getCursor("start"), options); + var selections = this.listSelections() + if (selections.length > 1) return; + // By default, don't allow completion when something is selected. + // A hint function can have a `supportsSelection` property to + // indicate that it can handle selections. + if (this.somethingSelected()) { + if (!options.hint.supportsSelection) return; + // Don't try with cross-line selections + for (var i = 0; i < selections.length; i++) + if (selections[i].head.line != selections[i].anchor.line) return; + } + + if (this.state.completionActive) this.state.completionActive.close(); + var completion = this.state.completionActive = new Completion(this, options); + if (!completion.options.hint) return; + + CodeMirror.signal(this, "startCompletion", this); + completion.update(true); + }); + + function Completion(cm, options) { + this.cm = cm; + this.options = options; + this.widget = null; + this.debounce = 0; + this.tick = 0; + this.startPos = this.cm.getCursor("start"); + this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length; + + var self = this; + cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); }); + } + + var requestAnimationFrame = window.requestAnimationFrame || function(fn) { + return setTimeout(fn, 1000/60); + }; + var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; + + Completion.prototype = { + close: function() { + if (!this.active()) return; + this.cm.state.completionActive = null; + this.tick = null; + this.cm.off("cursorActivity", this.activityFunc); + + if (this.widget && this.data) CodeMirror.signal(this.data, "close"); + if (this.widget) this.widget.close(); + CodeMirror.signal(this.cm, "endCompletion", this.cm); + }, + + active: function() { + return this.cm.state.completionActive == this; + }, + + pick: function(data, i) { + var completion = data.list[i]; + if (completion.hint) completion.hint(this.cm, data, completion); + else this.cm.replaceRange(getText(completion), completion.from || data.from, + completion.to || data.to, "complete"); + CodeMirror.signal(data, "pick", completion); + this.close(); + }, + + cursorActivity: function() { + if (this.debounce) { + cancelAnimationFrame(this.debounce); + this.debounce = 0; + } + + var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line); + if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || + pos.ch < this.startPos.ch || this.cm.somethingSelected() || + (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) { + this.close(); + } else { + var self = this; + this.debounce = requestAnimationFrame(function() {self.update();}); + if (this.widget) this.widget.disable(); + } + }, + + update: function(first) { + if (this.tick == null) return + var self = this, myTick = ++this.tick + fetchHints(this.options.hint, this.cm, this.options, function(data) { + if (self.tick == myTick) self.finishUpdate(data, first) + }) + }, + + finishUpdate: function(data, first) { + if (this.data) CodeMirror.signal(this.data, "update"); + + var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); + if (this.widget) this.widget.close(); + + if (data && this.data && isNewCompletion(this.data, data)) return; + this.data = data; + + if (data && data.list.length) { + if (picked && data.list.length == 1) { + this.pick(data, 0); + } else { + this.widget = new Widget(this, data); + CodeMirror.signal(data, "shown"); + } + } + } + }; + + function isNewCompletion(old, nw) { + var moved = CodeMirror.cmpPos(nw.from, old.from) + return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch + } + + function parseOptions(cm, pos, options) { + var editor = cm.options.hintOptions; + var out = {}; + for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; + if (editor) for (var prop in editor) + if (editor[prop] !== undefined) out[prop] = editor[prop]; + if (options) for (var prop in options) + if (options[prop] !== undefined) out[prop] = options[prop]; + if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos) + return out; + } + + function getText(completion) { + if (typeof completion == "string") return completion; + else return completion.text; + } + + function buildKeyMap(completion, handle) { + var baseMap = { + Up: function() {handle.moveFocus(-1);}, + Down: function() {handle.moveFocus(1);}, + PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);}, + PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);}, + Home: function() {handle.setFocus(0);}, + End: function() {handle.setFocus(handle.length - 1);}, + Enter: handle.pick, + Tab: handle.pick, + Esc: handle.close + }; + var custom = completion.options.customKeys; + var ourMap = custom ? {} : baseMap; + function addBinding(key, val) { + var bound; + if (typeof val != "string") + bound = function(cm) { return val(cm, handle); }; + // This mechanism is deprecated + else if (baseMap.hasOwnProperty(val)) + bound = baseMap[val]; + else + bound = val; + ourMap[key] = bound; + } + if (custom) + for (var key in custom) if (custom.hasOwnProperty(key)) + addBinding(key, custom[key]); + var extra = completion.options.extraKeys; + if (extra) + for (var key in extra) if (extra.hasOwnProperty(key)) + addBinding(key, extra[key]); + return ourMap; + } + + function getHintElement(hintsElement, el) { + while (el && el != hintsElement) { + if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; + el = el.parentNode; + } + } + + function Widget(completion, data) { + this.completion = completion; + this.data = data; + this.picked = false; + var widget = this, cm = completion.cm; + + var hints = this.hints = document.createElement("ul"); + hints.className = "CodeMirror-hints"; + this.selectedHint = data.selectedHint || 0; + + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; + var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); + if (cur.className != null) className = cur.className + " " + className; + elt.className = className; + if (cur.render) cur.render(elt, data, cur); + else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); + elt.hintId = i; + } + + var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); + var left = pos.left, top = pos.bottom, below = true; + hints.style.left = left + "px"; + hints.style.top = top + "px"; + // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. + var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); + var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); + (completion.options.container || document.body).appendChild(hints); + var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; + var scrolls = hints.scrollHeight > hints.clientHeight + 1 + var startScroll = cm.getScrollInfo(); + + if (overlapY > 0) { + var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); + if (curTop - height > 0) { // Fits above cursor + hints.style.top = (top = pos.top - height) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = (winH - 5) + "px"; + hints.style.top = (top = pos.bottom - box.top) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left) + "px"; + box = hints.getBoundingClientRect(); + } + } + } + var overlapX = box.right - winW; + if (overlapX > 0) { + if (box.right - box.left > winW) { + hints.style.width = (winW - 5) + "px"; + overlapX -= (box.right - box.left) - winW; + } + hints.style.left = (left = pos.left - overlapX) + "px"; + } + if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling) + node.style.paddingRight = cm.display.nativeBarWidth + "px" + + cm.addKeyMap(this.keyMap = buildKeyMap(completion, { + moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); }, + setFocus: function(n) { widget.changeActive(n); }, + menuSize: function() { return widget.screenAmount(); }, + length: completions.length, + close: function() { completion.close(); }, + pick: function() { widget.pick(); }, + data: data + })); + + if (completion.options.closeOnUnfocus) { + var closingOnBlur; + cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); }); + cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); }); + } + + cm.on("scroll", this.onScroll = function() { + var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); + var newTop = top + startScroll.top - curScroll.top; + var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); + if (!below) point += hints.offsetHeight; + if (point <= editor.top || point >= editor.bottom) return completion.close(); + hints.style.top = newTop + "px"; + hints.style.left = (left + startScroll.left - curScroll.left) + "px"; + }); + + CodeMirror.on(hints, "dblclick", function(e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();} + }); + + CodeMirror.on(hints, "click", function(e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + if (completion.options.completeOnSingleClick) widget.pick(); + } + }); + + CodeMirror.on(hints, "mousedown", function() { + setTimeout(function(){cm.focus();}, 20); + }); + + CodeMirror.signal(data, "select", completions[0], hints.firstChild); + return true; + } + + Widget.prototype = { + close: function() { + if (this.completion.widget != this) return; + this.completion.widget = null; + this.hints.parentNode.removeChild(this.hints); + this.completion.cm.removeKeyMap(this.keyMap); + + var cm = this.completion.cm; + if (this.completion.options.closeOnUnfocus) { + cm.off("blur", this.onBlur); + cm.off("focus", this.onFocus); + } + cm.off("scroll", this.onScroll); + }, + + disable: function() { + this.completion.cm.removeKeyMap(this.keyMap); + var widget = this; + this.keyMap = {Enter: function() { widget.picked = true; }}; + this.completion.cm.addKeyMap(this.keyMap); + }, + + pick: function() { + this.completion.pick(this.data, this.selectedHint); + }, + + changeActive: function(i, avoidWrap) { + if (i >= this.data.list.length) + i = avoidWrap ? this.data.list.length - 1 : 0; + else if (i < 0) + i = avoidWrap ? 0 : this.data.list.length - 1; + if (this.selectedHint == i) return; + var node = this.hints.childNodes[this.selectedHint]; + node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); + node = this.hints.childNodes[this.selectedHint = i]; + node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; + if (node.offsetTop < this.hints.scrollTop) + this.hints.scrollTop = node.offsetTop - 3; + else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) + this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; + CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); + }, + + screenAmount: function() { + return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; + } + }; + + function applicableHelpers(cm, helpers) { + if (!cm.somethingSelected()) return helpers + var result = [] + for (var i = 0; i < helpers.length; i++) + if (helpers[i].supportsSelection) result.push(helpers[i]) + return result + } + + function fetchHints(hint, cm, options, callback) { + if (hint.async) { + hint(cm, callback, options) + } else { + var result = hint(cm, options) + if (result && result.then) result.then(callback) + else callback(result) + } + } + + function resolveAutoHints(cm, pos) { + var helpers = cm.getHelpers(pos, "hint"), words + if (helpers.length) { + var resolved = function(cm, callback, options) { + var app = applicableHelpers(cm, helpers); + function run(i) { + if (i == app.length) return callback(null) + fetchHints(app[i], cm, options, function(result) { + if (result && result.list.length > 0) callback(result) + else run(i + 1) + }) + } + run(0) + } + resolved.async = true + resolved.supportsSelection = true + return resolved + } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { + return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) } + } else if (CodeMirror.hint.anyword) { + return function(cm, options) { return CodeMirror.hint.anyword(cm, options) } + } else { + return function() {} + } + } + + CodeMirror.registerHelper("hint", "auto", { + resolve: resolveAutoHints + }); + + CodeMirror.registerHelper("hint", "fromList", function(cm, options) { + var cur = cm.getCursor(), token = cm.getTokenAt(cur); + var to = CodeMirror.Pos(cur.line, token.end); + if (token.string && /\w/.test(token.string[token.string.length - 1])) { + var term = token.string, from = CodeMirror.Pos(cur.line, token.start); + } else { + var term = "", from = to; + } + var found = []; + for (var i = 0; i < options.words.length; i++) { + var word = options.words[i]; + if (word.slice(0, term.length) == term) + found.push(word); + } + + if (found.length) return {list: found, from: from, to: to}; + }); + + CodeMirror.commands.autocomplete = CodeMirror.showHint; + + var defaultOptions = { + hint: CodeMirror.hint.auto, + completeSingle: true, + alignWithWord: true, + closeCharacters: /[\s()\[\]{};:>,]/, + closeOnUnfocus: true, + completeOnSingleClick: true, + container: null, + customKeys: null, + extraKeys: null + }; + + CodeMirror.defineOption("hintOptions", null); +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + var Pos = CodeMirror.Pos; + + function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + function arrayContains(arr, item) { + if (!Array.prototype.indexOf) { + var i = arr.length; + while (i--) { + if (arr[i] === item) { + return true; + } + } + return false; + } + return arr.indexOf(item) != -1; + } + + function scriptHint(editor, keywords, getToken, options) { + // Find the token at the cursor + var cur = editor.getCursor(), token = getToken(editor, cur); + if (/\b(?:string|comment)\b/.test(token.type)) return; + token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + + // If it's not a 'word-style' token, ignore the token. + if (!/^[\w$_]*$/.test(token.string)) { + token = {start: cur.ch, end: cur.ch, string: "", state: token.state, + type: token.string == "." ? "property" : null}; + } else if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + var tprop = token; + // If it is a property, find out what it is a property of. + while (tprop.type == "property") { + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (tprop.string != ".") return; + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (!context) var context = []; + context.push(tprop); + } + return {list: getCompletions(token, context, keywords, options), + from: Pos(cur.line, token.start), + to: Pos(cur.line, token.end)}; + } + + function javascriptHint(editor, options) { + return scriptHint(editor, javascriptKeywords, + function (e, cur) {return e.getTokenAt(cur);}, + options); + }; + CodeMirror.registerHelper("hint", "javascript", javascriptHint); + + function getCoffeeScriptToken(editor, cur) { + // This getToken, it is for coffeescript, imitates the behavior of + // getTokenAt method in javascript.js, that is, returning "property" + // type and treat "." as indepenent token. + var token = editor.getTokenAt(cur); + if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { + token.end = token.start; + token.string = '.'; + token.type = "property"; + } + else if (/^\.[\w$_]*$/.test(token.string)) { + token.type = "property"; + token.start++; + token.string = token.string.replace(/\./, ''); + } + return token; + } + + function coffeescriptHint(editor, options) { + return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); + } + CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint); + + var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + + "toUpperCase toLowerCase split concat match replace search").split(" "); + var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); + var funcProps = "prototype apply call bind".split(" "); + var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + + "if in instanceof new null return switch throw true try typeof var void while with").split(" "); + var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + + "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" "); + + function forAllProps(obj, callback) { + if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) { + for (var name in obj) callback(name) + } else { + for (var o = obj; o; o = Object.getPrototypeOf(o)) + Object.getOwnPropertyNames(o).forEach(callback) + } + } + + function getCompletions(token, context, keywords, options) { + var found = [], start = token.string, global = options && options.globalScope || window; + function maybeAdd(str) { + if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str); + } + function gatherCompletions(obj) { + if (typeof obj == "string") forEach(stringProps, maybeAdd); + else if (obj instanceof Array) forEach(arrayProps, maybeAdd); + else if (obj instanceof Function) forEach(funcProps, maybeAdd); + forAllProps(obj, maybeAdd) + } + + if (context && context.length) { + // If this is a property, see if it belongs to some object we can + // find in the current environment. + var obj = context.pop(), base; + if (obj.type && obj.type.indexOf("variable") === 0) { + if (options && options.additionalContext) + base = options.additionalContext[obj.string]; + if (!options || options.useGlobalScope !== false) + base = base || global[obj.string]; + } else if (obj.type == "string") { + base = ""; + } else if (obj.type == "atom") { + base = 1; + } else if (obj.type == "function") { + if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && + (typeof global.jQuery == 'function')) + base = global.jQuery(); + else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function')) + base = global._(); + } + while (base != null && context.length) + base = base[context.pop().string]; + if (base != null) gatherCompletions(base); + } else { + // If not, just look in the global object and any local scope + // (reading into JS mode internals to get at the local and global variables) + for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); + for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name); + if (!options || options.useGlobalScope !== false) + gatherCompletions(global); + forEach(keywords, maybeAdd); + } + return found; + } +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../../mode/sql/sql")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../../mode/sql/sql"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var tables; + var defaultTable; + var keywords; + var identifierQuote; + var CONS = { + QUERY_DIV: ";", + ALIAS_KEYWORD: "AS" + }; + var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; + + function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" } + + function getKeywords(editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).keywords; + } + + function getIdentifierQuote(editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).identifierQuote || "`"; + } + + function getText(item) { + return typeof item == "string" ? item : item.text; + } + + function wrapTable(name, value) { + if (isArray(value)) value = {columns: value} + if (!value.text) value.text = name + return value + } + + function parseTables(input) { + var result = {} + if (isArray(input)) { + for (var i = input.length - 1; i >= 0; i--) { + var item = input[i] + result[getText(item).toUpperCase()] = wrapTable(getText(item), item) + } + } else if (input) { + for (var name in input) + result[name.toUpperCase()] = wrapTable(name, input[name]) + } + return result + } + + function getTable(name) { + return tables[name.toUpperCase()] + } + + function shallowClone(object) { + var result = {}; + for (var key in object) if (object.hasOwnProperty(key)) + result[key] = object[key]; + return result; + } + + function match(string, word) { + var len = string.length; + var sub = getText(word).substr(0, len); + return string.toUpperCase() === sub.toUpperCase(); + } + + function addMatches(result, search, wordlist, formatter) { + if (isArray(wordlist)) { + for (var i = 0; i < wordlist.length; i++) + if (match(search, wordlist[i])) result.push(formatter(wordlist[i])) + } else { + for (var word in wordlist) if (wordlist.hasOwnProperty(word)) { + var val = wordlist[word] + if (!val || val === true) + val = word + else + val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text + if (match(search, val)) result.push(formatter(val)) + } + } + } + + function cleanName(name) { + // Get rid name from identifierQuote and preceding dot(.) + if (name.charAt(0) == ".") { + name = name.substr(1); + } + // replace doublicated identifierQuotes with single identifierQuotes + // and remove single identifierQuotes + var nameParts = name.split(identifierQuote+identifierQuote); + for (var i = 0; i < nameParts.length; i++) + nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), ""); + return nameParts.join(identifierQuote); + } + + function insertIdentifierQuotes(name) { + var nameParts = getText(name).split("."); + for (var i = 0; i < nameParts.length; i++) + nameParts[i] = identifierQuote + + // doublicate identifierQuotes + nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) + + identifierQuote; + var escaped = nameParts.join("."); + if (typeof name == "string") return escaped; + name = shallowClone(name); + name.text = escaped; + return name; + } + + function nameCompletion(cur, token, result, editor) { + // Try to complete table, column names and return start position of completion + var useIdentifierQuotes = false; + var nameParts = []; + var start = token.start; + var cont = true; + while (cont) { + cont = (token.string.charAt(0) == "."); + useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); + + start = token.start; + nameParts.unshift(cleanName(token.string)); + + token = editor.getTokenAt(Pos(cur.line, token.start)); + if (token.string == ".") { + cont = true; + token = editor.getTokenAt(Pos(cur.line, token.start)); + } + } + + // Try to complete table names + var string = nameParts.join("."); + addMatches(result, string, tables, function(w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns from defaultTable + addMatches(result, string, defaultTable, function(w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns + string = nameParts.pop(); + var table = nameParts.join("."); + + var alias = false; + var aliasTable = table; + // Check if table is available. If not, find table by Alias + if (!getTable(table)) { + var oldTable = table; + table = findTableByAlias(table, editor); + if (table !== oldTable) alias = true; + } + + var columns = getTable(table); + if (columns && columns.columns) + columns = columns.columns; + + if (columns) { + addMatches(result, string, columns, function(w) { + var tableInsert = table; + if (alias == true) tableInsert = aliasTable; + if (typeof w == "string") { + w = tableInsert + "." + w; + } else { + w = shallowClone(w); + w.text = tableInsert + "." + w.text; + } + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + } + + return start; + } + + function eachWord(lineText, f) { + if (!lineText) return; + var excepted = /[,;]/g; + var words = lineText.split(" "); + for (var i = 0; i < words.length; i++) { + f(words[i]?words[i].replace(excepted, '') : ''); + } + } + + function findTableByAlias(alias, editor) { + var doc = editor.doc; + var fullQuery = doc.getValue(); + var aliasUpperCase = alias.toUpperCase(); + var previousWord = ""; + var table = ""; + var separator = []; + var validRange = { + start: Pos(0, 0), + end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) + }; + + //add separator + var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); + while(indexOfSeparator != -1) { + separator.push(doc.posFromIndex(indexOfSeparator)); + indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1); + } + separator.unshift(Pos(0, 0)); + separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); + + //find valid range + var prevItem = null; + var current = editor.getCursor() + for (var i = 0; i < separator.length; i++) { + if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { + validRange = {start: prevItem, end: separator[i]}; + break; + } + prevItem = separator[i]; + } + + var query = doc.getRange(validRange.start, validRange.end, false); + + for (var i = 0; i < query.length; i++) { + var lineText = query[i]; + eachWord(lineText, function(word) { + var wordUpperCase = word.toUpperCase(); + if (wordUpperCase === aliasUpperCase && getTable(previousWord)) + table = previousWord; + if (wordUpperCase !== CONS.ALIAS_KEYWORD) + previousWord = word; + }); + if (table) break; + } + return table; + } + + CodeMirror.registerHelper("hint", "sql", function(editor, options) { + tables = parseTables(options && options.tables) + var defaultTableName = options && options.defaultTable; + var disableKeywords = options && options.disableKeywords; + defaultTable = defaultTableName && getTable(defaultTableName); + keywords = getKeywords(editor); + identifierQuote = getIdentifierQuote(editor); + + if (defaultTableName && !defaultTable) + defaultTable = findTableByAlias(defaultTableName, editor); + + defaultTable = defaultTable || []; + + if (defaultTable.columns) + defaultTable = defaultTable.columns; + + var cur = editor.getCursor(); + var result = []; + var token = editor.getTokenAt(cur), start, end, search; + if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + if (token.string.match(/^[.`"\w@]\w*$/)) { + search = token.string; + start = token.start; + end = token.end; + } else { + start = end = cur.ch; + search = ""; + } + if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { + start = nameCompletion(cur, token, result, editor); + } else { + addMatches(result, search, tables, function(w) {return w;}); + addMatches(result, search, defaultTable, function(w) {return w;}); + if (!disableKeywords) + addMatches(result, search, keywords, function(w) {return w.toUpperCase();}); + } + + return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; + }); +}); + +(function () { + var Pos = CodeMirror.Pos; + + function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + function arrayContains(arr, item) { + if (!Array.prototype.indexOf) { + var i = arr.length; + while (i--) { + if (arr[i] === item) { + return true; + } + } + return false; + } + return arr.indexOf(item) != -1; + } + + function scriptHint(editor, keywords, getToken, options) { + // Find the token at the cursor + var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token; + var sToken = token.string.trim(); + + if ( sToken == "(") { + token = tprop = getToken(editor, Pos(cur.line, tprop.start)); + return {list: getCompletions(token.string, keywords, options), + from: Pos(cur.line, token.start), + to: Pos(cur.line, token.end + 1)}; + } + if ( sToken == "=") { + return {list: getCompletions(token.string, keywords, options), + from: Pos(cur.line, token.start + 1), + to: Pos(cur.line, token.end)}; + } + return {list: getCompletions(token.string, keywords, options), + from: Pos(cur.line, token.start), + to: Pos(cur.line, token.end)}; + } + + CodeMirror.phpHint = function(editor, options) { + return scriptHint(editor, phpPMFunctions, function (e, cur) {return e.getTokenAt(cur);}, options); + }; + + var SPACE = " "; + var arrayFunctions = []; + + var formatDate = "formatDate"; + var formatDateFunction = [formatDate+"($date,$format,$language);",formatDate+"($date,$format);"]; + arrayFunctions[formatDate] = formatDateFunction; + + var getCurrentDate = "getCurrentDate"; + var getCurrentDateFunction = [getCurrentDate+"()"]; + arrayFunctions[getCurrentDate] = getCurrentDateFunction; + + var getCurrentTime = "getCurrentTime"; + var getCurrentTimeFunction = [getCurrentTime+"()"]; + arrayFunctions[getCurrentTime] = getCurrentTimeFunction; + + var literalDate = "literalDate"; + var literalDateFunction = [literalDate+"($date,$Language)",literalDate+"($date)"]; + arrayFunctions[literalDate] = literalDateFunction; + + var capitalize = "capitalize"; + var capitalizeFunction = [capitalize+"($textToConvert)"]; + arrayFunctions[capitalize] = capitalizeFunction; + + var lowerCase = "lowerCase"; + var lowerCaseFunction = [lowerCase+"($textToConvert)"]; + arrayFunctions[lowerCase] = lowerCaseFunction; + + var upperCase = "upperCase"; + var upperCaseFunction = [upperCase+"($textToConvert)"]; + arrayFunctions[upperCase] = upperCaseFunction; + + var userInfo = "userInfo"; + var userInfoFunction = [userInfo+"($USER_ID)"]; + arrayFunctions[userInfo] = userInfoFunction; + + var executeQuery = "executeQuery"; + var executeQueryFunction = [executeQuery+"($sqlStatement,$DBConnectionUID)",executeQuery+"($sqlStatement)"]; + arrayFunctions[executeQuery] = executeQueryFunction; + + var orderGrid = "orderGrid"; + var orderGridFunction = ("orderGrid($gridName,$field,$criteria) orderGrid($gridName,$field)").split(SPACE); + arrayFunctions[orderGrid] = orderGridFunction; + + var evaluateFunction = "evaluateFunction"; + var evaluateFunctionFunction = [evaluateFunction+"($gridName,$Expression)"]; + arrayFunctions[evaluateFunction] = evaluateFunctionFunction; + + var PMFTotalCalculation = "PMFTotalCalculation"; + var PMFTotalCalculationFunction = [PMFTotalCalculation + "($gridName, $field, 'function')"]; + arrayFunctions[PMFTotalCalculation] = PMFTotalCalculationFunction; + + var PMFTaskCase = "PMFTaskCase"; + var PMFTaskCaseFunction = [PMFTaskCase+"($caseId)"]; + arrayFunctions[PMFTaskCase] = PMFTaskCaseFunction; + + var PMFTaskList = "PMFTaskList"; + var PMFTaskListFunction = [PMFTaskList+"($userId)"]; + arrayFunctions[PMFTaskList] = PMFTaskListFunction; + + var PMFUserList = "PMFUserList"; + var PMFUserListFunction = [PMFUserList+"()"]; + arrayFunctions[PMFUserList] = PMFUserListFunction; + + var PMFGroupList = "PMFGroupList"; + var PMFGroupListFunction = [PMFGroupList+"()"]; + arrayFunctions[PMFGroupList] = PMFGroupListFunction; + + var PMFRoleList = "PMFRoleList"; + var PMFRoleListFunction = [PMFRoleList+"()"]; + arrayFunctions[PMFRoleList] = PMFRoleListFunction; + + var PMFCaseList = "PMFCaseList"; + var PMFCaseListFunction = [PMFCaseList+"($userId)",PMFCaseList+"()"]; + arrayFunctions[PMFCaseList] = PMFCaseListFunction; + + var PMFProcessList = "PMFProcessList"; + var PMFProcessListFunction = [PMFProcessList+"()"]; + arrayFunctions[PMFProcessList] = PMFProcessListFunction; + + var PMFSendVariables = "PMFSendVariables"; + var PMFSendVariablesFunction = [PMFSendVariables+"($caseId,$variables)"]; + arrayFunctions[PMFSendVariables] = PMFSendVariablesFunction; + + var PMFDerivateCase = "PMFDerivateCase"; + var PMFDerivateCaseFunction = [PMFDerivateCase+"($caseId,$delegation,$executeTriggersBeforeAssigment)",PMFDerivateCase+"($caseId,$delegation)"]; + arrayFunctions[PMFDerivateCase] = PMFDerivateCaseFunction; + + var PMFNewCaseImpersonate = "PMFNewCaseImpersonate"; + var PMFNewCaseImpersonateFunction = [PMFNewCaseImpersonate+"($processId,$userId,$variables)"]; + arrayFunctions[PMFNewCaseImpersonate] = PMFNewCaseImpersonateFunction; + + var PMFNewCase = "PMFNewCase"; + var PMFNewCaseFunction = [PMFNewCase+"($processId,$userId,$taskId,$variables)"]; + arrayFunctions[PMFNewCase] = PMFNewCaseFunction; + + var PMFPauseCase = "PMFPauseCase"; + var PMFPauseCaseFunction = [PMFPauseCase+"($caseUid,$delIndex,$userUid,$unpauseDate)",PMFPauseCase+"($caseUid,$delIndex,$userUid)"]; + arrayFunctions[PMFPauseCase] = PMFPauseCaseFunction; + + var PMFAssignUserToGroup = "PMFAssignUserToGroup"; + var PMFAssignUserToGroupFunction = [PMFAssignUserToGroup+"($userId,$groupId)"]; + arrayFunctions[PMFAssignUserToGroup] = PMFAssignUserToGroupFunction; + + var PMFCreateUser = "PMFCreateUser"; + var PMFCreateUserFunction = [PMFCreateUser+"($userId,$password,$firstname,$lastname,$email,$role)"]; + arrayFunctions[PMFCreateUser] = PMFCreateUserFunction; + + var PMFUpdateUser = "PMFUpdateUser"; + var PMFUpdateUserFunction = [PMFUpdateUser+"($userUid,$userName,$firstName,$lastName,$email,$dueDate,$status,$role,$password)"]; + arrayFunctions[PMFUpdateUser] = PMFUpdateUserFunction; + + var PMFInformationUser = "PMFInformationUser"; + var PMFInformationUserFunction = [PMFInformationUser+"($userUid)"]; + arrayFunctions[PMFInformationUser] = PMFInformationUserFunction; + + var generateCode = "generateCode"; + var generateCodeFunction = [generateCode+"($size,$type)"]; + arrayFunctions[generateCode] = generateCodeFunction; + + var setCaseTrackerCode = "setCaseTrackerCode"; + var setCaseTrackerCodeFunction = [setCaseTrackerCode+"($caseId,$code,$pin)"]; + arrayFunctions[setCaseTrackerCode] = setCaseTrackerCodeFunction; + + var jumping = "jumping"; + var jumpingFunction = [jumping+"($caseId,$delegation)"]; + arrayFunctions[jumping] = jumpingFunction; + + var PMFRedirectToStep = "PMFRedirectToStep"; + var PMFRedirectToStepFunction = [PMFRedirectToStep+"($caseId,$delegation,$stepType,$stepId)"]; + arrayFunctions[PMFRedirectToStep] = PMFRedirectToStepFunction; + + var pauseCase = "pauseCase"; + var pauseCaseFunction = [pauseCase+"($caseId,$delegation,$userId,$unpauseDate)",pauseCase+"($caseId,$delegation,$userId)"]; + arrayFunctions[pauseCase] = pauseCaseFunction; + + var PMFUnpauseCase = "PMFUnpauseCase"; + var PMFUnpauseCaseFunction = [PMFUnpauseCase+"($caseId,$delegation,$userId,$unpauseDate)",PMFUnpauseCase+"($caseId,$delegation,$userId)"]; + arrayFunctions[PMFUnpauseCase] = PMFUnpauseCaseFunction; + + var PMFSendMessage = "PMFSendMessage"; + var PMFSendMessageFunction = [PMFSendMessage+"($caseId,$from,$to,$cc,$bcc,$subject,$template,$fields,$attachments)",PMFSendMessage+"($caseId,$from,$to,$cc,$bcc,$subject,$template,$fields)",PMFSendMessage+"($caseId,$from,$to,$cc,$bcc,$subject,$template)"]; + arrayFunctions[PMFSendMessage] = PMFSendMessageFunction; + + var PMFgetLabelOption = "PMFgetLabelOption"; + var PMFgetLabelOptionFunction = [PMFgetLabelOption+"($processId,$dynaformId,$fieldName,$optionId)"]; + arrayFunctions[PMFgetLabelOption] = PMFgetLabelOptionFunction; + + var PMFGenerateOutputDocument = "PMFGenerateOutputDocument"; + var PMFGenerateOutputDocumentFunction = [PMFGenerateOutputDocument+"($outputID)"]; + arrayFunctions[PMFGenerateOutputDocument] = PMFGenerateOutputDocumentFunction; + + var PMFGetUserEmailAddress = "PMFGetUserEmailAddress"; + var PMFGetUserEmailAddressFunction = [PMFGetUserEmailAddress+"($id,$APP_UID,$prefix)",PMFGetUserEmailAddress+"($id,$APP_UID)",PMFGetUserEmailAddress+"($id)"]; + arrayFunctions[PMFGetUserEmailAddress] = PMFGetUserEmailAddressFunction; + + var PMFGetNextAssignedUser = "PMFGetNextAssignedUser"; + var PMFGetNextAssignedUserFunction = (PMFGetNextAssignedUser+"($application,$task)").split(SPACE); + arrayFunctions[PMFGetNextAssignedUser] = PMFGetNextAssignedUserFunction; + + var PMFDeleteCase = "PMFDeleteCase"; + var PMFDeleteCaseFunction = ("PMFDeleteCase($caseId)").split(SPACE); + arrayFunctions[PMFDeleteCase] = PMFDeleteCaseFunction; + + var PMFCancelCase = "PMFCancelCase"; + var PMFCancelCaseFunction = [PMFCancelCase+"($caseUid,$delIndex,$userUid)"]; + arrayFunctions[PMFCancelCase] = PMFCancelCaseFunction; + + var PMFAddInputDocument = "PMFAddInputDocument"; + var PMFAddInputDocumentFunction = [PMFAddInputDocument+"($inputDocumentUid,$appDocUid,$docVersion,$appDocType,$appDocComment,$inputDocumentAction,$caseUid,$delIndex,$taskUid,$userUid,$option,$file)",PMFAddInputDocument+"($inputDocumentUid,$appDocUid,$docVersion,$appDocType,$appDocComment,$inputDocumentAction,$caseUid,$delIndex,$taskUid,$userUid,$option)",PMFAddInputDocument+"($inputDocumentUid,$appDocUid,$docVersion,$appDocType,$appDocComment,$inputDocumentAction,$caseUid,$delIndex,$taskUid,$userUid)"]; + arrayFunctions[PMFAddInputDocument] = PMFAddInputDocumentFunction; + + var PMFAddCaseNote = "PMFAddCaseNote"; + var PMFAddCaseNoteFunction = [PMFAddCaseNote+"($caseUid,$processUid,$taskUid,$userUid,$note,$sendMail)"]; + arrayFunctions[PMFAddCaseNote] = PMFAddCaseNoteFunction; + + var PMFGetCaseNotes = "PMFGetCaseNotes"; + var PMFGetCaseNotesFunction = [PMFGetCaseNotes+"($applicationID,$type,$userUid);",PMFGetCaseNotes+"($applicationID,$type)",PMFGetCaseNotes+"($applicationID)"]; + arrayFunctions[PMFGetCaseNotes] = PMFGetCaseNotesFunction; + + var phpPMFunctions = [formatDate,getCurrentDate,getCurrentTime,literalDate,capitalize,lowerCase,upperCase,userInfo,executeQuery,orderGrid, + evaluateFunction, PMFTotalCalculation, PMFTaskCase,PMFTaskList,PMFUserList,PMFGroupList,PMFRoleList,PMFCaseList,PMFProcessList,PMFSendVariables,PMFDerivateCase, + PMFNewCaseImpersonate,PMFNewCase,PMFPauseCase,PMFUnpauseCase,PMFAssignUserToGroup,PMFCreateUser,PMFUpdateUser,PMFInformationUser, + generateCode,setCaseTrackerCode,jumping,PMFRedirectToStep,pauseCase,PMFSendMessage,PMFgetLabelOption,PMFGenerateOutputDocument, + PMFGetUserEmailAddress,PMFGetNextAssignedUser,PMFDeleteCase,PMFCancelCase,PMFAddInputDocument,PMFAddCaseNote,PMFGetCaseNotes]; + + var phpKeywords = ("break case catch continue default do else false for function " + + "if new return switch throw true try var while").split(SPACE); + + function getCompletions(functionName, keywords, options) { + + var found = []; + + function maybeAdd(str) {// for keywords ? + if ( str.indexOf(functionName) == 0 && !arrayContains(found, str)) { + found.push(str); + } + } + + function yesAdd(str) { + if ( !arrayContains(found, str)) { + found.push(str); + } + } + + arrayFunction = arrayFunctions[functionName]; + + if (arrayFunction != undefined) { + forEach( arrayFunction, yesAdd); + } else { + if (functionName.trim() == "") { + forEach (phpKeywords, yesAdd); + forEach (keywords, yesAdd); + } else if (functionName == "=") { + forEach (phpPMFunctions, yesAdd); + } else { + for (index = 0; index < phpKeywords.length; index++) { + if ( phpKeywords[index].indexOf(functionName) == 0 ) { + found.push(phpKeywords[index]); + } + } + forEach(keywords, maybeAdd); + } + } + return found; + } +})(); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("./xml-hint")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "./xml-hint"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" "); + var targets = ["_blank", "_self", "_top", "_parent"]; + var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"]; + var methods = ["get", "post", "put", "delete"]; + var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]; + var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech", + "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait", + "orientation:landscape", "device-height: [X]", "device-width: [X]"]; + var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags + + var data = { + a: { + attrs: { + href: null, ping: null, type: null, + media: media, + target: targets, + hreflang: langs + } + }, + abbr: s, + acronym: s, + address: s, + applet: s, + area: { + attrs: { + alt: null, coords: null, href: null, target: null, ping: null, + media: media, hreflang: langs, type: null, + shape: ["default", "rect", "circle", "poly"] + } + }, + article: s, + aside: s, + audio: { + attrs: { + src: null, mediagroup: null, + crossorigin: ["anonymous", "use-credentials"], + preload: ["none", "metadata", "auto"], + autoplay: ["", "autoplay"], + loop: ["", "loop"], + controls: ["", "controls"] + } + }, + b: s, + base: { attrs: { href: null, target: targets } }, + basefont: s, + bdi: s, + bdo: s, + big: s, + blockquote: { attrs: { cite: null } }, + body: s, + br: s, + button: { + attrs: { + form: null, formaction: null, name: null, value: null, + autofocus: ["", "autofocus"], + disabled: ["", "autofocus"], + formenctype: encs, + formmethod: methods, + formnovalidate: ["", "novalidate"], + formtarget: targets, + type: ["submit", "reset", "button"] + } + }, + canvas: { attrs: { width: null, height: null } }, + caption: s, + center: s, + cite: s, + code: s, + col: { attrs: { span: null } }, + colgroup: { attrs: { span: null } }, + command: { + attrs: { + type: ["command", "checkbox", "radio"], + label: null, icon: null, radiogroup: null, command: null, title: null, + disabled: ["", "disabled"], + checked: ["", "checked"] + } + }, + data: { attrs: { value: null } }, + datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } }, + datalist: { attrs: { data: null } }, + dd: s, + del: { attrs: { cite: null, datetime: null } }, + details: { attrs: { open: ["", "open"] } }, + dfn: s, + dir: s, + div: s, + dl: s, + dt: s, + em: s, + embed: { attrs: { src: null, type: null, width: null, height: null } }, + eventsource: { attrs: { src: null } }, + fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } }, + figcaption: s, + figure: s, + font: s, + footer: s, + form: { + attrs: { + action: null, name: null, + "accept-charset": charsets, + autocomplete: ["on", "off"], + enctype: encs, + method: methods, + novalidate: ["", "novalidate"], + target: targets + } + }, + frame: s, + frameset: s, + h1: s, h2: s, h3: s, h4: s, h5: s, h6: s, + head: { + attrs: {}, + children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"] + }, + header: s, + hgroup: s, + hr: s, + html: { + attrs: { manifest: null }, + children: ["head", "body"] + }, + i: s, + iframe: { + attrs: { + src: null, srcdoc: null, name: null, width: null, height: null, + sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"], + seamless: ["", "seamless"] + } + }, + img: { + attrs: { + alt: null, src: null, ismap: null, usemap: null, width: null, height: null, + crossorigin: ["anonymous", "use-credentials"] + } + }, + input: { + attrs: { + alt: null, dirname: null, form: null, formaction: null, + height: null, list: null, max: null, maxlength: null, min: null, + name: null, pattern: null, placeholder: null, size: null, src: null, + step: null, value: null, width: null, + accept: ["audio/*", "video/*", "image/*"], + autocomplete: ["on", "off"], + autofocus: ["", "autofocus"], + checked: ["", "checked"], + disabled: ["", "disabled"], + formenctype: encs, + formmethod: methods, + formnovalidate: ["", "novalidate"], + formtarget: targets, + multiple: ["", "multiple"], + readonly: ["", "readonly"], + required: ["", "required"], + type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month", + "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio", + "file", "submit", "image", "reset", "button"] + } + }, + ins: { attrs: { cite: null, datetime: null } }, + kbd: s, + keygen: { + attrs: { + challenge: null, form: null, name: null, + autofocus: ["", "autofocus"], + disabled: ["", "disabled"], + keytype: ["RSA"] + } + }, + label: { attrs: { "for": null, form: null } }, + legend: s, + li: { attrs: { value: null } }, + link: { + attrs: { + href: null, type: null, + hreflang: langs, + media: media, + sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"] + } + }, + map: { attrs: { name: null } }, + mark: s, + menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } }, + meta: { + attrs: { + content: null, + charset: charsets, + name: ["viewport", "application-name", "author", "description", "generator", "keywords"], + "http-equiv": ["content-language", "content-type", "default-style", "refresh"] + } + }, + meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } }, + nav: s, + noframes: s, + noscript: s, + object: { + attrs: { + data: null, type: null, name: null, usemap: null, form: null, width: null, height: null, + typemustmatch: ["", "typemustmatch"] + } + }, + ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } }, + optgroup: { attrs: { disabled: ["", "disabled"], label: null } }, + option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } }, + output: { attrs: { "for": null, form: null, name: null } }, + p: s, + param: { attrs: { name: null, value: null } }, + pre: s, + progress: { attrs: { value: null, max: null } }, + q: { attrs: { cite: null } }, + rp: s, + rt: s, + ruby: s, + s: s, + samp: s, + script: { + attrs: { + type: ["text/javascript"], + src: null, + async: ["", "async"], + defer: ["", "defer"], + charset: charsets + } + }, + section: s, + select: { + attrs: { + form: null, name: null, size: null, + autofocus: ["", "autofocus"], + disabled: ["", "disabled"], + multiple: ["", "multiple"] + } + }, + small: s, + source: { attrs: { src: null, type: null, media: null } }, + span: s, + strike: s, + strong: s, + style: { + attrs: { + type: ["text/css"], + media: media, + scoped: null + } + }, + sub: s, + summary: s, + sup: s, + table: s, + tbody: s, + td: { attrs: { colspan: null, rowspan: null, headers: null } }, + textarea: { + attrs: { + dirname: null, form: null, maxlength: null, name: null, placeholder: null, + rows: null, cols: null, + autofocus: ["", "autofocus"], + disabled: ["", "disabled"], + readonly: ["", "readonly"], + required: ["", "required"], + wrap: ["soft", "hard"] + } + }, + tfoot: s, + th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } }, + thead: s, + time: { attrs: { datetime: null } }, + title: s, + tr: s, + track: { + attrs: { + src: null, label: null, "default": null, + kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"], + srclang: langs + } + }, + tt: s, + u: s, + ul: s, + "var": s, + video: { + attrs: { + src: null, poster: null, width: null, height: null, + crossorigin: ["anonymous", "use-credentials"], + preload: ["auto", "metadata", "none"], + autoplay: ["", "autoplay"], + mediagroup: ["movie"], + muted: ["", "muted"], + controls: ["", "controls"] + } + }, + wbr: s + }; + + var globalAttrs = { + accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], + "class": null, + contenteditable: ["true", "false"], + contextmenu: null, + dir: ["ltr", "rtl", "auto"], + draggable: ["true", "false", "auto"], + dropzone: ["copy", "move", "link", "string:", "file:"], + hidden: ["hidden"], + id: null, + inert: ["inert"], + itemid: null, + itemprop: null, + itemref: null, + itemscope: ["itemscope"], + itemtype: null, + lang: ["en", "es"], + spellcheck: ["true", "false"], + style: null, + tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"], + title: null, + translate: ["yes", "no"], + onclick: null, + rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"] + }; + function populate(obj) { + for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr)) + obj.attrs[attr] = globalAttrs[attr]; + } + + populate(s); + for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s) + populate(data[tag]); + + CodeMirror.htmlSchema = data; + function htmlHint(cm, options) { + var local = {schemaInfo: data}; + if (options) for (var opt in options) local[opt] = options[opt]; + return CodeMirror.hint.xml(cm, local); + } + CodeMirror.registerHelper("hint", "html", htmlHint); +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function expressionAllowed(stream, state, backUp) { + return /^(?:operator|sof|keyword c|case|new|export|default|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) +} + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + var jsKeywords = { + "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C, + "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C, "async": kw("async") + }; + + // Extend the 'normal' keywords with the TypeScript language extensions + if (isTS) { + var type = {type: "variable", style: "variable-3"}; + var tsKeywords = { + // object-like things + "interface": kw("class"), + "implements": C, + "namespace": C, + "module": kw("module"), + "enum": kw("module"), + "type": kw("type"), + + // scope modifiers + "public": kw("modifier"), + "private": kw("modifier"), + "protected": kw("modifier"), + "abstract": kw("modifier"), + + // operators + "as": operator, + + // types + "string": type, "number": type, "boolean": type, "any": type + }; + + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + + return jsKeywords; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } else if (ch == "0" && stream.eat(/o/i)) { + stream.eatWhile(/[0-7]/i); + return ret("number", "number"); + } else if (ch == "0" && stream.eat(/b/i)) { + stream.eatWhile(/[01]/i); + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") + stream.eatWhile(isOperatorChar); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + + var brackets = "([{}])"; + // This is a crude lookahead trick to try and notice that we're + // parsing the argument patterns for a fat-arrow function before we + // actually hit the arrow token. It only works if the arrow is on + // the same line as the arguments and there's no strange noise + // (comments) in between. Fallback is to only notice when we hit the + // arrow, and not declare the arguments as locals for the arrow + // body. + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { ++pos; break; } + if (--depth == 0) { if (ch == "(") sawSomething = true; break; } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/]/.test(ch)) { + return; + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx = state.context; cx; cx = cx.prev) { + for (var v = cx.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function register(varname) { + function inList(list) { + for (var v = list; v; v = v.next) + if (v.name == varname) return true; + return false; + } + var state = cx.state; + cx.marked = "def"; + if (state.context) { + if (inList(state.localVars)) return; + state.localVars = {name: varname, next: state.localVars}; + } else { + if (inList(state.globalVars)) return; + if (parserConfig.globalVars) + state.globalVars = {name: varname, next: state.globalVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: {name: "arguments"}}; + function pushcontext() { + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + cx.state.localVars = defaultVars; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + function exp(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(exp); + }; + return exp; + } + + function statement(type, value) { + if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), block, poplex); + if (type == ";") return cont(); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), parenExpr, pushlex("}", "switch"), expect("{"), + block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), + statement, poplex, popcontext); + if (type == "class") return cont(pushlex("form"), className, poplex); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex) + if (type == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";")); + if (type == "async") return cont(statement) + if (value == "@") return cont(expression, statement) + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + return expressionInner(type, false); + } + function expressionNoComma(type) { + return expressionInner(type, true); + } + function parenExpr(type) { + if (type != "(") return pass() + return cont(pushlex(")"), expression, expect(")"), poplex) + } + function expressionInner(type, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); + else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "class") return cont(pushlex("form"), classExpression, poplex); + if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeexpressionNoComma(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expressionNoComma); + } + + function maybeoperatorComma(type, value) { + if (type == ",") return cont(expression); + return maybeoperatorNoComma(type, value, false); + } + function maybeoperatorNoComma(type, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "operator") { + if (/\+\+|--/.test(value)) return cont(me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type == "quasi") { return pass(quasi, me); } + if (type == ";") return; + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type == ".") return cont(property, me); + if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + } + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(expression, continueQuasi); + } + function continueQuasi(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expression); + } + function arrowBodyNoComma(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type, value) { + if (type == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + return cont(afterprop); + } else if (type == "number" || type == "string") { + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (type == "modifier") { + return cont(objprop) + } else if (type == "[") { + return cont(expression, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expression); + } else if (type == ":") { + return pass(afterprop) + } + } + function getterSetter(type) { + if (type != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type) { + if (type == ":") return cont(expressionNoComma); + if (type == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type, value) { + if (sep ? sep.indexOf(type) > -1 : type == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function(type, value) { + if (type == end || value == end) return pass() + return pass(what) + }, proceed); + } + if (type == end || value == end) return cont(); + return cont(expect(end)); + } + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type, value) { + if (isTS) { + if (type == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function typeexpr(type) { + if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);} + if (type == "string" || type == "number" || type == "atom") return cont(afterType); + if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex) + if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType) + } + function maybeReturnType(type) { + if (type == "=>") return cont(typeexpr) + } + function typeprop(type, value) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property" + return cont(typeprop) + } else if (value == "?") { + return cont(typeprop) + } else if (type == ":") { + return cont(typeexpr) + } + } + function typearg(type) { + if (type == "variable") return cont(typearg) + else if (type == ":") return cont(typeexpr) + } + function afterType(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + if (value == "|" || type == ".") return cont(typeexpr) + if (type == "[") return cont(expect("]"), afterType) + } + function vardef() { + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type, value) { + if (type == "modifier") return cont(pattern) + if (type == "variable") { register(value); return cont(); } + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(pattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type, value) { + if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); + return cont(expect(":"), pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type) { + if (type == ",") return cont(vardef); + } + function maybeelse(type, value) { + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type) { + if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); + } + function forspec1(type) { + if (type == "var") return cont(vardef, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybeinof); + return pass(expression, expect(";"), forspec2); + } + function formaybeinof(_type, value) { + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return cont(maybeoperatorComma, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return pass(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, functiondef) + } + function funarg(type) { + if (type == "spread") return cont(funarg); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); + } + function className(type, value) { + if (type == "variable") {register(value); return cont(classNameAfter);} + } + function classNameAfter(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, classNameAfter) + if (value == "extends" || value == "implements" || (isTS && type == ",")) + return cont(isTS ? typeexpr : expression, classNameAfter); + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "variable" || cx.style == "keyword") { + if ((value == "async" || value == "static" || value == "get" || value == "set" || + (isTS && (value == "public" || value == "private" || value == "protected" || value == "readonly" || value == "abstract"))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { + cx.marked = "keyword"; + return cont(classBody); + } + cx.marked = "property"; + return cont(isTS ? classfield : functiondef, classBody); + } + if (type == "[") + return cont(expression, expect("]"), isTS ? classfield : functiondef, classBody) + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == ";") return cont(classBody); + if (type == "}") return cont(); + if (value == "@") return cont(expression, classBody) + } + function classfield(type, value) { + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) + if (value == "=") return cont(expressionNoComma) + return pass(functiondef) + } + function afterExport(type, value) { + if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } + if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } + if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } + if (type == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type) { + if (type == "string") return cont(); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type, value) { + if (type == "{") return contCommasep(importSpec, "}"); + if (type == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type) { + if (type == ",") return cont(importSpec, maybeMoreImports) + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } + } + function maybeFrom(_type, value) { + if (value == "from") { cx.marked = "keyword"; return cont(expression); } + } + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); + } + + // Interface + + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == tokenComment) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top + // Kludge to prevent 'maybelse' from blocking lexical scope pops + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter)))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + + helperType: jsonMode ? "json" : "javascript", + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + skipExpression: function(state) { + var top = state.cc[state.cc.length - 1] + if (top == expression || top == expressionNoComma) state.cc.pop() + } + }; +}); + +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && + (document.documentMode == null || document.documentMode < 8); + + var Pos = CodeMirror.Pos; + + var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; + + function findMatchingBracket(cm, where, strict, config) { + var line = cm.getLineHandle(where.line), pos = where.ch - 1; + var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; + if (!match) return null; + var dir = match.charAt(1) == ">" ? 1 : -1; + if (strict && (dir > 0) != (pos == where.ch)) return null; + var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); + + var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config); + if (found == null) return null; + return {from: Pos(where.line, pos), to: found && found.pos, + match: found && found.ch == match.charAt(0), forward: dir > 0}; + } + + // bracketRegex is used to specify which type of bracket to scan + // should be a regexp, e.g. /[[\]]/ + // + // Note: If "where" is on an open bracket, then this bracket is ignored. + // + // Returns false when no bracket was found, null when it reached + // maxScanLines and gave up + function scanForBracket(cm, where, dir, style, config) { + var maxScanLen = (config && config.maxScanLineLength) || 10000; + var maxScanLines = (config && config.maxScanLines) || 1000; + + var stack = []; + var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/; + var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) + : Math.max(cm.firstLine() - 1, where.line - maxScanLines); + for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { + var line = cm.getLine(lineNo); + if (!line) continue; + var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1; + if (line.length > maxScanLen) continue; + if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); + for (; pos != end; pos += dir) { + var ch = line.charAt(pos); + if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) { + var match = matching[ch]; + if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch); + else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch}; + else stack.pop(); + } + } + } + return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; + } + + function matchBrackets(cm, autoclear, config) { + // Disable brace matching in long lines, since it'll cause hugely slow updates + var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; + var marks = [], ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config); + if (match && cm.getLine(match.from.line).length <= maxHighlightLen) { + var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style})); + if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) + marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style})); + } + } + + if (marks.length) { + // Kludge to work around the IE bug from issue #1193, where text + // input stops going to the textare whever this fires. + if (ie_lt8 && cm.state.focused) cm.focus(); + + var clear = function() { + cm.operation(function() { + for (var i = 0; i < marks.length; i++) marks[i].clear(); + }); + }; + if (autoclear) setTimeout(clear, 800); + else return clear; + } + } + + var currentlyHighlighted = null; + function doMatchBrackets(cm) { + cm.operation(function() { + if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} + currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); + }); + } + + CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.off("cursorActivity", doMatchBrackets); + if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} + } + if (val) { + cm.state.matchBrackets = typeof val == "object" ? val : {}; + cm.on("cursorActivity", doMatchBrackets); + } + }); + + CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); + CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){ + return findMatchingBracket(this, pos, strict, config); + }); + CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){ + return scanForBracket(this, pos, dir, style, config); + }); +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + + function maybeBackup(stream, pat, style) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur); + } + return style; + } + + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); + } + + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)) + return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" + } + + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); + } + + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]) + } + } + + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; + } + } + + CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag + }); + + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName + if (tag && !/[<>\s\/]/.test(stream.current()) && + (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && + tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " " + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag) + state.inTag = null + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) + var mode = CodeMirror.getMode(config, modeSpec) + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function (stream, state) { + if (stream.match(endTagA, false)) { + state.token = html; + state.localState = state.localMode = null; + return null; + } + return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "")); + } else if (state.inTag) { + state.inTag += stream.current() + if (stream.eol()) state.inTag += " " + } + return style; + }; + + return { + startState: function () { + var state = CodeMirror.startState(htmlMode); + return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function (state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return {token: state.token, inTag: state.inTag, + localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function (stream, state) { + return state.token(stream, state); + }, + + indent: function (state, textAfter) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter); + else + return CodeMirror.Pass; + }, + + innerMode: function (state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; + }, "xml", "javascript", "css"); + + CodeMirror.defineMIME("text/html", "htmlmixed"); +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] + + // Return variables for tokenizers + var type, setStyle; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(parentTagName) || + !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(state); + } + } + + function baseState(type, stream, state) { + if (type == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(state.context.tagName)) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); + } + + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(tagName)) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); + } + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} + setStyle = "error"; + return attrState(type, stream, state); + } + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); + } + + return { + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state + }, + + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + // Indent multi-line strings (e.g. css). + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + // Indent the starts of attribute names. + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + } + }; +}); + +CodeMirror.defineMIME("text/xml", "xml"); +CodeMirror.defineMIME("application/xml", "xml"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + lineComment = parserConfig.lineComment, + supportsAtComponent = parserConfig.supportsAtComponent === true; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]+/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || + (ch == "d" && stream.match("omain(")) || + (ch == "r" && stream.match("egexp("))) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "word"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "meta") return "pseudo"; + + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + cx = cx.prev; + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: lineComment, + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i].toLowerCase()] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-blend-mode", "background-clip", + "background-color", "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", + "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", + "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", + "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "region-break-after", + "region-break-before", "region-break-inside", "region-fragment", + "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", + "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", + "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "contain", "content", "contents", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", "transform", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/\s*\{/, false)) + return [null, null] + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function Context(indented, column, type, info, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.info = info; + this.align = align; + this.prev = prev; +} +function pushContext(state, col, type, info) { + var indent = state.indented; + if (state.context && state.context.type == "statement" && type != "statement") + indent = state.context.indented; + return state.context = new Context(indent, col, type, info, null, state.context); +} +function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; +} + +function typeBefore(stream, state, pos) { + if (state.prevToken == "variable" || state.prevToken == "variable-3") return true; + if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; + if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; +} + +function isTopScope(context) { + for (;;) { + if (!context || context.type == "top") return true; + if (context.type == "}" && context.prev.info != "namespace") return false; + context = context.prev; + } +} + +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, + statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, + dontAlignCalls = parserConfig.dontAlignCalls, + keywords = parserConfig.keywords || {}, + types = parserConfig.types || {}, + builtin = parserConfig.builtin || {}, + blockKeywords = parserConfig.blockKeywords || {}, + defKeywords = parserConfig.defKeywords || {}, + atoms = parserConfig.atoms || {}, + hooks = parserConfig.hooks || {}, + multiLineStrings = parserConfig.multiLineStrings, + indentStatements = parserConfig.indentStatements !== false, + indentSwitch = parserConfig.indentSwitch !== false, + namespaceSeparator = parserConfig.namespaceSeparator, + isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, + numberStart = parserConfig.numberStart || /[\d\.]/, + number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, + isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, + isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/; + + var curPunc, isDefKeyword; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (isPunctuationChar.test(ch)) { + curPunc = ch; + return null; + } + if (numberStart.test(ch)) { + stream.backUp(1) + if (stream.match(number)) return "number" + stream.next() + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} + return "operator"; + } + stream.eatWhile(isIdentifierChar); + if (namespaceSeparator) while (stream.match(namespaceSeparator)) + stream.eatWhile(isIdentifierChar); + + var cur = stream.current(); + if (contains(keywords, cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + if (contains(defKeywords, cur)) isDefKeyword = true; + return "keyword"; + } + if (contains(types, cur)) return "variable-3"; + if (contains(builtin, cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + return "builtin"; + } + if (contains(atoms, cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function maybeEOL(stream, state) { + if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) + state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), + indented: 0, + startOfLine: true, + prevToken: null + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) { maybeEOL(stream, state); return null; } + curPunc = isDefKeyword = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) + while (state.context.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (indentStatements && + (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || + (ctx.type == "statement" && curPunc == "newstatement"))) { + pushContext(state, stream.column(), "statement", stream.current()); + } + + if (style == "variable" && + ((state.prevToken == "def" || + (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && + isTopScope(state.context) && stream.match(/^\s*\(/, false))))) + style = "def"; + + if (hooks.token) { + var result = hooks.token(stream, state, style); + if (result !== undefined) style = result; + } + + if (style == "def" && parserConfig.styleDefs === false) style = "variable"; + + state.startOfLine = false; + state.prevToken = isDefKeyword ? "def" : style || curPunc; + maybeEOL(stream, state); + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; + if (parserConfig.dontIndentStatements) + while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) + ctx = ctx.prev + if (hooks.indent) { + var hook = hooks.indent(state, ctx, textAfter); + if (typeof hook == "number") return hook + } + var closing = firstChar == ctx.type; + var switchBlock = ctx.prev && ctx.prev.info == "switch"; + if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { + while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev + return ctx.indented + } + if (ctx.type == "statement") + return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); + if (ctx.align && (!dontAlignCalls || ctx.type != ")")) + return ctx.column + (closing ? 0 : 1); + if (ctx.type == ")" && !closing) + return ctx.indented + statementIndentUnit; + + return ctx.indented + (closing ? 0 : indentUnit) + + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); + }, + + electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//", + fold: "brace" + }; +}); + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + function contains(words, word) { + if (typeof words === "function") { + return words(word); + } else { + return words.propertyIsEnumerable(word); + } + } + var cKeywords = "auto if break case register continue return default do sizeof " + + "static else struct switch extern typedef union for goto while enum const volatile"; + var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t"; + + function cppHook(stream, state) { + if (!state.startOfLine) return false + for (var ch, next = null; ch = stream.peek();) { + if (ch == "\\" && stream.match(/^.$/)) { + next = cppHook + break + } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { + break + } + stream.next() + } + state.tokenize = next + return "meta" + } + + function pointerHook(_stream, state) { + if (state.prevToken == "variable-3") return "variable-3"; + return false; + } + + function cpp14Literal(stream) { + stream.eatWhile(/[\w\.']/); + return "number"; + } + + function cpp11StringHook(stream, state) { + stream.backUp(1); + // Raw strings. + if (stream.match(/(R|u8R|uR|UR|LR)/)) { + var match = stream.match(/"([^\s\\()]{0,16})\(/); + if (!match) { + return false; + } + state.cpp11RawStringDelim = match[1]; + state.tokenize = tokenRawString; + return tokenRawString(stream, state); + } + // Unicode strings/chars. + if (stream.match(/(u8|u|U|L)/)) { + if (stream.match(/["']/, /* eat */ false)) { + return "string"; + } + return false; + } + // Ignore this hook. + stream.next(); + return false; + } + + function cppLooksLikeConstructor(word) { + var lastTwo = /(\w+)::~?(\w+)$/.exec(word); + return lastTwo && lastTwo[1] == lastTwo[2]; + } + + // C#-style strings where "" escapes a quote. + function tokenAtString(stream, state) { + var next; + while ((next = stream.next()) != null) { + if (next == '"' && !stream.eat('"')) { + state.tokenize = null; + break; + } + } + return "string"; + } + + // C++11 raw string literal is "( anything )", where + // can be a string up to 16 characters long. + function tokenRawString(stream, state) { + // Escape characters that have special regex meanings. + var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); + var match = stream.match(new RegExp(".*?\\)" + delim + '"')); + if (match) + state.tokenize = null; + else + stream.skipToEnd(); + return "string"; + } + + function def(mimes, mode) { + if (typeof mimes == "string") mimes = [mimes]; + var words = []; + function add(obj) { + if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) + words.push(prop); + } + add(mode.keywords); + add(mode.types); + add(mode.builtin); + add(mode.atoms); + if (words.length) { + mode.helperType = mimes[0]; + CodeMirror.registerHelper("hintWords", mimes[0], words); + } + + for (var i = 0; i < mimes.length; ++i) + CodeMirror.defineMIME(mimes[i], mode); + } + + def(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " + + "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " + + "uint32_t uint64_t"), + blockKeywords: words("case do else for if switch while struct"), + defKeywords: words("struct"), + typeFirstDefinitions: true, + atoms: words("null true false"), + hooks: {"#": cppHook, "*": pointerHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " + + "static_cast typeid catch operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected " + + "alignas alignof constexpr decltype nullptr noexcept thread_local final " + + "static_assert override"), + types: words(cTypes + " bool wchar_t"), + blockKeywords: words("catch class do else finally for if struct switch try while"), + defKeywords: words("class namespace struct enum union"), + typeFirstDefinitions: true, + atoms: words("true false null"), + dontIndentStatements: /^template$/, + isIdentifierChar: /[\w\$_~\xa1-\uffff]/, + hooks: { + "#": cppHook, + "*": pointerHook, + "u": cpp11StringHook, + "U": cpp11StringHook, + "L": cpp11StringHook, + "R": cpp11StringHook, + "0": cpp14Literal, + "1": cpp14Literal, + "2": cpp14Literal, + "3": cpp14Literal, + "4": cpp14Literal, + "5": cpp14Literal, + "6": cpp14Literal, + "7": cpp14Literal, + "8": cpp14Literal, + "9": cpp14Literal, + token: function(stream, state, style) { + if (style == "variable" && stream.peek() == "(" && + (state.prevToken == ";" || state.prevToken == null || + state.prevToken == "}") && + cppLooksLikeConstructor(stream.current())) + return "def"; + } + }, + namespaceSeparator: "::", + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-java", { + name: "clike", + keywords: words("abstract assert break case catch class const continue default " + + "do else enum extends final finally float for goto if implements import " + + "instanceof interface native new package private protected public " + + "return static strictfp super switch synchronized this throw throws transient " + + "try volatile while @interface"), + types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), + blockKeywords: words("catch class do else finally for if switch try while"), + defKeywords: words("class interface package enum @interface"), + typeFirstDefinitions: true, + atoms: words("true false null"), + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + hooks: { + "@": function(stream) { + // Don't match the @interface keyword. + if (stream.match('interface', false)) return false; + + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + }, + modeProps: {fold: ["brace", "import"]} + }); + + def("text/x-csharp", { + name: "clike", + keywords: words("abstract as async await base break case catch checked class const continue" + + " default delegate do else enum event explicit extern finally fixed for" + + " foreach goto if implicit in interface internal is lock namespace new" + + " operator out override params private protected public readonly ref return sealed" + + " sizeof stackalloc static struct switch this throw try typeof unchecked" + + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + + " global group into join let orderby partial remove select set value var yield"), + types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + + " UInt64 bool byte char decimal double short int long object" + + " sbyte float string ushort uint ulong"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + defKeywords: words("class interface namespace struct var"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + + function tokenTripleString(stream, state) { + var escaped = false; + while (!stream.eol()) { + if (!escaped && stream.match('"""')) { + state.tokenize = null; + break; + } + escaped = stream.next() == "\\" && !escaped; + } + return "string"; + } + + def("text/x-scala", { + name: "clike", + keywords: words( + + /* scala */ + "abstract case catch class def do else extends final finally for forSome if " + + "implicit import lazy match new null object override package private protected return " + + "sealed super this throw trait try type val var while with yield _ " + + + /* package scala */ + "assert assume require print println printf readLine readBoolean readByte readShort " + + "readChar readInt readLong readFloat readDouble" + ), + types: words( + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + + + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + multiLineStrings: true, + blockKeywords: words("catch class do else finally for forSome if match switch try while"), + defKeywords: words("class def object package trait type val var"), + atoms: words("true false null"), + indentStatements: false, + indentSwitch: false, + isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + if (!stream.match('""')) return false; + state.tokenize = tokenTripleString; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + "=": function(stream, state) { + var cx = state.context + if (cx.type == "}" && cx.align && stream.eat(">")) { + state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) + return "operator" + } else { + return false + } + } + }, + modeProps: {closeBrackets: {triples: '"'}} + }); + + function tokenKotlinString(tripleString){ + return function (stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} + if (tripleString && stream.match('"""')) {end = true; break;} + next = stream.next(); + if(!escaped && next == "$" && stream.match('{')) + stream.skipTo("}"); + escaped = !escaped && next == "\\" && !tripleString; + } + if (end || !tripleString) + state.tokenize = null; + return "string"; + } + } + + def("text/x-kotlin", { + name: "clike", + keywords: words( + /*keywords*/ + "package as typealias class interface this super val " + + "var fun for is in This throw return " + + "break continue object if else while do try when !in !is as? " + + + /*soft keywords*/ + "file import where by get set abstract enum open inner override private public internal " + + "protected catch finally out final vararg reified dynamic companion constructor init " + + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + + "external annotation crossinline const operator infix suspend" + ), + types: words( + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + intendSwitch: false, + indentStatements: false, + multiLineStrings: true, + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + blockKeywords: words("catch class do else finally for if where try while enum"), + defKeywords: words("class val var object package interface fun"), + atoms: words("true false null this"), + hooks: { + '"': function(stream, state) { + state.tokenize = tokenKotlinString(stream.match('""')); + return state.tokenize(stream, state); + } + }, + modeProps: {closeBrackets: {triples: '"'}} + }); + + def(["x-shader/x-vertex", "x-shader/x-fragment"], { + name: "clike", + keywords: words("sampler1D sampler2D sampler3D samplerCube " + + "sampler1DShadow sampler2DShadow " + + "const attribute uniform varying " + + "break continue discard return " + + "for while do if else struct " + + "in out inout"), + types: words("float int bool void " + + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + + "mat2 mat3 mat4"), + blockKeywords: words("for while do if else struct"), + builtin: words("radians degrees sin cos tan asin acos atan " + + "pow exp log exp2 sqrt inversesqrt " + + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + + "length distance dot cross normalize ftransform faceforward " + + "reflect refract matrixCompMult " + + "lessThan lessThanEqual greaterThan greaterThanEqual " + + "equal notEqual any all not " + + "texture1D texture1DProj texture1DLod texture1DProjLod " + + "texture2D texture2DProj texture2DLod texture2DProjLod " + + "texture3D texture3DProj texture3DLod texture3DProjLod " + + "textureCube textureCubeLod " + + "shadow1D shadow2D shadow1DProj shadow2DProj " + + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + + "dFdx dFdy fwidth " + + "noise1 noise2 noise3 noise4"), + atoms: words("true false " + + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + + "gl_FogCoord gl_PointCoord " + + "gl_Position gl_PointSize gl_ClipVertex " + + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + + "gl_TexCoord gl_FogFragCoord " + + "gl_FragCoord gl_FrontFacing " + + "gl_FragData gl_FragDepth " + + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + + "gl_ProjectionMatrixInverseTranspose " + + "gl_ModelViewProjectionMatrixInverseTranspose " + + "gl_TextureMatrixInverseTranspose " + + "gl_NormalScale gl_DepthRange gl_ClipPlane " + + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + + "gl_FrontLightModelProduct gl_BackLightModelProduct " + + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + + "gl_FogParameters " + + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + + "gl_MaxDrawBuffers"), + indentSwitch: false, + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-nesc", { + name: "clike", + keywords: words(cKeywords + "as atomic async call command component components configuration event generic " + + "implementation includes interface module new norace nx_struct nx_union post provides " + + "signal task uses abstract extends"), + types: words(cTypes), + blockKeywords: words("case do else for if switch while struct"), + atoms: words("null true false"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-objectivec", { + name: "clike", + keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " + + "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"), + types: words(cTypes), + atoms: words("YES NO NULL NILL ON OFF true false"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$]/); + return "keyword"; + }, + "#": cppHook, + indent: function(_state, ctx, textAfter) { + if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented + } + }, + modeProps: {fold: "brace"} + }); + + def("text/x-squirrel", { + name: "clike", + keywords: words("base break clone continue const default delete enum extends function in class" + + " foreach local resume return this throw typeof yield constructor instanceof static"), + types: words(cTypes), + blockKeywords: words("case catch class else for foreach if switch try while"), + defKeywords: words("function local class"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + // Ceylon Strings need to deal with interpolation + var stringTokenizer = null; + function tokenCeylonString(type) { + return function(stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!escaped && stream.match('"') && + (type == "single" || stream.match('""'))) { + end = true; + break; + } + if (!escaped && stream.match('``')) { + stringTokenizer = tokenCeylonString(type); + end = true; + break; + } + next = stream.next(); + escaped = type == "single" && !escaped && next == "\\"; + } + if (end) + state.tokenize = null; + return "string"; + } + } + + def("text/x-ceylon", { + name: "clike", + keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + + " exists extends finally for function given if import in interface is let module new" + + " nonempty object of out outer package return satisfies super switch then this throw" + + " try value void while"), + types: function(word) { + // In Ceylon all identifiers that start with an uppercase are types + var first = word.charAt(0); + return (first === first.toUpperCase() && first !== first.toLowerCase()); + }, + blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), + defKeywords: words("class dynamic function interface module object package value"), + builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + + " native optional sealed see serializable shared suppressWarnings tagged throws variable"), + isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, + isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, + numberStart: /[\d#$]/, + number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, + multiLineStrings: true, + typeFirstDefinitions: true, + atoms: words("true false null larger smaller equal empty finished"), + indentSwitch: false, + styleDefs: false, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); + return state.tokenize(stream, state); + }, + '`': function(stream, state) { + if (!stringTokenizer || !stream.match('`')) return false; + state.tokenize = stringTokenizer; + stringTokenizer = null; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + token: function(_stream, state, style) { + if ((style == "variable" || style == "variable-3") && + state.prevToken == ".") { + return "variable-2"; + } + } + }, + modeProps: { + fold: ["brace", "import"], + closeBrackets: {triples: '"'} + } + }); + +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../clike/clike")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + // Helper for phpString + function matchSequence(list, end, escapes) { + if (list.length == 0) return phpString(end); + return function (stream, state) { + var patterns = list[0]; + for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) { + state.tokenize = matchSequence(list.slice(1), end); + return patterns[i][1]; + } + state.tokenize = phpString(end, escapes); + return "string"; + }; + } + function phpString(closing, escapes) { + return function(stream, state) { return phpString_(stream, state, closing, escapes); }; + } + function phpString_(stream, state, closing, escapes) { + // "Complex" syntax + if (escapes !== false && stream.match("${", false) || stream.match("{$", false)) { + state.tokenize = null; + return "string"; + } + + // Simple syntax + if (escapes !== false && stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) { + // After the variable name there may appear array or object operator. + if (stream.match("[", false)) { + // Match array operator + state.tokenize = matchSequence([ + [["[", null]], + [[/\d[\w\.]*/, "number"], + [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"], + [/[\w\$]+/, "variable"]], + [["]", null]] + ], closing, escapes); + } + if (stream.match(/\-\>\w/, false)) { + // Match object operator + state.tokenize = matchSequence([ + [["->", null]], + [[/[\w]+/, "variable"]] + ], closing, escapes); + } + return "variable-2"; + } + + var escaped = false; + // Normal string + while (!stream.eol() && + (escaped || escapes === false || + (!stream.match("{$", false) && + !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) { + if (!escaped && stream.match(closing)) { + state.tokenize = null; + state.tokStack.pop(); state.tokStack.pop(); + break; + } + escaped = stream.next() == "\\" && !escaped; + } + return "string"; + } + + var phpKeywords = "abstract and array as break case catch class clone const continue declare default " + + "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " + + "for foreach function global goto if implements interface instanceof namespace " + + "new or private protected public static switch throw trait try use var while xor " + + "die echo empty exit eval include include_once isset list require require_once return " + + "print unset __halt_compiler self static parent yield insteadof finally"; + var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__"; + var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents file_put_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists array_intersect_key array_combine array_column pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count"; + CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" ")); + CodeMirror.registerHelper("wordChars", "php", /[\w$]/); + + var phpConfig = { + name: "clike", + helperType: "php", + keywords: keywords(phpKeywords), + blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"), + defKeywords: keywords("class function interface namespace trait"), + atoms: keywords(phpAtoms), + builtin: keywords(phpBuiltin), + multiLineStrings: true, + hooks: { + "$": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "variable-2"; + }, + "<": function(stream, state) { + var before; + if (before = stream.match(/<<\s*/)) { + var quoted = stream.eat(/['"]/); + stream.eatWhile(/[\w\.]/); + var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1)); + if (quoted) stream.eat(quoted); + if (delim) { + (state.tokStack || (state.tokStack = [])).push(delim, 0); + state.tokenize = phpString(delim, quoted != "'"); + return "string"; + } + } + return false; + }, + "#": function(stream) { + while (!stream.eol() && !stream.match("?>", false)) stream.next(); + return "comment"; + }, + "/": function(stream) { + if (stream.eat("/")) { + while (!stream.eol() && !stream.match("?>", false)) stream.next(); + return "comment"; + } + return false; + }, + '"': function(_stream, state) { + (state.tokStack || (state.tokStack = [])).push('"', 0); + state.tokenize = phpString('"'); + return "string"; + }, + "{": function(_stream, state) { + if (state.tokStack && state.tokStack.length) + state.tokStack[state.tokStack.length - 1]++; + return false; + }, + "}": function(_stream, state) { + if (state.tokStack && state.tokStack.length > 0 && + !--state.tokStack[state.tokStack.length - 1]) { + state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]); + } + return false; + } + } + }; + + CodeMirror.defineMode("php", function(config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, "text/html"); + var phpMode = CodeMirror.getMode(config, phpConfig); + + function dispatch(stream, state) { + var isPHP = state.curMode == phpMode; + if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null; + if (!isPHP) { + if (stream.match(/^<\?\w*/)) { + state.curMode = phpMode; + if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, "")) + state.curState = state.php; + return "meta"; + } + if (state.pending == '"' || state.pending == "'") { + while (!stream.eol() && stream.next() != state.pending) {} + var style = "string"; + } else if (state.pending && stream.pos < state.pending.end) { + stream.pos = state.pending.end; + var style = state.pending.style; + } else { + var style = htmlMode.token(stream, state.curState); + } + if (state.pending) state.pending = null; + var cur = stream.current(), openPHP = cur.search(/<\?/), m; + if (openPHP != -1) { + if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0]; + else state.pending = {end: stream.pos, style: style}; + stream.backUp(cur.length - openPHP); + } + return style; + } else if (isPHP && state.php.tokenize == null && stream.match("?>")) { + state.curMode = htmlMode; + state.curState = state.html; + if (!state.php.context.prev) state.php = null; + return "meta"; + } else { + return phpMode.token(stream, state.curState); + } + } + + return { + startState: function() { + var html = CodeMirror.startState(htmlMode) + var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null + return {html: html, + php: php, + curMode: parserConfig.startOpen ? phpMode : htmlMode, + curState: parserConfig.startOpen ? php : html, + pending: null}; + }, + + copyState: function(state) { + var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html), + php = state.php, phpNew = php && CodeMirror.copyState(phpMode, php), cur; + if (state.curMode == htmlMode) cur = htmlNew; + else cur = phpNew; + return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, + pending: state.pending}; + }, + + token: dispatch, + + indent: function(state, textAfter) { + if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) || + (state.curMode == phpMode && /^\?>/.test(textAfter))) + return htmlMode.indent(state.html, textAfter); + return state.curMode.indent(state.curState, textAfter); + }, + + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//", + + innerMode: function(state) { return {state: state.curState, mode: state.curMode}; } + }; + }, "htmlmixed", "clike"); + + CodeMirror.defineMIME("application/x-httpd-php", "php"); + CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true}); + CodeMirror.defineMIME("text/x-php", phpConfig); +}); + +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("sql", function(config, parserConfig) { + "use strict"; + + var client = parserConfig.client || {}, + atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, + builtin = parserConfig.builtin || {}, + keywords = parserConfig.keywords || {}, + operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, + support = parserConfig.support || {}, + hooks = parserConfig.hooks || {}, + dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}; + + function tokenBase(stream, state) { + var ch = stream.next(); + + // call hooks from the mime type + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + + if (support.hexNumber && + ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) + || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { + // hex + // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html + return "number"; + } else if (support.binaryNumber && + (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) + || (ch == "0" && stream.match(/^b[01]+/)))) { + // bitstring + // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html + stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/); + support.decimallessFloat && stream.eat('.'); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { + // strings + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if ((((support.nCharCast && (ch == "n" || ch == "N")) + || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) + && (stream.peek() == "'" || stream.peek() == '"'))) { + // charset casting: _utf8'str', N'str', n'str' + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + return "keyword"; + } else if (/^[\(\),\;\[\]]/.test(ch)) { + // no highlighting + return null; + } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { + // 1-line comment + stream.skipToEnd(); + return "comment"; + } else if ((support.commentHash && ch == "#") + || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { + // 1-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + // multi-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } else if (ch == ".") { + // .1 for 0.1 + if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) { + return "number"; + } + // .table_name (ODBC) + // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + if (support.ODBCdotTable && stream.match(/^[a-zA-Z_]+/)) { + return "variable-2"; + } + } else if (operatorChars.test(ch)) { + // operators + stream.eatWhile(operatorChars); + return null; + } else if (ch == '{' && + (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { + // dates (weird ODBC syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + return "number"; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + // dates (standard SQL syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) + return "number"; + if (atoms.hasOwnProperty(word)) return "atom"; + if (builtin.hasOwnProperty(word)) return "builtin"; + if (keywords.hasOwnProperty(word)) return "keyword"; + if (client.hasOwnProperty(word)) return "string-2"; + return null; + } + } + + // 'string', with char specified in quote escaped by '\' + function tokenLiteral(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && ch == "\\"; + } + return "string"; + }; + } + function tokenComment(stream, state) { + while (true) { + if (stream.skipTo("*")) { + stream.next(); + if (stream.eat("/")) { + state.tokenize = tokenBase; + break; + } + } else { + stream.skipToEnd(); + break; + } + } + return "comment"; + } + + function pushContext(stream, state, type) { + state.context = { + prev: state.context, + indent: stream.indentation(), + col: stream.column(), + type: type + }; + } + + function popContext(state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } + + return { + startState: function() { + return {tokenize: tokenBase, context: null}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) + state.context.align = false; + } + if (stream.eatSpace()) return null; + + var style = state.tokenize(stream, state); + if (style == "comment") return style; + + if (state.context && state.context.align == null) + state.context.align = true; + + var tok = stream.current(); + if (tok == "(") + pushContext(stream, state, ")"); + else if (tok == "[") + pushContext(stream, state, "]"); + else if (state.context && state.context.type == tok) + popContext(state); + return style; + }, + + indent: function(state, textAfter) { + var cx = state.context; + if (!cx) return CodeMirror.Pass; + var closing = textAfter.charAt(0) == cx.type; + if (cx.align) return cx.col + (closing ? 0 : 1); + else return cx.indent + (closing ? 0 : config.indentUnit); + }, + + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : null + }; +}); + +(function() { + "use strict"; + + // `identifier` + function hookIdentifier(stream) { + // MySQL/MariaDB identifiers + // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "`" && !stream.eat("`")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // "identifier" + function hookIdentifierDoublequote(stream) { + // Standard SQL /SQLite identifiers + // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier + // ref: http://sqlite.org/lang_keywords.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "\"" && !stream.eat("\"")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // variable token + function hookVar(stream) { + // variables + // @@prefix.varName @varName + // varName can be quoted with ` or ' or " + // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html + if (stream.eat("@")) { + stream.match(/^session\./); + stream.match(/^local\./); + stream.match(/^global\./); + } + + if (stream.eat("'")) { + stream.match(/^.*'/); + return "variable-2"; + } else if (stream.eat('"')) { + stream.match(/^.*"/); + return "variable-2"; + } else if (stream.eat("`")) { + stream.match(/^.*`/); + return "variable-2"; + } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { + return "variable-2"; + } + return null; + }; + + // short client keyword token + function hookClient(stream) { + // \N means NULL + // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html + if (stream.eat("N")) { + return "atom"; + } + // \g, etc + // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html + return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; + } + + // these keywords are used by all SQL dialects (however, a mode can still overwrite it) + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; + + // turn a space-separated list into an array + function set(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + // A generic SQL Mode. It's not a standard, it just try to support what is generally supported + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") + }); + + CodeMirror.defineMIME("text/x-mssql", { + name: "sql", + client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), + keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec"), + builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"), + hooks: { + "@": hookVar + } + }); + + CodeMirror.defineMIME("text/x-mysql", { + name: "sql", + client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), + keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), + builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=&|^]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), + hooks: { + "@": hookVar, + "`": hookIdentifier, + "\\": hookClient + } + }); + + CodeMirror.defineMIME("text/x-mariadb", { + name: "sql", + client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), + keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"), + builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=&|^]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), + hooks: { + "@": hookVar, + "`": hookIdentifier, + "\\": hookClient + } + }); + + // provided by the phpLiteAdmin project - phpliteadmin.org + CodeMirror.defineMIME("text/x-sqlite", { + name: "sql", + // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd + client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"), + // ref: http://sqlite.org/lang_keywords.html + keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"), + // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. + builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"), + // ref: http://sqlite.org/syntax/literal-value.html + atoms: set("null current_date current_time current_timestamp"), + // ref: http://sqlite.org/lang_expr.html#binaryops + operatorChars: /^[*+\-%<>!=&|/~]/, + // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. + dateSQL: set("date time timestamp datetime"), + support: set("decimallessFloat zerolessFloat"), + identifierQuote: "\"", //ref: http://sqlite.org/lang_keywords.html + hooks: { + // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam + "@": hookVar, + ":": hookVar, + "?": hookVar, + "$": hookVar, + // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html + "\"": hookIdentifierDoublequote, + // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html + "`": hookIdentifier + } + }); + + // the query language used by Apache Cassandra is called CQL, but this mime type + // is called Cassandra to avoid confusion with Contextual Query Language + CodeMirror.defineMIME("text/x-cassandra", { + name: "sql", + client: { }, + keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"), + builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"), + atoms: set("false true infinity NaN"), + operatorChars: /^[<>=]/, + dateSQL: { }, + support: set("commentSlashSlash decimallessFloat"), + hooks: { } + }); + + // this is based on Peter Raganitsch's 'plsql' mode + CodeMirror.defineMIME("text/x-plsql", { + name: "sql", + client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"), + keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"), + builtin: set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"), + operatorChars: /^[*+\-%<>!=~]/, + dateSQL: set("date time timestamp"), + support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber") + }); + + // Created to support specific hive keywords + CodeMirror.defineMIME("text/x-hive", { + name: "sql", + keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"), + builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") + }); + + CodeMirror.defineMIME("text/x-pgsql", { + name: "sql", + client: set("source"), + // http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html + keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat"), + // http://www.postgresql.org/docs/9.5/static/datatype.html + builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") + }); + + // Google's SQL-like query language, GQL + CodeMirror.defineMIME("text/x-gql", { + name: "sql", + keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"), + atoms: set("false true"), + builtin: set("blob datetime first key __key__ string integer double boolean null"), + operatorChars: /^[*+\-%<>!=]/ + }); +}()); + +}); + +/* + How Properties of Mime Types are used by SQL Mode + ================================================= + + keywords: + A list of keywords you want to be highlighted. + builtin: + A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword"). + operatorChars: + All characters that must be handled as operators. + client: + Commands parsed and executed by the client (not the server). + support: + A list of supported syntaxes which are not common, but are supported by more than 1 DBMS. + * ODBCdotTable: .tableName + * zerolessFloat: .1 + * doubleQuote + * nCharCast: N'string' + * charsetCast: _utf8'string' + * commentHash: use # char for comments + * commentSlashSlash: use // for comments + * commentSpaceRequired: require a space after -- for comments + atoms: + Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others: + UNKNOWN, INFINITY, UNDERFLOW, NaN... + dateSQL: + Used for date/time SQL standard syntax, because not all DBMS's support same temporal types. +*/ + diff --git a/workflow/public_html/lib/js/modernizr.js b/workflow/public_html/lib/js/modernizr.js new file mode 100644 index 000000000..2a6e0e42a --- /dev/null +++ b/workflow/public_html/lib/js/modernizr.js @@ -0,0 +1,4 @@ +/* Modernizr 2.7.1 (Custom Build) | MIT & BSD + * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-flexboxlegacy-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-cssclasses-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load + */ +;window.Modernizr=function(a,b,c){function C(a){j.cssText=a}function D(a,b){return C(n.join(a+";")+(b||""))}function E(a,b){return typeof a===b}function F(a,b){return!!~(""+a).indexOf(b)}function G(a,b){for(var d in a){var e=a[d];if(!F(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function H(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:E(f,"function")?f.bind(d||b):f}return!1}function I(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return E(b,"string")||E(b,"undefined")?G(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),H(e,b,c))}function J(){e.input=function(c){for(var d=0,e=c.length;d',a,""].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=E(e[d],"function"),E(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),A={}.hasOwnProperty,B;!E(A,"undefined")&&!E(A.call,"undefined")?B=function(a,b){return A.call(a,b)}:B=function(a,b){return b in a&&E(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return I("flexWrap")},s.flexboxlegacy=function(){return I("boxDirection")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!E(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!I("indexedDB",a)},s.hashchange=function(){return z("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return C("background-color:rgba(150,255,150,.5)"),F(j.backgroundColor,"rgba")},s.hsla=function(){return C("background-color:hsla(120,40%,100%,.5)"),F(j.backgroundColor,"rgba")||F(j.backgroundColor,"hsla")},s.multiplebgs=function(){return C("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return I("backgroundSize")},s.borderimage=function(){return I("borderImage")},s.borderradius=function(){return I("borderRadius")},s.boxshadow=function(){return I("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return D("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return I("animationName")},s.csscolumns=function(){return I("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return C((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),F(j.backgroundImage,"gradient")},s.cssreflections=function(){return I("boxReflect")},s.csstransforms=function(){return!!I("transform")},s.csstransforms3d=function(){var a=!!I("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return I("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var K in s)B(s,K)&&(x=K.toLowerCase(),e[x]=s[K](),v.push((e[x]?"":"no-")+x));return e.input||J(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)B(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},C(""),i=k=null,function(a,b){function l(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.hasEvent=z,e.testProp=function(a){return G([a])},e.testAllProps=I,e.testStyles=y,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f>2,i=(3&t)<<4|r>>4,n=(15&r)<<2|s>>6,a=63&s,isNaN(r)?n=a=64:isNaN(s)&&(a=64),h=h+this.keyStr.charAt(o)+this.keyStr.charAt(i)+this.keyStr.charAt(n)+this.keyStr.charAt(a);return h},decode:function(e){var t,r,s,o,i,n,a,h="",c=0;for(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");c>4,r=(15&i)<<4|n>>2,s=(3&n)<<6|a,h+=String.fromCharCode(t),64!==n&&(h+=String.fromCharCode(r)),64!==a&&(h+=String.fromCharCode(s));return h=this.utf8_decode(h)},utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t,r,s="";for(t=0;tr?s+=String.fromCharCode(r):r>127&&2048>r?(s+=String.fromCharCode(r>>6|192),s+=String.fromCharCode(63&r|128)):(s+=String.fromCharCode(r>>12|224),s+=String.fromCharCode(r>>6&63|128),s+=String.fromCharCode(63&r|128));return s},utf8_decode:function(e){for(var t="",r=0,s=0,o=0,i=0;rs?(t+=String.fromCharCode(s),r++):s>191&&224>s?(o=e.charCodeAt(r+1),t+=String.fromCharCode((31&s)<<6|63&o),r+=2):(o=e.charCodeAt(r+1),i=e.charCodeAt(r+2),t+=String.fromCharCode((15&s)<<12|(63&o)<<6|63&i),r+=3);return t}},RestClient;if(RestClient=function(){this.VERSION="0.1.9\n",this.authorization={},this.server={},this.response={},this.headers={},this.accessToken={},this.autoUseRefreshToken=!0,this.autoStoreAccessToken=!0,this.authorizationType="none",this.contentType="application/json",this.sendOAuthBearerAuthorization=!1,this.dataType="json",this.oauth2NeedsAuthorization=!0,this.expiredAccessTokenMessage="",this.restfulBehavior=!0,this.backupAJAXURL=null,this.acceptType=null,this.RESTMethods={create:"POST",read:"GET",update:"PUT","delete":"DELETE"},this.OAUTH2GrantTypes={code:"authorization_code",implicit:"token",user:"password",client:"client_credentials",refresh:"refresh_token"},RestClient.prototype.initObject.call(this)},RestClient.prototype.HTTP_SUCCESS=["200","201","202","204","207"],RestClient.prototype.HTTP_BAD_REQUEST=400,RestClient.prototype.HTTP_UNAUTHORIZED=401,RestClient.prototype.OAUTH2_INVALID_GRANT="invalid_grant",RestClient.prototype.initObject=function(){this.authorization={},this.server={},this.response={},this.headers={},this.accessToken={},this.autoUseRefreshToken=!0,this.autoStoreAccessToken=!0,this.authorizationType="none",this.contentType="application/json",this.acceptType="application/json",this.sendOAuthBearerAuthorization=!1,this.oauth2NeedsAuthorization=!0,this.dataType="json",this.expiredAccessTokenMessage="The access token provided has expired."},RestClient.prototype.setUseRefreshTokenAutomatically=function(e){return _.isBoolean(e)&&(this.autoUseRefreshToken=e),this},RestClient.prototype.setStoreAccessTokenAutomatically=function(e){return _.isBoolean(e)&&(this.autoStoreAccessToken=e),this},RestClient.prototype.setAuthorizationType=function(e){var t={none:1,basic:1,oauth2:1};return t[e]&&(this.authorizationType=e),this},RestClient.prototype.setContentType=function(e){return this.contentType=e,this},RestClient.prototype.setAcceptType=function(e){var t={plain:"text/plain",xhtml_xml:"application/xhtml+xml",json:"application/json",xml:"application/xml",all:"*/*"};return t[e]&&(this.acceptType=t[e]),this},RestClient.prototype.setSendBearerAuthorization=function(e){return _.isBoolean(e)&&(this.sendOAuthBearerAuthorization=e),this},RestClient.prototype.setOAuth2NeedsAuthorization=function(e){return _.isBoolean(e)&&(this.oauth2NeedsAuthorization=e),this},RestClient.prototype.setDataType=function(e){var t={json:"application/json",plain:"text/plain",form:"application/x-www-form-urlencoded",html:"text/html"};return t[e]&&(this.dataType=e,this.contentType=t[e]),this},RestClient.prototype.setAccessTokenExpiredMessage=function(e){return this.expiredAccessTokenMessage=e,this},RestClient.prototype.getVersion=function(){return this.VERSION},RestClient.prototype.setClient=function(e,t,r){return this.authorization.client_id=e,this.authorization.client_secret=t,this.authorization.client_url="undefined"!==r?r:null,this},RestClient.prototype.setGrantType=function(e,t){return this.authorization.grant_type="undefined"!==this.OAUTH2GrantTypes[e]?this.OAUTH2GrantTypes[e]:null,this.authorization=_.extend(this.authorization,t),this},RestClient.prototype.setAuthorizationServer=function(e){var t,r=!0;return"undefined"==typeof e||null===e?r=!1:(t=/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/,e.match(t)?this.server.rest_auth_uri=e:r=!1),r},RestClient.prototype.setHeader=function(e,t){var r,s=!0;return e&&t?(r=JSON.parse('{"'+e+'" : "'+t+'"}'),this.headers=_.extend(this.headers,r)):s=!1,s},RestClient.prototype.JSONParse=function(e){var t;try{t=e?""===e?"":JSON.parse(e):""}catch(r){t="ERROR_PARSE"}return t},RestClient.prototype.setBasicCredentials=function(e,t){return this.authorization.basic_user=e,this.authorization.basic_password=t,this},RestClient.prototype.setAccessToken=function(e){return"object"==typeof e&&(this.accessToken=e),this},RestClient.prototype.setRestfulBehavior=function(e){return _.isBoolean(e)&&(this.restfulBehavior=e),this},RestClient.prototype.setBackupAjaxUrl=function(e){return this.backupAJAXURL=e,this},RestClient.prototype.toParams=function(e){var t=_.keys(e),r=[];return _.each(t,function(t){r.push(t+"="+e[t])}),r.join("&")},RestClient.prototype.prepareBody=function(e){var t="";return"json"===this.dataType||"jsonp"===this.dataType?"object"==typeof e&&(t=JSON.stringify(e)):t=this.toParams(e),t},RestClient.prototype.createXHR=function(){var e;if(window.XMLHttpRequest)e=new XMLHttpRequest;else try{e=new ActiveXObject("MSXML2.XMLHTTP")}catch(t){try{e=new ActiveXObject("Microsoft.XMLHTTP")}catch(r){}}return e?e:!1},RestClient.prototype.authorize=function(e){var t,r,s,o,i=this,n=!1,a="create",h=this.RESTMethods[a];t=RCBase64.encode(this.authorization.client_id+":"+this.authorization.client_secret),r=this.createXHR();try{r.open(h,this.server.rest_auth_uri,!1)}catch(c){return e.xhrfailure?e.xhrfailure(c,{}):this.XHRFailure(c,{}),n}if(r.onreadystatechange=function(){if(e.ready?e.ready(r):i.AuthorizeReady(r),4===r.readyState){if(o=i.JSONParse(r.responseText),-1!=i.HTTP_SUCCESS.indexOf(String(r.status))&&"ERROR_PARSE"!==o)if(i.autoStoreAccessToken&&(i.accessToken=o.token||{}),n=!0,e.success)try{e.success(r,o)}catch(t){throw new Error(t.message)}else i.AuthorizeSuccess(r,o);else if("ERROR_PARSE"===o&&(o={success:!1,error:{error:i.HTTP_BAD_REQUEST,error_description:"Response is not a valid JSON"}}),e.failure)try{e.failure(r,o)}catch(t){throw new Error(t.message)}else i.AuthorizeFailure(r,o);"function"==typeof e.complete&&e.complete(r,o)}},s={},this.authorization.grant_type)switch(s.grant_type=this.authorization.grant_type,this.authorization.grant_type){case"authorization_code":s.code=this.authorization.code;break;case"token":s.token=this.authorization.token;break;case"password":s.username=this.authorization.username,s.password=this.authorization.password;break;case"client_credentials":s.client_id=this.authorization.client_id,s.client_id=this.authorization.client_secret;break;case"refresh_token":s.refresh_token=this.authorization.refresh_token}return this.oauth2NeedsAuthorization&&r.setRequestHeader("Authorization","Basic "+t),r.setRequestHeader("Accept",this.acceptType),r.setRequestHeader("Content-Type",this.contentType),_.each(this.headers,function(e,t){r.setRequestHeader(t,e)}),r.send(this.prepareBody(s)),n},RestClient.prototype.prepareReqFields=function(e){var t;return t={success:!1,error:{error:this.HTTP_BAD_REQUEST,error_description:"Required fields not found"},fields:e}},RestClient.prototype.prepareConsumeUrl=function(e,t,r,s){var o,i,n=this.acceptType,a=this.contentType,h=!1;if(this.restfulBehavior)switch(e){case"read":o=t,r&&(o+=r),"oauth2"!==this.authorizationType||this.sendOAuthBearerAuthorization||(h=!0,o+="?access_token="+this.accessToken.access_token),s&&s!=={}&&(o+=h?"&":"?",o+=this.toParams(s)),i=null,null===a&&(a="application/json");break;case"create":o=t,i=s||{},"oauth2"!==this.authorizationType||this.sendOAuthBearerAuthorization||(i.access_token=this.accessToken.access_token),i=this.prepareBody(i);break;case"update":o=t,r&&(o+=r),i=s||{},"oauth2"!==this.authorizationType||this.sendOAuthBearerAuthorization||(i.access_token=this.accessToken.access_token),i=this.prepareBody(i);break;case"delete":o=t,r&&(o+=r),i=s||{},"oauth2"!==this.authorizationType||this.sendOAuthBearerAuthorization||(i.access_token=this.accessToken.access_token),i=this.prepareBody(i)}else o=this.backupAJAXURL,i={operation:e,url:t,id:r,data:s},i="data='"+encodeURIComponent(JSON.stringify(i))+"'",null===a&&(a="application/json");return n||(n="*/*"),{url:o,body:i,content_type:a,acceptType:n}},RestClient.prototype.getCall=function(e){return e.operation="read",this.consume(e)},RestClient.prototype.postCall=function(e){return e.operation="create",this.consume(e)},RestClient.prototype.putCall=function(e){return e.operation="update",this.consume(e)},RestClient.prototype.deleteCall=function(e){return e.operation="delete",this.consume(e)},RestClient.prototype.consume=function(e){var t,r,s,o,i,n,a,h,c,u,p,l,d,f,y,R={},T=!0,C=[],A=!1;if(e.operation?s=e.operation:(T=!1,C.push("operation")),e.url?c=e.url:(T=!1,C.push("url")),u=e.data||null,p=e.id||null,!T)return e.failure?e.failure(null,this.prepareReqFields(C)):this.ConsumeFailure(null,this.prepareReqFields(C)),T;l=this.prepareConsumeUrl(s,c,p,u),n=l.url,i=l.body,f=l.content_type,y=l.acceptType,r=this.createXHR(),o=this.restfulBehavior?this.RESTMethods[s]:this.RESTMethods.create;try{switch(r.open(o,n,!1),this.authorizationType){case"none":break;case"basic":t=RCBase64.encode(this.authorization.basic_user+":"+this.authorization.basic_password),r.setRequestHeader("Authorization","Basic "+t);break;case"oauth2":if(!this.accessToken.access_token)return T=!1,C.push("access_token"),h={success:!1,error:{error:this.HTTP_BAD_REQUEST,error_description:"Access Token not defined"}},e.failure?e.failure(null,this.prepareReqFields(C)):this.ConsumeFailure(null,this.prepareReqFields(C)),T;this.sendOAuthBearerAuthorization&&(d="Bearer "+this.accessToken.access_token,r.setRequestHeader("Authorization",d))}}catch(k){return e.xhrfailure?e.xhrfailure(k,u):this.XHRFailure(k,u),!1}return a=this,r.onreadystatechange=function(){if(e.ready?e.ready(r):a.ConsumeReady(r),4===r.readyState){if(R=a.JSONParse(r.responseText),-1!=a.HTTP_SUCCESS.indexOf(String(r.status))&&"ERROR_PARSE"!==R)if(a.autoStoreAccessToken&&(a.accessToken=R.token||{}),T=!0,e.success)try{e.success(r,R)}catch(t){throw new Error(t.message)}else a.AuthorizeSuccess(r,R);else if(T=!1,"ERROR_PARSE"===R?R={success:!1,error:{error:a.HTTP_BAD_REQUEST,error_description:"Response is not a valid JSON"}}:(R.error===a.OAUTH2_INVALID_GRANT&&R.error_description===a.expiredAccessTokenMessage&&(A=!0),r.status===a.HTTP_UNAUTHORIZED&&a.autoUseRefreshToken&&A&&(a.accessToken.refresh_token?(a.setGrantType("refresh",{refresh_token:a.accessToken.refresh_token}),a.authorize({success:function(){T=a.consume(e),T&&(e.autorefresh?e.autorefresh(a.accessToken):a.AuthorizeAutoRefresh(a.accessToken))},failure:function(t,r){T=!1,e.failure?e.failure(null,r):a.ConsumeFailure(null,r)}})):(T=!1,R={success:!1,error:{error:a.HTTP_UNAUTHORIZED,error_description:"Refresh token is not defined"}}))),e.failure)try{e.failure(r,R)}catch(t){throw new Error(t.message)}else a.AuthorizeFailure(r,R);"function"==typeof e.complete&&e.complete(r,R)}},r.setRequestHeader("Accept",y),r.setRequestHeader("Content-Type",f),_.each(this.headers,function(e,t){r.setRequestHeader(t,e)}),r.send(i),T},RestClient.prototype.XHRFailure=function(){},RestClient.prototype.AuthorizeSuccess=function(){},RestClient.prototype.AuthorizeFailure=function(){},RestClient.prototype.AuthorizeReady=function(){},RestClient.prototype.AuthorizeAutoRefresh=function(){},RestClient.prototype.ConsumeSuccess=function(){},RestClient.prototype.ConsumeFailure=function(){},RestClient.prototype.ConsumeReady=function(){},"undefined"!=typeof exports){module.exports={RestClient:RestClient,RCBase64:RCBase64};var _=require("underscore")} \ No newline at end of file diff --git a/workflow/public_html/lib/js/underscore-min.js b/workflow/public_html/lib/js/underscore-min.js new file mode 100644 index 000000000..f8728b3f2 --- /dev/null +++ b/workflow/public_html/lib/js/underscore-min.js @@ -0,0 +1,5 @@ +// Underscore.js 1.5.2 +// http://underscorejs.org +// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?(this._wrapped=n,void 0):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.5.2";var A=j.each=j.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var E="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(E);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(E);return r},j.find=j.detect=function(n,t,r){var e;return O(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var O=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:O(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,function(n){return n[t]})},j.where=function(n,t,r){return j.isEmpty(t)?r?void 0:[]:j[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},j.findWhere=function(n,t){return j.where(n,t,!0)},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);if(!t&&j.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>e.computed&&(e={value:n,computed:a})}),e.value},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);if(!t&&j.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;ae||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={},i=null==r?j.identity:k(r);return A(t,function(r,a){var o=i.call(e,r,a,t);n(u,o,r)}),u}};j.groupBy=F(function(n,t,r){(j.has(n,t)?n[t]:n[t]=[]).push(r)}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=null==r?j.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])=0})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:new Date,a=null,i=n.apply(e,u)};return function(){var l=new Date;o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u)):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o;return function(){i=this,u=arguments,a=new Date;var c=function(){var l=new Date-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u)))},l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u)),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=w||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var I={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};I.unescape=j.invert(I.escape);var T={escape:new RegExp("["+j.keys(I.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(I.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(T[n],function(t){return I[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); diff --git a/workflow/public_html/lib/js/wz_jsgraphics.js b/workflow/public_html/lib/js/wz_jsgraphics.js new file mode 100644 index 000000000..1f9a7b9f4 --- /dev/null +++ b/workflow/public_html/lib/js/wz_jsgraphics.js @@ -0,0 +1,1108 @@ +/* This notice must be untouched at all times. + +wz_jsgraphics.js v. 3.05 +The latest version is available at +http://www.walterzorn.com +or http://www.devira.com +or http://www.walterzorn.de + +Copyright (c) 2002-2009 Walter Zorn. All rights reserved. +Created 3. 11. 2002 by Walter Zorn (Web: http://www.walterzorn.com ) +Last modified: 2. 2. 2009 + +Performance optimizations for Internet Explorer +by Thomas Frank and John Holdsworth. +fillPolygon method implemented by Matthieu Haller. + +High Performance JavaScript Graphics Library. +Provides methods +- to draw lines, rectangles, ellipses, polygons + with specifiable line thickness, +- to fill rectangles, polygons, ellipses and arcs +- to draw text. +NOTE: Operations, functions and branching have rather been optimized +to efficiency and speed than to shortness of source code. + +LICENSE: LGPL + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License (LGPL) as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, +or see http://www.gnu.org/copyleft/lesser.html +*/ + + +var jg_ok, jg_ie, jg_fast, jg_dom, jg_moz; + + +function _chkDHTM(wnd, x, i) +// Under XUL, owner of 'document' must be specified explicitly +{ + x = wnd.document.body || null; + jg_ie = x && typeof x.insertAdjacentHTML != "undefined" && wnd.document.createElement; + jg_dom = (x && !jg_ie && + typeof x.appendChild != "undefined" && + typeof wnd.document.createRange != "undefined" && + typeof (i = wnd.document.createRange()).setStartBefore != "undefined" && + typeof i.createContextualFragment != "undefined"); + jg_fast = jg_ie && wnd.document.all && !wnd.opera; + jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined"; + jg_ok = !!(jg_ie || jg_dom); +} + +function _pntCnvDom() +{ + var x = this.wnd.document.createRange(); + x.setStartBefore(this.cnv); + x = x.createContextualFragment(jg_fast? this._htmRpc() : this.htm); + if(this.cnv) this.cnv.appendChild(x); + this.htm = ""; +} + +function _pntCnvIe() +{ + if(this.cnv) this.cnv.insertAdjacentHTML("BeforeEnd", jg_fast? this._htmRpc() : this.htm); + this.htm = ""; +} + +function _pntDoc() +{ + this.wnd.document.write(jg_fast? this._htmRpc() : this.htm); + this.htm = ''; +} + +function _pntN() +{ + ; +} + +function _mkDiv(x, y, w, h) +{ + this.htm += '

<\/div>'; +} + +function _mkDivIe(x, y, w, h) +{ + this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';'; +} + +function _mkDivPrt(x, y, w, h) +{ + this.htm += '
<\/div>'; +} + +var _regex = /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g; +function _htmRpc() +{ + return this.htm.replace( + _regex, + '
\n'); +} + +function _htmPrtRpc() +{ + return this.htm.replace( + _regex, + '
\n'); +} + +function _mkLin(x1, y1, x2, y2) +{ + if(x1 > x2) + { + var _x2 = x2; + var _y2 = y2; + x2 = x1; + y2 = y1; + x1 = _x2; + y1 = _y2; + } + var dx = x2-x1, dy = Math.abs(y2-y1), + x = x1, y = y1, + yIncr = (y1 > y2)? -1 : 1; + + if(dx >= dy) + { + var pr = dy<<1, + pru = pr - (dx<<1), + p = pr-dx, + ox = x; + while(dx > 0) + {--dx; + ++x; + if(p > 0) + { + this._mkDiv(ox, y, x-ox, 1); + y += yIncr; + p += pru; + ox = x; + } + else p += pr; + } + this._mkDiv(ox, y, x2-ox+1, 1); + } + + else + { + var pr = dx<<1, + pru = pr - (dy<<1), + p = pr-dy, + oy = y; + if(y2 <= y1) + { + while(dy > 0) + {--dy; + if(p > 0) + { + this._mkDiv(x++, y, 1, oy-y+1); + y += yIncr; + p += pru; + oy = y; + } + else + { + y += yIncr; + p += pr; + } + } + this._mkDiv(x2, y2, 1, oy-y2+1); + } + else + { + while(dy > 0) + {--dy; + y += yIncr; + if(p > 0) + { + this._mkDiv(x++, oy, 1, y-oy); + p += pru; + oy = y; + } + else p += pr; + } + this._mkDiv(x2, oy, 1, y2-oy+1); + } + } +} + +function _mkLin2D(x1, y1, x2, y2) +{ + if(x1 > x2) + { + var _x2 = x2; + var _y2 = y2; + x2 = x1; + y2 = y1; + x1 = _x2; + y1 = _y2; + } + var dx = x2-x1, dy = Math.abs(y2-y1), + x = x1, y = y1, + yIncr = (y1 > y2)? -1 : 1; + + var s = this.stroke; + if(dx >= dy) + { + if(dx > 0 && s-3 > 0) + { + var _s = (s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy) / dx; + _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1; + } + else var _s = s; + var ad = Math.ceil(s/2); + + var pr = dy<<1, + pru = pr - (dx<<1), + p = pr-dx, + ox = x; + while(dx > 0) + {--dx; + ++x; + if(p > 0) + { + this._mkDiv(ox, y, x-ox+ad, _s); + y += yIncr; + p += pru; + ox = x; + } + else p += pr; + } + this._mkDiv(ox, y, x2-ox+ad+1, _s); + } + + else + { + if(s-3 > 0) + { + var _s = (s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy) / dy; + _s = (!(s-4)? Math.ceil(_s) : Math.round(_s)) + 1; + } + else var _s = s; + var ad = Math.round(s/2); + + var pr = dx<<1, + pru = pr - (dy<<1), + p = pr-dy, + oy = y; + if(y2 <= y1) + { + ++ad; + while(dy > 0) + {--dy; + if(p > 0) + { + this._mkDiv(x++, y, _s, oy-y+ad); + y += yIncr; + p += pru; + oy = y; + } + else + { + y += yIncr; + p += pr; + } + } + this._mkDiv(x2, y2, _s, oy-y2+ad); + } + else + { + while(dy > 0) + {--dy; + y += yIncr; + if(p > 0) + { + this._mkDiv(x++, oy, _s, y-oy+ad); + p += pru; + oy = y; + } + else p += pr; + } + this._mkDiv(x2, oy, _s, y2-oy+ad+1); + } + } +} + +function _mkLinDott(x1, y1, x2, y2) +{ + if(x1 > x2) + { + var _x2 = x2; + var _y2 = y2; + x2 = x1; + y2 = y1; + x1 = _x2; + y1 = _y2; + } + var dx = x2-x1, dy = Math.abs(y2-y1), + x = x1, y = y1, + yIncr = (y1 > y2)? -1 : 1, + drw = true; + if(dx >= dy) + { + var pr = dy<<1, + pru = pr - (dx<<1), + p = pr-dx; + while(dx > 0) + {--dx; + if(drw) this._mkDiv(x, y, 1, 1); + drw = !drw; + if(p > 0) + { + y += yIncr; + p += pru; + } + else p += pr; + ++x; + } + } + else + { + var pr = dx<<1, + pru = pr - (dy<<1), + p = pr-dy; + while(dy > 0) + {--dy; + if(drw) this._mkDiv(x, y, 1, 1); + drw = !drw; + y += yIncr; + if(p > 0) + { + ++x; + p += pru; + } + else p += pr; + } + } + if(drw) this._mkDiv(x, y, 1, 1); +} + +function _mkOv(left, top, width, height) +{ + var a = (++width)>>1, b = (++height)>>1, + wod = width&1, hod = height&1, + cx = left+a, cy = top+b, + x = 0, y = b, + ox = 0, oy = b, + aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1, + st = (aa2>>1)*(1-(b<<1)) + bb2, + tt = (bb2>>1) - aa2*((b<<1)-1), + w, h; + while(y > 0) + { + if(st < 0) + { + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) + { + st += bb2*((x<<1)+3) - aa4*(y-1); + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + w = x-ox; + h = oy-y; + if((w&2) && (h&2)) + { + this._mkOvQds(cx, cy, x-2, y+2, 1, 1, wod, hod); + this._mkOvQds(cx, cy, x-1, y+1, 1, 1, wod, hod); + } + else this._mkOvQds(cx, cy, x-1, oy, w, h, wod, hod); + ox = x; + oy = y; + } + else + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + } + } + w = a-ox+1; + h = (oy<<1)+hod; + y = cy-oy; + this._mkDiv(cx-a, y, w, h); + this._mkDiv(cx+ox+wod-1, y, w, h); +} + +function _mkOv2D(left, top, width, height) +{ + var s = this.stroke; + width += s+1; + height += s+1; + var a = width>>1, b = height>>1, + wod = width&1, hod = height&1, + cx = left+a, cy = top+b, + x = 0, y = b, + aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1, + st = (aa2>>1)*(1-(b<<1)) + bb2, + tt = (bb2>>1) - aa2*((b<<1)-1); + + if(s-4 < 0 && (!(s-2) || width-51 > 0 && height-51 > 0)) + { + var ox = 0, oy = b, + w, h, + pxw; + while(y > 0) + { + if(st < 0) + { + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) + { + st += bb2*((x<<1)+3) - aa4*(y-1); + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + w = x-ox; + h = oy-y; + + if(w-1) + { + pxw = w+1+(s&1); + h = s; + } + else if(h-1) + { + pxw = s; + h += 1+(s&1); + } + else pxw = h = s; + this._mkOvQds(cx, cy, x-1, oy, pxw, h, wod, hod); + ox = x; + oy = y; + } + else + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + } + } + this._mkDiv(cx-a, cy-oy, s, (oy<<1)+hod); + this._mkDiv(cx+a+wod-s, cy-oy, s, (oy<<1)+hod); + } + + else + { + var _a = (width-(s<<1))>>1, + _b = (height-(s<<1))>>1, + _x = 0, _y = _b, + _aa2 = (_a*_a)<<1, _aa4 = _aa2<<1, _bb2 = (_b*_b)<<1, _bb4 = _bb2<<1, + _st = (_aa2>>1)*(1-(_b<<1)) + _bb2, + _tt = (_bb2>>1) - _aa2*((_b<<1)-1), + + pxl = new Array(), + pxt = new Array(), + _pxb = new Array(); + pxl[0] = 0; + pxt[0] = b; + _pxb[0] = _b-1; + while(y > 0) + { + if(st < 0) + { + pxl[pxl.length] = x; + pxt[pxt.length] = y; + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) + { + pxl[pxl.length] = x; + st += bb2*((x<<1)+3) - aa4*(y-1); + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + pxt[pxt.length] = y; + } + else + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + } + + if(_y > 0) + { + if(_st < 0) + { + _st += _bb2*((_x<<1)+3); + _tt += _bb4*(++_x); + _pxb[_pxb.length] = _y-1; + } + else if(_tt < 0) + { + _st += _bb2*((_x<<1)+3) - _aa4*(_y-1); + _tt += _bb4*(++_x) - _aa2*(((_y--)<<1)-3); + _pxb[_pxb.length] = _y-1; + } + else + { + _tt -= _aa2*((_y<<1)-3); + _st -= _aa4*(--_y); + _pxb[_pxb.length-1]--; + } + } + } + + var ox = -wod, oy = b, + _oy = _pxb[0], + l = pxl.length, + w, h; + for(var i = 0; i < l; i++) + { + if(typeof _pxb[i] != "undefined") + { + if(_pxb[i] < _oy || pxt[i] < oy) + { + x = pxl[i]; + this._mkOvQds(cx, cy, x, oy, x-ox, oy-_oy, wod, hod); + ox = x; + oy = pxt[i]; + _oy = _pxb[i]; + } + } + else + { + x = pxl[i]; + this._mkDiv(cx-x, cy-oy, 1, (oy<<1)+hod); + this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod); + ox = x; + oy = pxt[i]; + } + } + this._mkDiv(cx-a, cy-oy, 1, (oy<<1)+hod); + this._mkDiv(cx+ox+wod, cy-oy, 1, (oy<<1)+hod); + } +} + +function _mkOvDott(left, top, width, height) +{ + var a = (++width)>>1, b = (++height)>>1, + wod = width&1, hod = height&1, hodu = hod^1, + cx = left+a, cy = top+b, + x = 0, y = b, + aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1, + st = (aa2>>1)*(1-(b<<1)) + bb2, + tt = (bb2>>1) - aa2*((b<<1)-1), + drw = true; + while(y > 0) + { + if(st < 0) + { + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) + { + st += bb2*((x<<1)+3) - aa4*(y-1); + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + } + else + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + } + if(drw && y >= hodu) this._mkOvQds(cx, cy, x, y, 1, 1, wod, hod); + drw = !drw; + } +} + +function _mkRect(x, y, w, h) +{ + var s = this.stroke; + this._mkDiv(x, y, w, s); + this._mkDiv(x+w, y, s, h); + this._mkDiv(x, y+h, w+s, s); + this._mkDiv(x, y+s, s, h-s); +} + +function _mkRectDott(x, y, w, h) +{ + this.drawLine(x, y, x+w, y); + this.drawLine(x+w, y, x+w, y+h); + this.drawLine(x, y+h, x+w, y+h); + this.drawLine(x, y, x, y+h); +} + +function jsgFont() +{ + this.PLAIN = 'font-weight:normal;'; + this.BOLD = 'font-weight:bold;'; + this.ITALIC = 'font-style:italic;'; + this.ITALIC_BOLD = this.ITALIC + this.BOLD; + this.BOLD_ITALIC = this.ITALIC_BOLD; +} +var Font = new jsgFont(); + +function jsgStroke() +{ + this.DOTTED = -1; +} +var Stroke = new jsgStroke(); + +function JSGraphics(cnv, wnd) +{ + this.setColor = function(x) + { + this.color = x.toLowerCase(); + }; + + this.setStroke = function(x) + { + this.stroke = x; + if(!(x+1)) + { + this.drawLine = _mkLinDott; + this._mkOv = _mkOvDott; + this.drawRect = _mkRectDott; + } + else if(x-1 > 0) + { + this.drawLine = _mkLin2D; + this._mkOv = _mkOv2D; + this.drawRect = _mkRect; + } + else + { + this.drawLine = _mkLin; + this._mkOv = _mkOv; + this.drawRect = _mkRect; + } + }; + + this.setPrintable = function(arg) + { + this.printable = arg; + if(jg_fast) + { + this._mkDiv = _mkDivIe; + this._htmRpc = arg? _htmPrtRpc : _htmRpc; + } + else this._mkDiv = arg? _mkDivPrt : _mkDiv; + }; + + this.setFont = function(fam, sz, sty) + { + this.ftFam = fam; + this.ftSz = sz; + this.ftSty = sty || Font.PLAIN; + }; + + this.drawPolyline = this.drawPolyLine = function(x, y) + { + for (var i=x.length - 1; i;) + {--i; + this.drawLine(x[i], y[i], x[i+1], y[i+1]); + } + }; + + this.fillRect = function(x, y, w, h) + { + this._mkDiv(x, y, w, h); + }; + + this.drawPolygon = function(x, y) + { + this.drawPolyline(x, y); + this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]); + }; + + this.drawEllipse = this.drawOval = function(x, y, w, h) + { + this._mkOv(x, y, w, h); + }; + + this.fillEllipse = this.fillOval = function(left, top, w, h) + { + var a = w>>1, b = h>>1, + wod = w&1, hod = h&1, + cx = left+a, cy = top+b, + x = 0, y = b, oy = b, + aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1, + st = (aa2>>1)*(1-(b<<1)) + bb2, + tt = (bb2>>1) - aa2*((b<<1)-1), + xl, dw, dh; + if(w) while(y > 0) + { + if(st < 0) + { + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) + { + st += bb2*((x<<1)+3) - aa4*(y-1); + xl = cx-x; + dw = (x<<1)+wod; + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + dh = oy-y; + this._mkDiv(xl, cy-oy, dw, dh); + this._mkDiv(xl, cy+y+hod, dw, dh); + oy = y; + } + else + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + } + } + this._mkDiv(cx-a, cy-oy, w, (oy<<1)+hod); + }; + + this.fillArc = function(iL, iT, iW, iH, fAngA, fAngZ) + { + var a = iW>>1, b = iH>>1, + iOdds = (iW&1) | ((iH&1) << 16), + cx = iL+a, cy = iT+b, + x = 0, y = b, ox = x, oy = y, + aa2 = (a*a)<<1, aa4 = aa2<<1, bb2 = (b*b)<<1, bb4 = bb2<<1, + st = (aa2>>1)*(1-(b<<1)) + bb2, + tt = (bb2>>1) - aa2*((b<<1)-1), + // Vars for radial boundary lines + xEndA, yEndA, xEndZ, yEndZ, + iSects = (1 << (Math.floor((fAngA %= 360.0)/180.0) << 3)) + | (2 << (Math.floor((fAngZ %= 360.0)/180.0) << 3)) + | ((fAngA >= fAngZ) << 16), + aBndA = new Array(b+1), aBndZ = new Array(b+1); + + // Set up radial boundary lines + fAngA *= Math.PI/180.0; + fAngZ *= Math.PI/180.0; + xEndA = cx+Math.round(a*Math.cos(fAngA)); + yEndA = cy+Math.round(-b*Math.sin(fAngA)); + _mkLinVirt(aBndA, cx, cy, xEndA, yEndA); + xEndZ = cx+Math.round(a*Math.cos(fAngZ)); + yEndZ = cy+Math.round(-b*Math.sin(fAngZ)); + _mkLinVirt(aBndZ, cx, cy, xEndZ, yEndZ); + + while(y > 0) + { + if(st < 0) // Advance x + { + st += bb2*((x<<1)+3); + tt += bb4*(++x); + } + else if(tt < 0) // Advance x and y + { + st += bb2*((x<<1)+3) - aa4*(y-1); + ox = x; + tt += bb4*(++x) - aa2*(((y--)<<1)-3); + this._mkArcDiv(ox, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects); + oy = y; + } + else // Advance y + { + tt -= aa2*((y<<1)-3); + st -= aa4*(--y); + if(y && (aBndA[y] != aBndA[y-1] || aBndZ[y] != aBndZ[y-1])) + { + this._mkArcDiv(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects); + ox = x; + oy = y; + } + } + } + this._mkArcDiv(x, 0, oy, cx, cy, iOdds, aBndA, aBndZ, iSects); + if(iOdds >> 16) // Odd height + { + if(iSects >> 16) // Start-angle > end-angle + { + var xl = (yEndA <= cy || yEndZ > cy)? (cx - x) : cx; + this._mkDiv(xl, cy, x + cx - xl + (iOdds & 0xffff), 1); + } + else if((iSects & 0x01) && yEndZ > cy) + this._mkDiv(cx - x, cy, x, 1); + } + }; + +/* fillPolygon method, implemented by Matthieu Haller. +This javascript function is an adaptation of the gdImageFilledPolygon for Walter Zorn lib. +C source of GD 1.8.4 found at http://www.boutell.com/gd/ + +THANKS to Kirsten Schulz for the polygon fixes! + +The intersection finding technique of this code could be improved +by remembering the previous intertersection, and by using the slope. +That could help to adjust intersections to produce a nice +interior_extrema. */ + this.fillPolygon = function(array_x, array_y) + { + var i; + var y; + var miny, maxy; + var x1, y1; + var x2, y2; + var ind1, ind2; + var ints; + + var n = array_x.length; + if(!n) return; + + miny = array_y[0]; + maxy = array_y[0]; + for(i = 1; i < n; i++) + { + if(array_y[i] < miny) + miny = array_y[i]; + + if(array_y[i] > maxy) + maxy = array_y[i]; + } + for(y = miny; y <= maxy; y++) + { + var polyInts = new Array(); + ints = 0; + for(i = 0; i < n; i++) + { + if(!i) + { + ind1 = n-1; + ind2 = 0; + } + else + { + ind1 = i-1; + ind2 = i; + } + y1 = array_y[ind1]; + y2 = array_y[ind2]; + if(y1 < y2) + { + x1 = array_x[ind1]; + x2 = array_x[ind2]; + } + else if(y1 > y2) + { + y2 = array_y[ind1]; + y1 = array_y[ind2]; + x2 = array_x[ind1]; + x1 = array_x[ind2]; + } + else continue; + + // Modified 11. 2. 2004 Walter Zorn + if((y >= y1) && (y < y2)) + polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1); + + else if((y == maxy) && (y > y1) && (y <= y2)) + polyInts[ints++] = Math.round((y-y1) * (x2-x1) / (y2-y1) + x1); + } + polyInts.sort(_CompInt); + for(i = 0; i < ints; i+=2) + this._mkDiv(polyInts[i], y, polyInts[i+1]-polyInts[i]+1, 1); + } + }; + + this.drawString = function(txt, x, y) + { + this.htm += '
'+ + txt + + '<\/div>'; + }; + +/* drawStringRect() added by Rick Blommers. +Allows to specify the size of the text rectangle and to align the +text both horizontally (e.g. right) and vertically within that rectangle */ + this.drawStringRect = function(txt, x, y, width, halign) + { + this.htm += '
'+ + txt + + '<\/div>'; + }; + + this.drawImage = function(imgSrc, x, y, w, h, a) + { + this.htm += '
'+ + ''+ + '<\/div>'; + }; + + this.clear = function() + { + this.htm = ""; + if(this.cnv) this.cnv.innerHTML = ""; + }; + + this._mkOvQds = function(cx, cy, x, y, w, h, wod, hod) + { + var xl = cx - x, xr = cx + x + wod - w, yt = cy - y, yb = cy + y + hod - h; + if(xr > xl+w) + { + this._mkDiv(xr, yt, w, h); + this._mkDiv(xr, yb, w, h); + } + else + w = xr - xl + w; + this._mkDiv(xl, yt, w, h); + this._mkDiv(xl, yb, w, h); + }; + + this._mkArcDiv = function(x, y, oy, cx, cy, iOdds, aBndA, aBndZ, iSects) + { + var xrDef = cx + x + (iOdds & 0xffff), y2, h = oy - y, xl, xr, w; + + if(!h) h = 1; + x = cx - x; + + if(iSects & 0xff0000) // Start-angle > end-angle + { + y2 = cy - y - h; + if(iSects & 0x00ff) + { + if(iSects & 0x02) + { + xl = Math.max(x, aBndZ[y]); + w = xrDef - xl; + if(w > 0) this._mkDiv(xl, y2, w, h); + } + if(iSects & 0x01) + { + xr = Math.min(xrDef, aBndA[y]); + w = xr - x; + if(w > 0) this._mkDiv(x, y2, w, h); + } + } + else + this._mkDiv(x, y2, xrDef - x, h); + y2 = cy + y + (iOdds >> 16); + if(iSects & 0xff00) + { + if(iSects & 0x0100) + { + xl = Math.max(x, aBndA[y]); + w = xrDef - xl; + if(w > 0) this._mkDiv(xl, y2, w, h); + } + if(iSects & 0x0200) + { + xr = Math.min(xrDef, aBndZ[y]); + w = xr - x; + if(w > 0) this._mkDiv(x, y2, w, h); + } + } + else + this._mkDiv(x, y2, xrDef - x, h); + } + else + { + if(iSects & 0x00ff) + { + if(iSects & 0x02) + xl = Math.max(x, aBndZ[y]); + else + xl = x; + if(iSects & 0x01) + xr = Math.min(xrDef, aBndA[y]); + else + xr = xrDef; + y2 = cy - y - h; + w = xr - xl; + if(w > 0) this._mkDiv(xl, y2, w, h); + } + if(iSects & 0xff00) + { + if(iSects & 0x0100) + xl = Math.max(x, aBndA[y]); + else + xl = x; + if(iSects & 0x0200) + xr = Math.min(xrDef, aBndZ[y]); + else + xr = xrDef; + y2 = cy + y + (iOdds >> 16); + w = xr - xl; + if(w > 0) this._mkDiv(xl, y2, w, h); + } + } + }; + + this.setStroke(1); + this.setFont("verdana,geneva,helvetica,sans-serif", "12px", Font.PLAIN); + this.color = "#000000"; + this.htm = ""; + this.wnd = wnd || window; + + if(!jg_ok) _chkDHTM(this.wnd); + if(jg_ok) + { + if(cnv) + { + if(typeof(cnv) == "string") + this.cont = document.all? (this.wnd.document.all[cnv] || null) + : document.getElementById? (this.wnd.document.getElementById(cnv) || null) + : null; + else if(cnv == window.document) + this.cont = document.getElementsByTagName("body")[0]; + // If cnv is a direct reference to a canvas DOM node + // (option suggested by Andreas Luleich) + else this.cont = cnv; + // Create new canvas inside container DIV. Thus the drawing and clearing + // methods won't interfere with the container's inner html. + // Solution suggested by Vladimir. + this.cnv = this.wnd.document.createElement("div"); + this.cnv.style.fontSize=0; + this.cont.appendChild(this.cnv); + this.paint = jg_dom? _pntCnvDom : _pntCnvIe; + } + else + this.paint = _pntDoc; + } + else + this.paint = _pntN; + + this.setPrintable(false); +} + +function _mkLinVirt(aLin, x1, y1, x2, y2) +{ + var dx = Math.abs(x2-x1), dy = Math.abs(y2-y1), + x = x1, y = y1, + xIncr = (x1 > x2)? -1 : 1, + yIncr = (y1 > y2)? -1 : 1, + p, + i = 0; + if(dx >= dy) + { + var pr = dy<<1, + pru = pr - (dx<<1); + p = pr-dx; + while(dx > 0) + {--dx; + if(p > 0) // Increment y + { + aLin[i++] = x; + y += yIncr; + p += pru; + } + else p += pr; + x += xIncr; + } + } + else + { + var pr = dx<<1, + pru = pr - (dy<<1); + p = pr-dy; + while(dy > 0) + {--dy; + y += yIncr; + aLin[i++] = x; + if(p > 0) // Increment x + { + x += xIncr; + p += pru; + } + else p += pr; + } + } + for(var len = aLin.length, i = len-i; i;) + aLin[len-(i--)] = x; +}; + +function _CompInt(x, y) +{ + return(x - y); +} + diff --git a/workflow/public_html/lib/lib-mafe.log b/workflow/public_html/lib/lib-mafe.log new file mode 100644 index 000000000..10db0db52 --- /dev/null +++ b/workflow/public_html/lib/lib-mafe.log @@ -0,0 +1,30 @@ +[8 weeks ago] a9ede644 (origin/bugfix/PMCORE-2311-C) PMCORE-2311-C +[9 weeks ago] 734f5c8f (origin/bugfix/PMCORE-2311-B) PMCORE-2311-B +[9 weeks ago] e1b2fc4e (origin/bugfix/PMCORE-2136-C) PMCORE-2136-C +[9 weeks ago] 0e0de9d8 (origin/bugfix/PMCORE-2311-A) PMCORE-2311-A +[9 weeks ago] d6c268a9 (origin/bugfix/PMCORE-2136-B) PMCORE-2136-B +[9 weeks ago] db51b322 (origin/bugfix/PMCORE-2136-A) PMCORE-2136-A +[9 weeks ago] 18b5e64f PMCORE-2311 +[2 months ago] a1283ec8 (origin/bugfix/PMCORE-2278) PMCORE-2278 +[3 months ago] 440c12da (origin/bugfix/PMCORE-2136) PMCORE-2136 +[3 months ago] 2bf373db (origin/bugfix/PMCORE-561) PMCORE-561 +[3 months ago] 9af801bc (origin/bugfix/PMCORE-2040) PMCORE-2040 +[3 months ago] 4568d802 (origin/bugfix/PMCORE-2044) PMCORE-2044 +[3 months ago] 9166e496 (origin/feature/PMCORE-2095) Fix CR observations by Rodrigo +[3 months ago] 1f85f34e (origin/bugfix/PMCORE-694) PMCORE-694 +[3 months ago] a5ffc5de (origin/bugfix/PMCORE-2128) PMCORE-2128 +[3 months ago] 7ddb25d1 Fix PM observations +[3 months ago] 009637ed PMCORE-2099 +[3 months ago] 41259199 PMCORE-2096 +[4 months ago] 5b3dce87 Fix PM observations +[4 months ago] 7f2dcb73 (origin/bugfix/PMCORE-2099) PMCORE-2099 +[4 months ago] c0cb7a81 (origin/bugfix/PMCORE-2096) PMCORE-2096 +[4 months ago] c09985a7 (origin/feature/PMCORE-2112) PMCORE-2112: Add Fixed Location Property to geomap mobile control +[5 months ago] 8f7a7423 translate +[5 months ago] e3dd3b95 PMCORE-1829:default-vaule property does not have hint +[5 months ago] 24c0137d PMCORE-1828:Hint to max-date property of date-time control was not update +[5 months ago] 45574666 (origin/bugfix/PMCORE-1776) PMCORE-1776 +[5 months ago] 0b76dd90 (origin/bugfix/PMCORE-1745_B) PMCORE-1745: ABE - Email response >> the default email account is empty for the "receiver account" option +[5 months ago] 50aee6d9 (origin/bugfix/PMCORE-1745) PMCORE-1745: ABE - Email response >> the default email account is empty for the "receiver account" option +[6 months ago] 970aedbb PMCORE-1712:PMFTotalCalculation trigger Wizard help letters get out of the box +[6 months ago] e624023a (origin/bugfix/PMCORE-1688) PMCORE-1688 Review the composer from the release/3.5.0 \ No newline at end of file diff --git a/workflow/public_html/lib/lib-pmdynaform.log b/workflow/public_html/lib/lib-pmdynaform.log new file mode 100644 index 000000000..17c5b0638 --- /dev/null +++ b/workflow/public_html/lib/lib-pmdynaform.log @@ -0,0 +1,30 @@ +[4 days ago] 66a14701 (HEAD, origin/release/3.5.7, origin/release/3.5.6) PMCORE-2526:Radio control does not update after use "setValue" helper to clean the control +[3 weeks ago] 71439824 PMCORE-2378: Error opening Dynaform after saving with saveForm () +[3 weeks ago] 5ea6113a PMCORE-2425: Dynaform - Grid Control - Delete button is not working as expected +[3 weeks ago] fcd75b65 PMCORE-2462: Set empty value to Radio buttons is not working +[9 weeks ago] 7237fd1a PMCORE-1773:[20214 ] GetValue() method is returning the label instead of the Key for radio fields in Mobile. +[9 weeks ago] 731e77a1 (origin/bugfix/PMCORE-1341-A) PMCORE-1341-A +[10 weeks ago] 2073d30c [20214 ] GetValue() method is returning the label instead of the Key for radio fields in Mobile. +[3 months ago] 18035a13 PMCORE-1773:[20214 ] GetValue() method is returning the label instead of the Key for radio fields in Mobile. +[3 months ago] b41c162e (origin/bugfix/PMCORE-2161) PMCORE-2161: Wrong functionality of the dropdown controls in grid +[3 months ago] aa024a7a (origin/bugfix/PMCORE-1234) PMCORE-1234 +[3 months ago] 3728a520 (origin/bugfix/PMCORE-1751) PMCORE-1751 +[3 months ago] c580864a (origin/escapeSelector) escapeSelector methos was created +[3 months ago] 7565b8cc (origin/bugfix/PMCORE-2061) PMCORE-2061 +[4 months ago] c2246d87 (origin/feature/PMCORE-2114) PMCORE-2114: Javascript Helper functions for geomap control +[4 months ago] 1966b2ef (origin/bugfix/PMCORE-1961) PMCORE-1961 +[4 months ago] 4d3a8804 (origin/bugfix/PMCORE-759) PMCORE-759 +[4 months ago] 96ab5933 PMCORE-537:Bug with rows of the grid and multiple file +[4 months ago] 0cf32fc3 (origin/bugfix/PMCORE-2052) PMCORE-2052 +[4 months ago] 8db9a803 (origin/bugfix/PMCORE-2045) PMCORE-2045 +[4 months ago] 8dc912cc (origin/bugfix/PMCORE-2004, origin/bigfix/PMCORE-2004) PMCORE-2004: IE 11>> Values of suggest control are lost in the second task +[4 months ago] a03762cf (origin/bugfix/PMCORE-1998) PMCORE-1998 +[4 months ago] 7eef0679 (origin/bugfix/PMCORE-2009) PMCORE-2009: IE 11 >> Date time control validation does not disappear, when it is corrected +[4 months ago] 5c92fd62 (origin/bugfix/PMCORE-1112-A) PMCORE-1112-A +[4 months ago] 555883b5 (origin/bugfix/PMCORE-1837) PMCORE-1837 +[4 months ago] 570fa814 (origin/bugfix/PMCORE-559) PMCORE-559: [ZenDesk 11723] Date Time Control - Initial Selection Date Property when setting the format HH:mm is not displaying the time correctly +[5 months ago] a79bc677 (origin/bugfix/PMCORE-1112) PMCORE-1112 +[5 months ago] 8c8d2ba7 (origin/bugfix/PMCORE-1607-B) update v2 +[5 months ago] 87a2a94b update +[5 months ago] 09ae2de3 PMCORE-1607-B +[5 months ago] 6ccfe4bf PMCORE-1607-B \ No newline at end of file diff --git a/workflow/public_html/lib/lib-pmui.log b/workflow/public_html/lib/lib-pmui.log new file mode 100644 index 000000000..4a1b7642c --- /dev/null +++ b/workflow/public_html/lib/lib-pmui.log @@ -0,0 +1,30 @@ +[3 months ago] 582f50cd (origin/bugfix/PMCORE-2044) PMCORE-2044 +[4 months ago] 48b618c1 (origin/bugfix/PMCORE-2011) PMCORE-2011 +[1 year, 8 months ago] 581a6f26 (origin/bugfix/PMC-166) PMC-166 +[2 years ago] 62cc5a80 PMC-322:[Mantis 25900] Add the labels for some English fields in the English .po file} +[2 years ago] bcb72023 PMC-320:Does not works the "Del/Supr" Key after press "Enter" key in the "Confirm" frame +[2 years ago] be0c1479 PMC-171:The line to connect elements BPMN aren't delete using the Del/Supr key +[2 years, 1 month ago] 984ddb1f FBI-2394:Task deleted on CTRL+ALT+DELETE - Windows 10 +[2 years, 1 month ago] 29bcda88 (origin/bugfix/PMC-4) PMC-4: [Mantis-25811]When assigning triggers to execute before a dynaform, the sequence is getting out of order and the cardinal number is repeated or misplaced +[2 years, 8 months ago] 9eb86aa8 FBI-2383:Triggers > when we are going to edit the code of a trigger, the code is superimposed on the alert "required field" +[3 years, 2 months ago] 0aad8c90 (origin/improvement/FBI-2144) FBI-2144 +[3 years, 4 months ago] f78ce304 FBI-636 +[3 years, 5 months ago] 9c30bd36 FBI-1140 (Task Steps) Label "No Records Found" even if there is a trigger assigned +[3 years, 5 months ago] 809acfe1 FBI-1464: Improved solution +[3 years, 7 months ago] 31cf982c FBI-927: Add validation to avoid duplicated items in canvas +[3 years, 7 months ago] 85b88acb FBI-1781 +[3 years, 9 months ago] d347bbef FBI-992: Fix "Required field" to be permanently visible +[3 years, 10 months ago] 1db5a6b7 FBI-1513 Grammar mistakes found in the Create a Variable window +[3 years, 10 months ago] 7e5e9d35 FBI-1008 +[3 years, 11 months ago] 73fa18e2 FBI-1415: The lasso does not work when we move the process flow +[4 years, 2 months ago] e1d0f9ae FBI-1237: [PMUI] No es posible adicionar una nueva opcin en un checkgroupField +[4 years, 3 months ago] f8386bca FBI-1074 +[4 years, 3 months ago] 68134906 FBI-1041: Cost&Units: Al hacer click en SAVE después de dejar vacíos estos elementos, no es posible editarlos +[4 years, 4 months ago] 612abd38 FBI-1009 +[4 years, 4 months ago] de682c10 FBI-961: [Process Designer] Error guardar la fecha del datepicker de PMUI +[4 years, 4 months ago] 1d06ba1f FBI-898 +[4 years, 4 months ago] f8b8c64c FBI-847: Variable no permite editar el Name en IE 11 +[4 years, 4 months ago] 3951a241 FBI-801: Fixes +[4 years, 4 months ago] 2eaddf4e FBI-789 +[4 years, 4 months ago] 5e3e5f0d FBI-393: Fix connection decorator positioning +[4 years, 5 months ago] c4824521 FBI-670:(Custom Trigger) No se actualizan las listas de los triggers \ No newline at end of file diff --git a/workflow/public_html/lib/mafe/designer.min.js b/workflow/public_html/lib/mafe/designer.min.js new file mode 100644 index 000000000..864e0725a --- /dev/null +++ b/workflow/public_html/lib/mafe/designer.min.js @@ -0,0 +1,35237 @@ +var defaultCrown = { + items: [ + { + id: "task", + name: "Task".translate(), + className: "mafe-corona-task", + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'TASK'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-task'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "gateway", + name: 'Gateway'.translate(), + className: 'mafe-corona-gateway-exclusive', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'EXCLUSIVE'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-gateway-exclusive'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "intermediate", + name: 'Intermediate'.translate(), + className: 'mafe-corona-intermediate', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'INTERMEDIATE_EMAIL'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-intermediate-send-mesage'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "end", + name: 'End'.translate(), + className: 'mafe-corona-end', + eventOnClick: function (item) { + item.parent.hide(); + }, + eventOnMouseDown: function (item) { + item.canvas.canCreateShape = true; + item.canvas.canCreateShapeType = 'END'; + item.canvas.canCreateShapeClass = 'mafe-toolbar-end'; + item.canvas.connectStartShape = item.parent.parent; + }, + eventOnMouseOut: function (item) { + if (item.canvas.canCreateShape) { + item.parent.hide(); + } + } + }, + { + id: "flow", + name: 'Flow'.translate(), + className: 'mafe-corona-flow', + eventOnClick: function (item) { + item.parent.hide(); + item.parent.parent.canvas.hideAllFocusedLabels(); + }, + eventOnMouseDown: function (item) { + item.canvas.canConnect = true; + item.canvas.connectStartShape = item.parent.parent; + } + }, + { + id: "properties", + name: 'Properties'.translate(), + className: 'mafe-corona-settings', + eventOnClick: function (item) { + item.parent.hide(); + PMDesigner.saveAndOpenSettings(item.parent.parent, PMDesigner.shapeProperties); + } + }, + { + id: "delete", + name: 'Delete'.translate(), + className: 'mafe-corona-delete', + eventOnClick: function (item) { + PMUI.getActiveCanvas().removeElements(); + item.parent.hide(); + } + } + ] +}; + +var configCrown = { + 'PMActivity': { + 'DEFAULT': { + order: ["task", "gateway", "intermediate", "end", "flow", "properties", "delete"], + rows: 3, + cols: 3 + } + }, + 'PMGateway': { + 'PARALLEL': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'EXCLUSIVE': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INCLUSIVE': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + } + }, + 'PMEvent': { + 'START_EMPTY': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'START_MESSAGECATCH': { + order: ["task", "gateway", "intermediate", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'START_TIMER': { + order: ["task", "gateway", "intermediate", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'START_CONDITIONAL': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'START_SIGNALCATCH': { + order: ["task", "gateway", "intermediate", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_EMAIL': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_MESSAGETHROW': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_SIGNALTHROW': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_MESSAGECATCH': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_TIMER': { + order: ["task", "gateway", "end", "flow", "properties", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_CONDITIONAL': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'INTERMEDIATE_SIGNALCATCH': { + order: ["task", "gateway", "end", "flow", "delete"], + rows: 3, + cols: 2 + }, + 'END_EMPTY': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_EMAIL': { + order: ["flow", "properties", "delete"], + rows: 2, + cols: 2 + }, + 'END_MESSAGETHROW': { + order: ["flow", "properties", "delete"], + rows: 2, + cols: 2 + }, + 'END_ERRORTHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_SIGNALTHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'END_TERMINATETHROW': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + }, + 'PMPool': { + 'DEFAULT': { + order: ["delete"], + rows: 1, + cols: 1 + } + }, + 'PMParticipant': { + 'DEFAULT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + }, + 'PMArtifact': { + 'TEXT_ANNOTATION': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'GROUP': { + order: ["delete"], + rows: 1, + cols: 1 + } + }, + 'PMData': { + 'DATAOBJECT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATAINPUT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATAOUTPUT': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + }, + 'DATASTORE': { + order: ["flow", "delete"], + rows: 2, + cols: 1 + } + } +}; +var PMDesigner = {}, + LANG, + WORKSPACE, + SKIN, + DEFAULT_WINDOW_WIDTH, + DEFAULT_WINDOW_HEIGHT, + ENABLED_FEATURES, + DataDictionary, + enviromentVariables, + resizingFrame, + ViewTaskInformation; + +PMDesigner.defaultRules = window.defaultRules ? window.defaultRules : {}; +PMDesigner.defaultCrown = window.defaultCrown ? defaultCrown : {}; +PMDesigner.configCrown = window.configCrown ? configCrown : {}; +PMDesigner.modelRules = new ModelRules(PMDesigner.defaultRules); +PMDesigner.modelCrown = new ModelCrown(PMDesigner.defaultCrown); +PMDesigner.remoteUrl = ""; +PMDesigner.moddle = new BpmnModdle(); +PMDesigner.bpmnFactory = new BpmnFactory(PMDesigner.moddle); +PMDesigner.keyCodeF5 = 116; +PMDesigner.shapeProperties = function (shape) { + var typeShape = shape.type; + switch (typeShape) { + case "PMActivity": + PMDesigner.activityProperties(shape); + break; + case "PMGateway": + PMDesigner.gatewayProperties(shape); + break; + case "PMEvent": + shape.eventProperties(); + break; + } +}; + +/** + * function to get the enviroment variables (WORKSPACE, LANG, SKIN) + */ +enviromentVariables = function (variable) { + var url1, variables, WORKSPACE, LANG, SKIN; + if (window.parent) { + url1 = window.parent.location.pathname; + variables = url1.split('/'); + WORKSPACE = variables[1]; + WORKSPACE = WORKSPACE.substring(3); + LANG = variables[2]; + SKIN = variables[3]; + + if (variable == 'WORKSPACE') { + return WORKSPACE; + } else if (variable == 'LANG') { + return LANG; + } else if (variable == 'SKIN') { + return SKIN; + } else { + return null; + } + } +}; + +LANG = (typeof SYS_LANG !== "undefined") ? SYS_LANG : enviromentVariables('LANG'); +WORKSPACE = (typeof SYS_SYS !== "undefined") ? SYS_SYS : enviromentVariables('WORKSPACE'); +SKIN = (typeof SYS_SKIN !== "undefined") ? SYS_SKIN : enviromentVariables('SKIN'); + +DEFAULT_WINDOW_WIDTH = 943; +DEFAULT_WINDOW_HEIGHT = 520; +ENABLED_FEATURES = []; + +if (LANG != 'en') { + if (typeof __TRANSLATIONMAFE != "undefined" && typeof __TRANSLATIONMAFE[LANG] != 'undefined') { + PMUI.loadLanguage(__TRANSLATIONMAFE.en, 'en'); + PMUI.loadLanguage(__TRANSLATIONMAFE[LANG], LANG); + + PMUI.setDefaultLanguage('en'); + PMUI.setCurrentLanguage(LANG); + } +} + +PMDesigner.resizeFrame = function () { + if (parent.document.documentElement === document.documentElement) { + jQuery(".content").css("height", parseInt(jQuery(window).height())); + } else { + jQuery(".content").css("height", document.body.clientHeight); + + } +}; +resizingFrame = PMDesigner.resizeFrame; +PMDesigner.applyCanvasOptions = function () { + list = new PMUI.control.DropDownListControl({ + options: [], + style: { + cssClasses: [ + "mafe-dropdown-zoom" + ] + }, + width: 150, + onChange: function (newValue, previous) { + var canvas = PMDesigner.project.diagrams.find('id', newValue); + PMUI.getActiveCanvas().getHTML().style.display = 'none'; + PMUI.setActiveCanvas(canvas); + canvas.getHTML().style.display = 'inline'; + } + }); + //enable to support multidiagram + //jQuery(jQuery(".navBar li")[6]).append(list.getHTML()); + list.defineEvents(); + PMDesigner.canvasList = list; +}; +//Zoom +PMDesigner.ApplyOptionsZoom = function () { + list = new PMUI.control.DropDownListControl({ + id: '_idListZoom', + options: [ + { + label: "50%", + value: 1 + }, + { + label: "75%", + value: 2 + }, + { + label: "100%", + value: 3, + selected: true + }, + { + label: "125%", + value: 4 + }, + { + label: "150%", + value: 5 + } + ], + style: { + cssClasses: [ + "mafe-dropdown-zoom" + ] + }, + onChange: function (newValue, previous) { + var i; + newValue = parseInt(newValue, 10); + PMUI.getActiveCanvas().applyZoom(newValue); + } + }); + + //jQuery(jQuery(".navBar li")[4]).append(list.getHTML()); + jQuery(jQuery(".mafe-zoom-options")).append(list.getHTML()); + + list.defineEvents(); +}; +/** + * hides all requiered TinyControls + */ +PMDesigner.hideAllTinyEditorControls = function () { + var control, + i, + max, + j, + mapMax, + editor, + controlMap = [ + 'tinyeditor_fontselect', + 'tinyeditor_fontsizeselect', + 'tinyeditor_bullist', + 'tinyeditor_numlist', + 'tinyeditor_forecolor', + 'tinyeditor_backcolor' + ]; + for (i = 0, max = tinymce.editors.length; i < max; i += 1) { + editor = tinymce.editors[i]; + jQuery.each(editor.controlManager.controls, function (index, val) { + if (val && jQuery.isFunction(val.hideMenu)) { + val.hideMenu(); + } + }); + } + +}; + + +jQuery(document).ready(function ($) { + var setSaveButtonDisabled, + s, + sidebarCanvas, + project, + d, + downloadLink, + handlerExportNormal, + handlerExportGranular, + handler, + validatosr, + help, + option, + menu, + elem, + validatorLabel = "Validator".translate(); + /*************************************************** + * Defines the Process + ***************************************************/ + if (typeof prj_uid === "undefined") { + prj_uid = ''; + } + if (typeof prj_readonly === "undefined") { + prj_readonly = ''; + } + if (typeof credentials === "undefined") { + credentials = ''; + } else { + credentials = RCBase64.decode(credentials); + credentials = (credentials == '') ? "" : JSON.parse(credentials); + } + + if (prj_readonly !== 'true') { + $("#idContent").find(".content_controls").show(); + $(".bpmn_shapes").show(); + $('.bpmn_shapes_legend').hide(); + $("#idNavBar").show().css('height', '33px'); + } + + PMDesigner.createHTML(); + setSaveButtonDisabled = function (that) { + if (that.isDirty()) { + if (document.getElementsByClassName("mafe-save-process").length > 0) { + document.getElementsByClassName("mafe-save-process")[0].removeAttribute("style"); + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].style.color = "#FFF"; + + var mafebuttonMenu = document.getElementsByClassName("mafe-button-menu")[0]; + mafebuttonMenu.style.backgroundColor = "#0C9778"; + mafebuttonMenu.firstChild.src = "/lib/img/caret-down-w.png"; + } + } else { + if (document.getElementsByClassName("mafe-save-process").length > 0) { + document.getElementsByClassName("mafe-save-process")[0].style.backgroundColor = "#e8e8e8"; + document.getElementsByClassName("mafe-save-process")[0].style.color = "#000"; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].style.color = "#000"; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].text = "Save".translate(); + + var mafebuttonMenu = document.getElementsByClassName("mafe-button-menu")[0]; + mafebuttonMenu.style.backgroundColor = "#e8e8e8"; + mafebuttonMenu.firstChild.src = "/lib/img/caret-down.png"; + } + } + }; + sidebarCanvas = []; + for (s = 0; s < PMDesigner.sidebar.length; s += 1) { + sidebarCanvas = sidebarCanvas.concat(PMDesigner.sidebar[s].getSelectors()); + jQuery(".bpmn_shapes").append(PMDesigner.sidebar[s].getHTML()); + } + //Adding Sidebar to DOM + firstAbsuluteX = jQuery("#div-layout-canvas").offset().left; + + project = new PMProject({ + id: prj_uid, + name: 'Untitled Process', + readOnly: prj_readonly === "true", + keys: { + access_token: credentials.access_token, + expires_in: credentials.expires_in, + token_type: credentials.token_type, + scope: credentials.scope, + refresh_token: credentials.refresh_token, + client_id: credentials.client_id, + client_secret: credentials.client_secret + }, + listeners: { + create: function (self, element) { + var sh, i, + contDivergent = 0, + contConvergent = 0; + //Updating the background color for connections + jQuery(".pmui-intersection > div > div").css("background-color", "black"); + + if (element.type == "Connection") { + ///////////****************Changing the gatDirection*******************////////////////// + if (element.relatedObject.srcPort.parent.gat_type === "PARALLEL" || + element.relatedObject.srcPort.parent.gat_type === "INCLUSIVE" || + element.relatedObject.destPort.parent.gat_type === "PARALLEL" || + element.relatedObject.destPort.parent.gat_type === "INCLUSIVE") { + if (element.relatedObject.srcPort.parent.gat_type !== undefined) { + sh = element.relatedObject.srcPort.parent; + } else { + sh = element.relatedObject.destPort.parent; + } + + if (sh.gat_direction === "DIVERGING") { + for (i = 0; i < sh.ports.asArray().length; i += 1) { + if (sh.ports.asArray()[i].connection.flo_element_origin_type === "bpmnActivity") { + contDivergent += 1; + } + if (contDivergent > 1) { + sh.gat_direction = "CONVERGING"; + i = sh.ports.asArray().length; + } + } + } + if (sh.gat_direction === "CONVERGING") { + for (i = 0; i < sh.ports.asArray().length; i += 1) { + if (sh.ports.asArray()[i].connection.flo_element_origin_type === "bpmnGateway") { + contConvergent += 1; + } + if (contConvergent > 1) { + sh.gat_direction = "DIVERGING"; + i = sh.ports.asArray().length; + } + } + } + + } + } + setSaveButtonDisabled(self); + }, + update: function (self) { + //Updating the background color for connections + jQuery(".pmui-intersection > div > div").css("background-color", "black"); + setSaveButtonDisabled(self); + }, + remove: function (self) { + setSaveButtonDisabled(self); + }, + success: function (self, xhr, response) { + var message; + self.dirty = false; + setSaveButtonDisabled(self); + self.dirtyElements[0] = { + laneset: {}, + lanes: {}, + activities: {}, + events: {}, + gateways: {}, + flows: {}, + artifacts: {}, + lines: {}, + data: {}, + participants: {}, + startMessageEvent: {}, + startTimerEvent: {} + }; + self.updateIdentifiers(response); + PMDesigner.connectValidator.bpmnValidator(); + //if (PMDesigner.currentMsgFlash) { + PMDesigner.msgFlash('The process was saved successfully.'.translate(), document.body, 'success', 3000, 5); + PMDesigner.RoutingRuleSetOrder(); + //} + + }, + failure: function (self, xhr, response) { + var message; + if (response.error.code === 401) { + /*message = new PMUI.ui.FlashMessage({ + message: "It was not possible to establish a connection with the server".translate(), + duration: 5000, + appendTo: document.body, + severity: 'info' + }); + message.show();*/ + //self.remoteProxy.setUrl("/"+WORKSPACE+"/oauth2/token"); + //self.setRefreshToken(); + //self.remoteProxy.setUrl("/api/1.0/"+WORKSPACE+"/project/"+prj_uid); + //self.save(); + } else { + PMDesigner.msgFlash('Error saving the process.'.translate(), document.body, 'error', 3000, 5); + self.updateIdentifiers(response); + } + } + } + }); + PMDesigner.project = project; + //create a new restApi + PMDesigner.restApi = RestApi.createRestApi({ + serverUrl: '/rest/v10', + keys: PMDesigner.project.keys + }); + systemRest = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'system/enabled-features', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var result = response.pop(); + ENABLED_FEATURES = result.response; + navbarExportUpdate(); + }, + functionFailure: function (xhr, response) { + ENABLED_FEATURES = []; + } + }).setBaseEndPoint('').executeRestClient(); + PMDesigner.connectValidator = new ConnectValidator(); + for (d = 0; d < PMDesigner.sidebar.length; d += 1) { + PMDesigner.sidebar[d].activate(); + } + + $('.bpmn_shapes_legend').hide(); + project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + prj_uid); + project.load(); + + /*=========================================== + = ProcessMaker module = + ===========================================*/ + + //Renders content controls + PMDesigner.contentControl.show(); + new PMAction({ + selector: ".mafe-menu-eventmessages-create", + label: { + selector: ".mafe-menu-eventmessages-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.eventMessages.create(); + } + }); + + /*----- End of ProcessMaker module ------*/ + + /*======================================== + = Designer buttons = + ========================================*/ + + //Renders navBar Panel + PMDesigner.navbarPanel.show(); + // create Zoom options + PMDesigner.ApplyOptionsZoom(); + //the action to generate a .bpmn file with the export option. + downloadLink = $('.mafe-button-export-bpmn-process'); + downloadLink.click(function (e) { + PMDesigner.moddle.toXML(PMDesigner.businessObject, function (err, xmlStrUpdated) { + + setEncoded(downloadLink, PMDesigner.project.projectName + '.bpmn', xmlStrUpdated); + + // xmlStrUpdated contains new id and the added process + }); + + }); + option = $("
" + "Save as".translate() + "
"); + /** + * Add data tables + */ + $('body').append('
') + $('.validator_header').append('

' + validatorLabel + '

'); + $('.validator_header').append(''); + $('.validator_body').html('
'); + PMDesigner.validTable = $('#validator-table').DataTable({ + paging: false, + scrollY: 100, + searching: false, + "info": false, + scrollCollapse: true, + "columns": [ + { + name: 'numrow', + "title": "#", + width: '5%', + render: function (data, type, row, conf) { + return conf.row + 1; + } + }, + { + name: 'id', + className: 'never' + }, + { + "title": "Type".translate(), + width: '10%', + name: 'severity', + render: function (data, type, row, conf) { + var clasMap = { + Error: 'mafe-icon-error', + Warning: 'mafe-icon-warning' + }; + if (type === 'display') { + return ' ' + data; + } + return data; + } + }, + {name: 'element', "title": "Element".translate(), width: '15%'}, + {name: 'element-type', "title": "Element Type".translate(), width: '15%'}, + {name: 'description', "title": "Description".translate(), width: '45%'} + ] + }); + jQuery('#validator-table tbody').on('click', 'tr', function () { + var id = PMDesigner.validTable.row(this).data()[1], + shape; + if ($(this).hasClass('selected')) { + $(this).removeClass('selected'); + PMUI.getActiveCanvas().hideAllCoronas().emptyCurrentSelection(); + } + else { + PMDesigner.validTable.$('tr.selected').removeClass('selected'); + $(this).addClass('selected'); + PMUI.getActiveCanvas().hideAllCoronas().emptyCurrentSelection(); + shape = PMUI.getActiveCanvas().items.find('id', id); + PMUI.getActiveCanvas().addToSelection(shape.relatedObject); + } + }); + PMDesigner.validTable.columns([1]).visible(false); + /********finish datatables********/ + new PMAction({ + selector: ".mafe-validator-close", + tooltip: "Close Validator".translate(), + execute: true, + handler: function () { + $('.bpmn_validator').css('visibility', 'hidden'); + $('.mafe-toolbar-validation').css('background-color', 'rgb(233, 233, 233)'); + PMDesigner.validator = false; + } + }); + + menu = $("
"); + menu.append(option); + option.on("mouseout", function (e) { + menu.hide(); + }); + option.on("click", function (e) { + var saveas; + menu.hide(); + PMDesigner.project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id); + PMDesigner.project.save(true); + saveas = new SaveAs(); + saveas.open(); + }); + $(".mafe-button-menu").on("click", function (e) { + e.stopPropagation(); + $(".mafe-save-process").append(menu); + menu.show(); + }); + + /*----- End of Designer buttons ------*/ + /*================================================= + = Full screen functionality = + =================================================*/ + if (parent.document.documentElement === document.documentElement) { + elem = document.documentElement; + } else { + elem = parent.document.getElementById("frameMain"); + } + PMDesigner.fullScreen = new FullScreen({ + element: elem, + onReadyScreen: function () { + setTimeout(function () { + PMDesigner.resizeFrame(); + }, 500); + }, + onCancelScreen: function () { + setTimeout(function () { + PMDesigner.resizeFrame(); + }, 500); + } + }); + /*----- End of Full screen functionality ------*/ + + /*============================================= + = Shapes and Controls Box = + =============================================*/ + PMDesigner.cookie = { + name: "PMDesigner", + object: {}, + get: function (cname) { + var name = cname + "=", i, c, + ca = document.cookie.split(';'); + for (i = 0; i < ca.length; i += 1) { + c = ca[i].trim(); + if (c.indexOf(name) == 0) + return c.substring(name.length, c.length); + } + return ""; + }, + remove: function (cname) { + jQuery.each(PMDesigner.cookie.object, function (index, val) { + if (index === cname) { + delete PMDesigner.cookie.object[cname]; + PMDesigner.cookie.refresh(); + } + }); + }, + refresh: function () { + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + }; + PMDesigner.localStorage = { + prefix: "PM_" + WORKSPACE + "_" + prj_uid, + object: {}, + remove: function (cname) { + var obj; + obj = localStorage.getItem(PMDesigner.localStorage.prefix); + obj = (obj === null) ? {} : JSON.parse(obj); + if (obj[cname]) { + delete obj[cname]; + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(obj)); + } + } + }; + if (Modernizr.localstorage) { + var localDesigner = localStorage.getItem(PMDesigner.localStorage.prefix); + localDesigner = (localDesigner === null) ? {} : JSON.parse(localDesigner); + PMDesigner.panelsPosition = localDesigner; + } else { + if (PMDesigner.cookie.get(PMDesigner.cookie.name) !== "") { + var positions, pLeft, pTop, html; + positions = JSON.parse(PMDesigner.cookie.get(PMDesigner.cookie.name)); + PMDesigner.cookie.object = positions; + PMDesigner.panelsPosition = positions; + } + } + if (typeof PMDesigner.panelsPosition === "object") { + var pst = PMDesigner.panelsPosition; + if (pst.navbar) { + pLeft = pst.navbar.x; + pTop = pst.navbar.y; + html = document.getElementsByClassName("navBar")[0]; + } + if (pst.bpmn) { + pLeft = 0; + pTop = 0; + html = document.getElementsByClassName("bpmn_shapes")[0]; + html.style.left = pLeft + "px"; + html.style.top = pTop + "px"; + } + if (pst.controls) { + pLeft = pst.controls.x; + pTop = pst.controls.y; + html = document.getElementsByClassName("content_controls")[0]; + html.style.left = pLeft + "px"; + html.style.top = pTop + "px"; + if (pTop > 503) { + $("#idContent").find(".content_controls").css({'top': '', 'left': ''}); + } + } + } + jQuery(".bpmn_shapes").draggable({ + handle: "div", + start: function () { + }, + drag: function () { + }, + stop: function (event) { + var pLeft, pTop, currentObj; + pLeft = parseInt(event.target.style.left); + pTop = parseInt(event.target.style.top); + bpmn = { + bpmn: { + x: pLeft, + y: pTop + } + }; + if (Modernizr.localstorage) { + currentObj = localStorage.getItem(PMDesigner.localStorage.prefix); + currentObj = (currentObj === null) ? {} : JSON.parse(currentObj); + jQuery.extend(true, currentObj, bpmn); + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(currentObj)); + } else { + jQuery.extend(true, PMDesigner.cookie.object, bpmn); + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + } + }); + jQuery(".content_controls").draggable({ + handle: "div", + start: function () { + }, + drag: function () { + jQuery("html").css("overflow", "hidden"); + }, + stop: function (event) { + jQuery("html").css("overflow", "auto"); + if (jQuery(this).position().top > $(window).height()) { + var x = $(window).height() - 30; + jQuery(this).css({'top': x + 'px'}); + } + var pLeft, pTop, currentObj; + pLeft = parseInt(event.target.style.left); + pTop = parseInt(event.target.style.top); + if (pTop < 90) + pTop = 90; + event.target.style.setProperty("top", pTop.toString() + "px"); + controls = { + controls: { + x: pLeft, + y: pTop + } + }; + if (Modernizr.localstorage) { + currentObj = localStorage.getItem(PMDesigner.localStorage.prefix); + currentObj = (currentObj === null) ? {} : JSON.parse(currentObj); + jQuery.extend(true, currentObj, controls); + localStorage.setItem(PMDesigner.localStorage.prefix, JSON.stringify(currentObj)); + } else { + jQuery.extend(true, PMDesigner.cookie.object, controls); + document.cookie = PMDesigner.cookie.name + "=" + JSON.stringify(PMDesigner.cookie.object); + } + } + }); + /*----- End of Shapes and Controls Box ------*/ + + //Resize window + PMDesigner.resizeFrame(); + + /*============================================== + = Autosave functionality = + ==============================================*/ + PMDesigner.project.setSaveInterval(40000); + setInterval(function () { + if (PMDesigner.project.isDirty() && PMDesigner.project.readOnly === false) { + PMDesigner.project.remoteProxy.setUrl(HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + prj_uid); + PMDesigner.msgFlash('Saving Process'.translate(), document.body, 'success', 5000, 5); + PMDesigner.project.save(true); + } + }, PMDesigner.project.saveInterval); + /*----- End of Autosave functionality ------*/ + + //Reviewing functionalities + if (!PMDesigner.supportBrowser("fullscreen")) { + var li = document.getElementsByClassName("mafe-button-fullscreen"); + if (li) { + li[0].parentElement.style.display = "none"; + } + } + jQuery('.mafe-zoom-options').attr('title', 'Zoom'.translate()).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery('.mafe-toolbar-lasso').mouseover(function (e) { + $('.mafe-toolbar-lasso').css('cursor', 'pointer'); + }); + jQuery('.mafe-toolbar-validation').mouseover(function (e) { + $('.mafe-toolbar-validation').css('cursor', 'pointer'); + }); + jQuery('.mafe-toolbar-lasso').click(function (e) { + if (!PMUI.getActiveCanvas().lassoEnabled) { + $('.mafe-toolbar-lasso').css('background-color', 'rgb(207, 207, 207)'); + PMUI.getActiveCanvas().lassoEnabled = true; + } else { + $('.mafe-toolbar-lasso').css('background-color', 'rgb(233, 233, 233)'); + PMUI.getActiveCanvas().lassoEnabled = false; + } + }); + + PMDesigner.helper = new IntroHelper({ + tooltipClass: 'general', + skipLabel: 'Quit'.translate(), + + nextLabel: 'Next →'.translate(), + prevLabel: '← Back'.translate(), + doneLabel: 'Done'.translate(), + steps: [ + { + intro: '
' + }, + { + element: '#idNavBar', + intro: 'The designer bar displays the process name and is used to control the process view (zoom, full screen view), the export, undo/redo and the save button.'.translate() + }, + + { + element: '.bpmn_shapes', + intro: 'Drag and drop the process elements that you want to include in the process design.'.translate() + + '
' + ' Task: Add to include an action in your process.'.translate() + + '
' + ' Gateway: Selects a path or divides the process into multiple paths and joins them together.'.translate() + + '
' + ' Start Event: The process always begins with a start event.'.translate() + + '
' + ' Intermediate Event: Used to define an event that happens in the middle of the process.'.translate() + + '
' + ' End Event: End the execution of the process.'.translate() + + '
' + ' Pool: Place each process in a separate pool.'.translate() + + '
' + ' Lane: Used to divide a process into different sections.'.translate() + }, + { + element: '#div-layout-canvas', + intro: "In the design area you can drop the process elements and order or arrange them to design your process.".translate() + }, + { + element: '.content_controls', + intro: '

' + + 'The process objects are used to add execution features to the current process design.'.translate() + + '
Variables: Define the process data.'.translate() + + '
Dynaforms: Create dynamic forms.'.translate() + + '
Triggers: Create scripts.'.translate() + + '
Output documents: Generate documents with process data.'.translate() + + '
DB connections: Connect to external databases.'.translate() + + '

', + position: 'left' + }, + { + intro: '
' + 'Select an element in the designer to display the quick toolbar with the list of the most used options available for that element.'.translate() + '
' + } + ], + onExit: function () { + var canvas = PMUI.getActiveCanvas(); + if (canvas && canvas.getGridLine() && canvas.getHTML()) { + canvas.getHTML().classList.add("pmui-pmcanvas"); + } + } + }); + + jQuery('.mafe-toolbar-validation').click(function (e) { + if (!PMDesigner.validator) { + $('.mafe-toolbar-validation').css('background-color', 'rgb(207, 207, 207)'); + PMDesigner.validator = true; + } else { + $('.bpmn_validator').css('visibility', 'hidden'); + $('.mafe-toolbar-validation').css('background-color', 'rgb(233, 233, 233)'); + PMDesigner.validator = false; + } + }); + if (inArray("jXsSi94bkRUcVZyRStNVExlTXhEclVadGRRcG9xbjNvTWVFQUF3cklKQVBiVT0=", ENABLED_FEATURES)) { + $("#idNavBar").find(".mafe-button-export-process").html( + $("#idNavBar").find(".mafe-button-export-process").text() + " ▼" + ); + } + + function inArray(needle, haystack) { + var i, + length = haystack.length; + for (i = 0; i < length; i += 1) { + if (haystack[i] == needle) return true; + } + return false; + } +}); + +window.onload = function () { + //Reset the scroll positions + window.scrollBy(-window.scrollX, -window.scrollY); + document.onkeydown = function (e) { + if (e.keyCode === 8 && e.target === document.body) { + e.stopPropagation(); + return false; + } + }; +}; +/*================================================== + = Components from the Panels = + ==================================================*/ + +PMDesigner.createHTML = function () { + var minShapes = document.createElement("span"), + minShapesLegend = document.createElement("span"), + refreshShapes = document.createElement("span"), + minControls = document.createElement("span"), + processObjects = document.createElement("span"), + refreshControls = document.createElement("span"), + refreshNavBar = document.createElement("span"); + minShapes.id = "minShapes"; + minShapesLegend.id = "minShapesLegend"; + refreshShapes.id = "resetShapes"; + minControls.id = "minControls"; + refreshControls.id = "resetControls"; + refreshNavBar.id = "resetNavBar"; + minShapes.className = "mafe-shapes-toggle"; + minShapesLegend.className = "mafe-shapes-toggle"; + refreshShapes.className = "mafe-shapes-refresh"; + minControls.className = "mafe-shapes-toggle"; + processObjects.className = "mafe-process-object"; + refreshControls.className = "mafe-shapes-refresh"; + refreshNavBar.className = "mafe-shapes-refresh"; + minShapes.title = "Minimize".translate(); + minShapesLegend.title = "Minimize".translate(); + refreshShapes.title = "reset".translate(); + minControls.title = "Minimize".translate(); + refreshControls.title = "Reset to original position".translate(); + refreshNavBar.title = "reset".translate(); + + jQuery(minShapes).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(minShapesLegend).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshShapes).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(minControls).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshControls).tooltip({tooltipClass: "mafe-action-tooltip"}); + jQuery(refreshNavBar).tooltip({tooltipClass: "mafe-action-tooltip"}); + + refreshControls.style.backgroundPosition = '0px 0px'; + processObjects.textContent = "Process Objects".translate(); + + minShapes.onclick = function () { + var i, + items = jQuery(".bpmn_shapes > ul"); + if (items.length > 0) { + for (i = 0; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + } + + } + } + }; + minShapesLegend.onclick = function () { + var i, + items = jQuery(".bpmn_shapes_legend").children(); + for (i = 1; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + } + } + }; + refreshShapes.onclick = function () { + jQuery(".bpmn_shapes").removeAttr('style'); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("bpmn"); + } else { + PMDesigner.cookie.remove("bpmn"); + } + }; + minControls.onclick = function () { + var i, + title = '', + items = jQuery(".content_controls > ul"); + + if (items.length > 0) { + for (i = 0; i < items.length; i += 1) { + if (jQuery(items[i]).css("display").toLowerCase() !== "none") { + jQuery(items[i]).css({ + display: 'none' + }); + title = "Maximize"; + $('#minControls').removeClass('mafe-shapes-toggle'); + $('#minControls').addClass('mafe-shapes-plus'); + } else { + jQuery(items[i]).css({ + display: 'block' + }); + title = "Minimize"; + $('#minControls').removeClass('mafe-shapes-plus'); + $('#minControls').addClass('mafe-shapes-toggle'); + + } + } + } + jQuery(minControls).tooltip({content: title.translate()}); + }; + refreshControls.onclick = function () { + jQuery(".content_controls").css({ + left: "auto", + right: "20px", + top: "90px" + }); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("controls"); + } else { + PMDesigner.cookie.remove("controls"); + } + }; + refreshNavBar.onclick = function () { + jQuery(".navBar").removeAttr('style'); + if (Modernizr.localstorage) { + PMDesigner.localStorage.remove("navbar"); + } else { + PMDesigner.cookie.remove("navbar"); + } + }; + + + jQuery(".bpmn_shapes>div").append(minShapes); + jQuery(".bpmn_shapes>div").append(refreshShapes); + jQuery(".content_controls>div").append(processObjects); + jQuery(".content_controls>div").append(minControls); + jQuery(".content_controls>div").append(refreshControls); + jQuery(".navBar>div").append(refreshNavBar); + jQuery(".bpmn_shapes_legend>div").append(minShapesLegend); + jQuery(".bpmn_shapes, .content_controls").on("contextmenu", function (e) { + e.preventDefault(); + }); + + PMDesigner.applyCanvasOptions(); + +}; + +/*----- End of Components from the Panels ------*/ + +/*===================================================== + = Get information about browser = + =====================================================*/ +PMDesigner.getBrowser = function () { + var match, + ua = navigator.userAgent.toLowerCase(); + if (ua) { + match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[1] || "", + version: match[2] || "0" + }; + } +}; +/*----- End of Get information about browser ------*/ + +PMDesigner.supportBrowser = function (functionality) { + var browser, el, module; + functionality = functionality.toLowerCase(); + switch (functionality) { + case "fullscreen": + browser = PMDesigner.getBrowser(); + if ((browser.browser === "msie") && (parseInt(browser.version, 10) <= 10)) { + try { + module = new ActiveXObject("WScript.Shell"); + } catch (e) { + module = false; + } + } else { + el = document.documentElement; + module = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen; + if (!module) { + module = false; + } + } + break; + case "": + break; + } + return module; +}; + +/*============================================================ + = Leave the current page Functionality = + ============================================================*/ +window.onbeforeunload = function (e) { + var message; + if ((PMDesigner.project.isDirty() + && !PMDesigner.project.readOnly) + || PMDesigner.project.isSave) { + message = "There are unsaved changes, if you leave the editor some changes won't be saved.".translate(); + e = e || window.event; + if (e) { + e.returnValue = message; + } + return message; + } +}; +/*----- End of Leave the current page Functionality ------*/ + +/*===================================================================== + = Validating coordinates for create a new shape = + =====================================================================*/ +PMUI.validCoordinatedToCreate = function (canvas, event, shape) { + var position, p, width, height, createElem = true, panels = [], message; + //navBar panel + position = jQuery(".navBar").offset(); + width = jQuery(".navBar").width(); + height = jQuery(".navBar").height(); + element = { + x1: position.left, + y1: position.top, + x2: position.left + width, + y2: position.top + height + }; + panels.push(element); + //BPMN panel + position = jQuery(".bpmn_shapes").offset(); + width = jQuery(".bpmn_shapes").width(); + height = jQuery(".bpmn_shapes").height(); + element = { + x1: position.left, + y1: position.top, + x2: position.left + width, + y2: position.top + height + }; + if (panels.length > 0) { + for (p = 0; p < panels.length; p += 1) { + if (((event.pageX >= panels[p].x1) && (event.pageX <= panels[p].x2)) + && ((event.pageY >= panels[p].y1) && (event.pageY <= panels[p].y2))) { + PMDesigner.msgFlash('Is not possible create the element in that area'.translate(), document.body, 'info', 3000, 5); + return false; + } + } + } + + return true; +}; +/*----- End of Validating coordinates for create a new shape ------*/ + +PMUI.pageCoordinatesToShapeCoordinates = function (shape, e, xCoord, yCoord, customShape) { + var coordinates, + x = (!xCoord) ? e.pageX : xCoord, + y = (!yCoord) ? e.pageY : yCoord, + orgX = (!xCoord) ? e.pageX : xCoord, + orgY = (!yCoord) ? e.pageY : yCoord, + canvas = shape.getCanvas(); + x += canvas.getLeftScroll() - shape.getAbsoluteX() - canvas.getX(); + y += canvas.getTopScroll() - shape.getAbsoluteY() - canvas.getY(); + coordinates = new PMUI.util.Point(x, y); + return coordinates; +}; + +PMDesigner.msgFlash = function (text, container, severity, duration, zorder) { + var msg; + if (!PMDesigner.currentMsgFlash) { + msg = new PMUI.ui.FlashMessage({ + id: '__msgFlashMessage', + severity: 'success' + }); + } else { + msg = PMDesigner.currentMsgFlash; + } + if (msg.html) + jQuery(msg.html).remove(); + msg.setMessage(text || ""); + msg.setAppendTo(container || document.body); + msg.setSeverity(severity || "success"); + msg.setDuration(duration || 3000); + msg.setZOrder(zorder || 100); + msg.show(); + PMDesigner.currentMsgFlash = msg; +}; + +PMDesigner.msgWinError = function (text) { + var msgError; + if (!PMDesigner.currentWinError) { + msgError = new PMUI.ui.MessageWindow({ + id: 'showMessageWindowFailure', + width: 490, + windowMessageType: 'error', + title: 'Error'.translate(), + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + msgError.close(); + }, + buttonType: "success" + } + ] + }); + } else { + msgError = PMDesigner.currentWinError; + } + msgError.setMessage(text || 'Error'.translate()); + msgError.showFooter(); + msgError.open(); + PMDesigner.currentWinError = msgError; +}; + +PMDesigner.msgWinWarning = function (text) { + var msgWarning; + if (!PMDesigner.currentWinWarning) { + msgWarning = new PMUI.ui.MessageWindow({ + id: 'showMessageWindowWarning', + windowMessageType: 'warning', + width: 490, + title: 'Warning'.translate(), + footerItems: [{ + text: 'Ok'.translate(), + buttonType: "success", handler: function () { + msgWarning.close(); + } + }] + }); + } else { + msgWarning = PMDesigner.currentWinWarning; + } + msgWarning.setMessage(text || 'Warning'.translate()); + msgWarning.showFooter(); + msgWarning.open(); + PMDesigner.currentWinWarning = msgWarning; +}; + +PMDesigner.modeReadOnly = function () { + var restClient; + if (prj_readonly === 'true') { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'cases/' + app_uid + '/tasks', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var viewTaskInformation = new ViewTaskInformation(); + viewTaskInformation.setData(response[0].response); + viewTaskInformation.setShapes(); + viewTaskInformation.showViewLegendsInformation(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + } +}; + +PMDesigner.reloadDataTable = function () { + $('.bpmn_validator').css('visibility', 'visible'); +}; + +/** + * Escape XML characters method. + * There are only five: + * " " + * ' ' + * < < + * > > + * & & + * + * @param {string} label + * @returns {string} + */ +PMDesigner.escapeXMLCharacters = function (label) { + return label + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(/'/g, "'") + .replace(//g, ">"); +}; + +DataDictionary = function () { +}; +DataDictionary.prototype.getColor = function (value) { + switch (value) { + case 'TASK_IN_PROGRESS': + return 'red'; + case 'TASK_COMPLETED': + return 'green'; + case 'TASK_PENDING_NOT_EXECUTED': + return 'silver'; + case 'TASK_PARALLEL': + return 'orange'; + default: + return 'white'; + } +}; +DataDictionary.prototype.getStatus = function (value) { + switch (value) { + case 'TASK_IN_PROGRESS': + return 'Task in Progress'.translate(); + case 'TASK_COMPLETED': + return 'Completed Task'.translate(); + case 'TASK_PENDING_NOT_EXECUTED': + return 'Pending Task / Not Executed'.translate(); + case 'TASK_PARALLEL': + return 'Parallel Task'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasAssignType = function (value) { + switch (value) { + case 'BALANCED': + return 'Balanced'.translate(); + case 'MANUAL': + return 'Manual'.translate(); + case 'REPORT_TO': + return 'Report toO'.translate(); + case 'EVALUATE': + return 'Evaluate'.translate(); + case 'SELF_SERVICE': + return 'self Service'.translate(); + case 'SELF_SERVICE_EVALUATE': + return 'Self Service Evaluate'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasType = function (value) { + switch (value) { + case 'NORMAL': + return 'Normal'.translate(); + case 'SUBPROCESS': + return 'Sub Process'.translate(); + default: + return value; + } +}; +DataDictionary.prototype.getTasDerivation = function (value) { + switch (value) { + case 'NORMAL': + return 'Normal'.translate(); + default: + return value; + } +}; + +ViewTaskInformation = function (settings) { + ViewTaskInformation.prototype.init.call(this, settings); +}; +ViewTaskInformation.prototype.init = function () { + var that = this, + panelButton = new PMUI.core.Panel({ + layout: 'hbox', + items: [ + that.getButton('Information', function () { + that.showInformation(); + }), + that.getButton('Delegations', function () { + that.showDelegations(); + }), + that.getButton('Route', function () { + that.showRoute(); + }) + ] + }); + that.windowAbstract.showFooter(); + that.windowAbstract.addItem(panelButton); + that.windowAbstract.addItem(that.panelvertical); +}; +ViewTaskInformation.prototype.dataDictionary = new DataDictionary(); +ViewTaskInformation.prototype.data = null; +ViewTaskInformation.prototype.shapeData = null; +ViewTaskInformation.prototype.panelvertical = new PMUI.core.Panel({layout: 'vbox', width: 400}); +ViewTaskInformation.prototype.windowAbstract = new PMUI.ui.Window({id: 'windowAbstract', width: 500, height: 350}); +ViewTaskInformation.prototype.setData = function (data) { + this.data = data; +}; +ViewTaskInformation.prototype.setCursor = function (shape) { + shape.getHTML().onmouseover = function () { + this.style.cursor = 'pointer'; + }; + shape.getHTML().onmouseout = function () { + this.style.cursor = ''; + }; +}; +ViewTaskInformation.prototype.setShapes = function () { + var that = this, + shape, + diagrams, + i, + j, + dt = that.data; + for (i = 0; i < dt.length; i += 1) { + diagrams = PMDesigner.project.diagrams.asArray(); + for (j = 0; j < diagrams.length; j += 1) { + shape = diagrams[j].getCustomShapes().find('id', dt[i].tas_uid); + if (typeof shape != "undefined" && shape != null) { + shape.changeColor(that.dataDictionary.getColor(dt[i].status)); + shape.data = dt[i]; + shape.hasClick = function (event) { + that.setShapeData(this.data); + that.showInformation(); + }; + that.setCursor(shape); + } + } + } +}; +ViewTaskInformation.prototype.setShapeData = function (data) { + this.shapeData = data; +}; +ViewTaskInformation.prototype.addRowNewLine = function (label, value) { + var panelhorizontal = new PMUI.core.Panel({ + layout: 'hbox' + }); + panelhorizontal.addItem(new PMUI.ui.TextLabel({text: ''})); + this.panelvertical.addItem(panelhorizontal); + return panelhorizontal; +}; +ViewTaskInformation.prototype.addRow = function (label, value) { + var field1, field2, field3, panelhorizontal; + + field1 = new PMUI.ui.TextLabel({text: label.translate(), proportion: 0.3}); + field2 = new PMUI.ui.TextLabel({text: ':', proportion: 0.1}); + field3 = new PMUI.ui.TextLabel({text: value ? value + '' : '', proportion: 0.6}); + + panelhorizontal = new PMUI.core.Panel({ + layout: 'hbox' + }); + + panelhorizontal.addItem(field1); + panelhorizontal.addItem(field2); + panelhorizontal.addItem(field3); + this.panelvertical.addItem(panelhorizontal); + return panelhorizontal; +}; +ViewTaskInformation.prototype.clearRows = function () { + this.panelvertical.clearItems(); +}; +ViewTaskInformation.prototype.showInformation = function () { + var that = this; + that.clearRows(); + that.addRow('Title'.translate(), that.shapeData.tas_title); + that.addRow('Description'.translate(), that.shapeData.tas_description); + that.addRow('Status'.translate(), that.dataDictionary.getStatus(that.shapeData.status)); + that.addRow('Type'.translate(), that.dataDictionary.getTasType(that.shapeData.tas_type)); + that.addRow('Assign type'.translate(), that.dataDictionary.getTasAssignType(that.shapeData.tas_assign_type)); + that.addRow('Routing'.translate(), that.dataDictionary.getTasDerivation(that.shapeData.tas_derivation)); + that.addRow('Start'.translate(), that.shapeData.tas_start); + that.addRowNewLine(); + that.addRow('Last User Name'.translate(), that.shapeData.usr_username); + that.addRow('Last User'.translate(), that.shapeData.usr_firstname + ' ' + that.shapeData.usr_lastname); + + that.windowAbstract.setTitle('Information'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.showDelegations = function () { + var that = this, i, dt; + that.clearRows(); + dt = that.shapeData.delegations; + for (i = 0; i < dt.length; i += 1) { + that.addRow('User', dt[i].usr_username); + that.addRow('User Name', dt[i].usr_firstname + ' ' + dt[i].usr_lastname); + that.addRow('Duration', dt[i].del_duration); + that.addRow('Finish Date', dt[i].del_finish_date); + that.addRow('Index', dt[i].del_index); + that.addRow('Init Date', dt[i].del_init_date); + that.addRow('Task Due Date', dt[i].del_task_due_date); + that.addRowNewLine(); + } + + that.windowAbstract.setTitle('Delegations'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.showRoute = function () { + var that = this, i, dt; + that.clearRows(); + that.addRow('Type', that.shapeData.route.type); + that.addRowNewLine(); + dt = that.shapeData.route.to; + for (i = 0; i < dt.length; i += 1) { + that.addRow('Condition', dt[i].rou_condition); + that.addRow('Number', dt[i].rou_number); + that.addRowNewLine(); + } + + that.windowAbstract.setTitle('Route'.translate() + ' ' + that.shapeData.tas_title); + that.windowAbstract.open(); + that.windowAbstract.body.style.padding = '20px'; +}; +ViewTaskInformation.prototype.getButton = function (text, fn) { + return new PMUI.ui.Button({ + text: text.translate(), + width: 180, + height: 50, + style: { + cssProperties: { + marginRight: 10, + marginBottom: 10, + backgroundColor: '#474747', + borderRadius: 5, + padding: 5 + }, + cssClasses: ['mafeButton'] + }, + handler: fn + }); +}; +ViewTaskInformation.prototype.showViewLegendsInformation = function () { + var i, dt, legend, legendIcon, legendText; + $('.bpmn_shapes_legend').show(); + + i; + dt = [ + ['red', 'Task in Progress'.translate()], + ['green', 'Completed Task'.translate()], + ['silver', 'Pending Task / Not Executed'.translate()], + ['orange', 'Parallel Task'.translate()] + ]; + for (i = 0; i < dt.length; i += 1) { + legend = $("
"); + legendIcon = $("
").addClass("mafe-activity-task-" + dt[i][0]).addClass("icon-legend"); + legendText = $("
" + dt[i][1] + "
").addClass("text-legend"); + legend.append(legendIcon).append(legendText); + jQuery(".bpmn_shapes_legend").append(legend); + } + + jQuery(".bpmn_shapes_legend").draggable({ + handle: "div", + start: function () { + }, + drag: function (event, e, u) { + }, + stop: function (event) { + + } + }); +}; + +(function () { + /** + * @class PMUI.menu.ContextMenu + * Handles the context menu of designer + * contains all the menus for elements + * + * @extend PMUI.util.Factory + * @constructor + * This method creates a new instance of this object + * @param {Object} [settings] Constructor settings + */ + "use strict"; + var ContextMenu = function (settings) { + this.factory = null; + ContextMenu.prototype.init.call(this, settings); + }; + + ContextMenu.prototype.type = 'ContextMenu'; + + ContextMenu.prototype.family = 'ContextMenu'; + + /** + * Initializes the object. + * @param {Object} settings A JSON object with the config options. + * @private + */ + ContextMenu.prototype.init = function (settings) { + jQuery.extend(true, defaults, settings); + this.factory = new PMUI.util.Factory(defaults.factory); + }; + + /** + * Register a new context menu object into a product. + * + * Usage example: + * @example + * //Remember, this is an abstract class so it shouldn't be instantiate, + * //anyway we are instantiating it just for this example + * var additionalMenu = { + * id: "additionalMenu", + * text: "New Menu", + * onClick: function () { + * PMDesigner.msgWinWarning('This is a new Menu'); + * } + * }; + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * PMDesigner.contextMenuFactory.registerMenu("CANVAS", additionalMenu); + * + * @param {String} productName Name of the shape or product in factory. + * @param {Object} menu Object with menu values and actions. + * @private + */ + ContextMenu.prototype.registerMenu = function (productName, menu) { + if (typeof this.factory.products[productName] === 'undefined') { + console.log('Context Menu Warning: Cannot add Menu into: ' + productName + '. Please, review name.'); + } else { + if (this.factory.products[productName].items instanceof Array) { + this.factory.products[productName].items.push(menu); + } + } + }; + + /** + * Removes context menu object from product. + * + * Usage example: + * @example + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * // this example removes Canvas gridLines option + * PMDesigner.contextMenuFactory.removeMenu("CANVAS", "id", "menuGridLines"); + * + * @param {String} product Name of the shape or product in factory. + * @param {String} id Key to look through product. + * @param {String} value Name of the elementValue. + * @private + */ + ContextMenu.prototype.removeMenu = function (product, id, value) { + if (typeof this.factory.products[product] !== 'undefined') { + this.factory.products[product].items = _.reject(this.factory.products[product].items, function (menuValue) { + return menuValue[id] === value; + }); + } else { + console.log('Context Menu Warning: Cannot find ' + product + ' Menu. Please, review name.'); + } + }; + + /** + * Returns specific product. + * @param {String} type Name of product. + * @private + */ + ContextMenu.prototype.getProduct = function (type) { + return this.factory.products[type]; + }; + + var menuMessages = { + 'START': { + 'TIMER': 'Please configure cron to create cases.'.translate(), + 'CONDITIONAL': 'Please configure cron to create cases in base to a condition.'.translate(), + 'SIGNALCATCH': 'Please configure cron to create cases in base to a signal.'.translate() + }, + 'INTERMEDIATE': { + 'CATCH': { + 'TIMER': 'Please configure cron to wait for time event.'.translate(), + 'CONDITIONAL': 'Please configure cron to wait for time condition.'.translate(), + 'SIGNALCATCH': 'Please configure script to wait for a signal.'.translate() + }, + 'THROW': { + 'SIGNALTHROW': 'Please configure a script to send a signal.'.translate() + } + }, + 'END': { + 'ERRORTHROW': 'Please configure script to end with error status.'.translate(), + 'SIGNALTHROW': 'Please configure script to send a signal.'.translate(), + 'TERMINATETHROW': 'Please configure script to terminate case.'.translate() + } + }, + menu = {}, + rootMenu, + elementActivite, + typeMenu = { + text: "Gateway Type".translate(), + icon: "mafe-menu-properties-action", + id: "gatewaytype", + items: [ + { + id: "gatewayexclusive", + text: "Exclusive (XOR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('EXCLUSIVE'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayparallel", + text: "Parallel (AND) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('PARALLEL'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayinclusive", + text: "Inclusive (OR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('INCLUSIVE'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + endMarker = { + text: "End Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "endempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endmessagethrow", + text: "Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "enderrorthrow", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORTHROW', 'Error'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endsignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endterminatethrow", + text: "Terminate".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TERMINATETHROW', 'Terminate'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + intermediateCatchMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "intermediatemessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatetimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediateconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + boundaryCatchMarker = { + text: "Boundary Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "eventType", + items: [ + { + id: "messageCatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + } + }, + { + id: "boundaryTimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + } + }, + { + id: "BoudaryConditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + } + }, + { + id: "BoudarySignal", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + } + }, + { + id: "BoudaryError", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORCATCH', 'Error'); + } + } + ] + }, + intermediateThrowMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "intermediateemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatemessagethrow", + text: "Send Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Send Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + startCatchMarker = { + text: "Start Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "startempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startmessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "starttimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startsignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + } + ] + }, + canvas = { + id: "menuCanvas", + width: 150, + items: [ + { + id: "menuEditProcess", + text: "Edit Process".translate(), + onClick: function (menuOption) { + PMDesigner.propertiesProcess(); + } + }, + { + id: "menuGridLines", + text: "Enable Grid Lines".translate(), + onClick: function () { + var canvas = PMUI.getActiveCanvas(); + if (canvas.toogleGridLine()) { + this.setText("Disable Grid Lines".translate()); + } else { + this.setText("Enable Grid Lines".translate()); + } + } + } + ], + onShow: function (menu) { + var canvas = PMUI.getActiveCanvas(); + if (canvas.currentConnection) { + canvas.currentConnection.hidePortsAndHandlers(); + } + if (canvas.isGridLine) { + menu.items.find('id', 'menuGridLines').setText("Disable Grid Lines".translate()); + } + + } + }, + task = { + id: "menuTask", + items: [ + { + id: "taskType", + text: "Task Type".translate(), + items: [ + { + id: "empty", + text: "Empty Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "sendtask", + text: "Send Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "receivetask", + text: "Receive Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "usertask", + text: "User Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "servicetask", + text: "Service Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "scripttask", + text: "Script Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "manualtask", + text: "Manual Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "businessrule", + text: "Business Rule Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + } + ] + }, + { + id: "loopType", + text: "Marker Type".translate(), + items: [ + { + id: "empty", + text: "None".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "loop", + text: "Loop".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "parallel", + text: "Parallel".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "sequential", + text: "Sequential".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + } + ] + }, + { + id: "menuTaskSteps", + text: "Steps".translate(), + icon: "mafe-menu-task-steps", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + } + } + }, + { + id: "menuTaskAssignedRules", + text: "Assignment Rules".translate(), + icon: "mafe-menu-users-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuTaskProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + + if (targetElement.act_task_type == "SCRIPTTASK") { + menu.getItems()[1].setVisible(false); + menu.getItems()[2].setVisible(false); + menu.getItems()[3].setVisible(false); + } else { + menu.getItems()[1].setVisible(true); + menu.getItems()[2].setVisible(true); + menu.getItems()[3].setVisible(true); + } + + if (targetElement.act_task_type == "MANUALTASK" || targetElement.act_task_type == "USERTASK" || targetElement.act_task_type == "EMPTY") { + menu.getItems()[1].getItems()[2].setVisible(true); + } else { + menu.getItems()[1].getItems()[2].setVisible(false); + } + } + }, + subProcess = { + id: "menuSubProcess", + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas + .hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete Routing Rule".translate(), + icon: "mafe-menu-delete-rules-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuSubProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + } + }, + start = { + id: 'menuStart', + items: [ + startCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuStartWebEntry", + text: "Web Entry".translate(), + icon: "mafe-menu-start-message-view", + //visible: false, + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"), webEntry; + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + var webEntry; + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + } + } + }, + { + id: "menuStartProperties", + text: "Properties".translate(), + icon: "mafe-menu-start-message-view", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + shape, + propertyMap = ['MESSAGECATCH', 'TIMER']; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (targetElement.evn_marker == 'TIMER') { + } + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (targetElement.evn_marker === 'MESSAGECATCH') { + var dt = menu.getItems(); + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(true); + } + } + } + //disabled weebentry for others pmEvent no support + if (targetElement.getPorts().asArray().length) { + shape = targetElement.getPorts().getFirst().getConnection().getDestPort().parent; + if (shape && (shape instanceof PMActivity) && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else if (shape && (shape instanceof PMEvent) && shape.evn_marker === "EMAIL" + && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + + //Enable && Disabled - Properties + if (targetElement.evn_type === "START" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuStartProperties').enable(); + } else { + menu.items.find('id', 'menuStartProperties').disable(); + } + }, + onHide: function (menu) { + var dt = menu.getItems(), i; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(false); + } + } + } + }, + end = { + id: 'menuEnd', + items: [ + endMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuEndProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var propertyMap = ['MESSAGETHROW', 'EMAIL'], + targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + + + //Enable && Disabled - Properties + if (targetElement.evn_type === "END" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuEndProperties').enable(); + } else { + menu.items.find('id', 'menuEndProperties').disable(); + } + } + }, + selection = { + id: 'menuSelection', + items: [ + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action" + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action" + } + ] + }, + evaluation = { + id: 'menuEvaluation', + items: [ + + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + } + ] + }, + parallel = { + id: 'menuParallel', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + listeners: {}, + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + } + }, + exclusive = { + id: 'menuExclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + + } + }, + inclusive = { + id: 'menuInclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: 'Properties'.translate(), + icon: 'mafe-menu-properties-action', + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + } + }, + complex = { + id: 'menuComplex', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.complexRoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + group = { + id: 'menuLine', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataObject = { + id: 'menuDataObject', + items: [ + { + id: "dataType", + text: "Data Type".translate(), + items: [ + { + id: "dataobject", + text: "Data Empty".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOBJECT'); + } + }, + { + id: "datainput", + text: "Data Input".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAINPUT'); + } + }, + { + id: "dataoutput", + text: "Data Output".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOUTPUT'); + } + } + ] + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataStore = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + textAnnotation = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + intermediate = { + id: 'intermediate', + items: [ + intermediateCatchMarker, + intermediateThrowMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "intermediateProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + propertyEnabled = ['MESSAGECATCH', 'MESSAGETHROW', 'EMAIL', 'TIMER']; + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (targetElement.evn_behavior === 'CATCH') { + targetElement.menu.getItems()[0].setVisible(true); + targetElement.menu.getItems()[1].setVisible(false); + } else { + targetElement.menu.getItems()[0].setVisible(false); + targetElement.menu.getItems()[1].setVisible(true); + } + + //Enable && Disabled - Properties + if (propertyEnabled.indexOf(targetElement.evn_marker) >= 0) { + + menu.items.find('id', 'intermediateProperties').enable(); + } else { + menu.items.find('id', 'intermediateProperties').disable(); + } + } + }, + boundary = { + id: 'menuDataObject', + items: [ + boundaryCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + } + }, + participant = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }; + var defaults = { + factory: { + products: { + 'CANVAS': canvas, + 'TASK': task, + 'SUB_PROCESS': subProcess, + 'START': start, + 'END': end, + 'SELECTION': selection, + 'EVALUATION': evaluation, + 'PARALLEL': parallel, + 'EXCLUSIVE': exclusive, + 'EVENTBASED': exclusive, + 'EXCLUSIVEEVENTBASED': exclusive, + 'PARALLELEVENTBASED': exclusive, + 'INCLUSIVE': inclusive, + 'COMPLEX': complex, + 'VERTICAL_LINE': group, + 'HORIZONTAL_LINE': group, + 'GROUP': group, + 'LANE': participant, + 'DATAOBJECT': dataObject, + 'DATASTORE': dataStore, + 'TEXT_ANNOTATION': textAnnotation, + 'V_LABEL': textAnnotation, + 'H_LABEL': textAnnotation, + 'INTERMEDIATE': intermediate, + 'BOUNDARY': boundary, + 'PARTICIPANT': participant, + 'POOL': participant + }, + + defaultProduct: 'START' + } + }; + + PMDesigner.contextMenuFactory = new ContextMenu(defaults.factory); + PMDesigner.getMenuFactory = function (type) { + if (prj_readonly === 'true') { + return {}; + } + return PMDesigner.contextMenuFactory.getProduct(type); + }; + /** + * Change task type marker + * @param menuOption + */ + function handlerMarkerType(menuOption) { + var result = true, + tempType = menuOption.getMenuTargetElement().getTaskType(); + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().switchTaskType(menuOption.id.toUpperCase()); + + //validate if act loop type is parallel + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + handlerMarkerLoopType(menuOption, tempType) + } + + //to enable save button + PMDesigner.project.updateElement([]); + + } + + /** + * Change marker loop type + * @param menuOption + * @param type + * @returns {boolean} + */ + function handlerMarkerLoopType(menuOption, type) { + var message_window, + loopType = menuOption.id.toUpperCase(), + taskType = menuOption.getMenuTargetElement().act_task_type; + if (typeof type !== 'undefined' && type !== null) { + taskType = type; + } + + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + + message_window = new PMUI.ui.MessageWindow({ + id: "handlerMarkerType", + width: 490, + title: 'Parallel Marker Type'.translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: "The configuring of multiple instances will be lost".translate(), + footerItems: [ + { + text: 'Cancel'.translate(), + handler: function () { + menuOption.getMenuTargetElement().switchLoopType('PARALLEL'); + menuOption.getMenuTargetElement().switchTaskType(taskType); + message_window.close(); + return false; + }, + buttonType: "error" + }, + { + text: 'Continue'.translate(), + handler: function () { + try { + if (loopType == "loop" || loopType == "sequential") { + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + } else { + menuOption.getMenuTargetElement().switchLoopType('EMPTY'); + } + PMDesigner.project.updateElement([]); + } catch (e) { + console.error("loop marker error", e.message); + } + message_window.close(); + return true; + }, + buttonType: "success" + } + + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + PMDesigner.project.updateElement([]); + return true; + } + } + +}()); + +(function () { + PMDesigner.shapeFactory = function (type, options) { + var customshape = null, + menuShape, + defaultOptions = null, + canvasName, + name, + id, + classEvent = "start", + pmCanvas = this.canvas, + corona = PMDesigner.defaultCrown, + wildcard; + + canvasName = new IncrementNameCanvas(pmCanvas); + name = canvasName.get(type); + + if (typeof options === 'undefined') { + options = {}; + if (type === 'START_MESSAGE') { + type = 'START'; + classEvent = "message"; + options.evn_marker = 'MESSAGECATCH'; + } + if (type === 'START_TIMER') { + type = 'START'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } + + if (type === 'END_MESSAGE') { + type = 'END'; + classEvent = "message"; + options.evn_marker = 'MESSAGETHROW'; + } + if (type === 'END_EMAIL') { + type = 'END'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_SENDMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "sendmessage"; + options.evn_marker = 'MESSAGETHROW'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_RECEIVEMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "receivemessage"; + options.evn_marker = 'MESSAGECATCH'; + options.evn_behavior = 'CATCH'; + } + if (type === 'INTERMEDIATE_EMAIL') { + type = 'INTERMEDIATE'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_TIMER') { + type = 'INTERMEDIATE'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } + if (type === 'BOUNDARY_EVENT') { + type = 'BOUNDARY'; + classEvent = "receivemessage"; + options.evn_marker = 'EMPTY'; + options.evn_behavior = 'CATCH'; + } + + switch (type) { + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': + options.gat_type = type; + break; + } + } + if (type === 'DATAOBJECT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataobject'; + } + if (type === 'DATAINPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'datainput'; + } + if (type === 'DATAOUTPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataoutput'; + } + + wildcard = [ + { + name: 'wildcard'.translate(), + className: 'mafe-wildcard', + onClick: null, + column: 2 + } + ]; + + switch (type) { + case 'TASK': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'TASK', + act_name: name, + act_task_type: 'EMPTY', + act_loop_type: 'EMPTY', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ + { + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-task' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'USERTASK', + x: 10, + y: 10, + position: 0, + markerZoomClasses: [] + }, + { + markerType: 'EMPTY', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [] + } + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ], + markerZoomClassesWarning: [ + "mafe-style-warning-marker-7", + "mafe-style-warning-marker-10", + "mafe-style-warning-marker-14", + "mafe-style-warning-marker-17", + "mafe-style-warning-marker-21" + ] + } + } + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + defaultOptions.markers[1] + .markerZoomClasses = PMDesigner.updateLoopLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'SUB_PROCESS': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'SUB_PROCESS', + act_loop_type: 'EMPTY', + act_name: name, + act_task_type: 'COLLAPSED', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ + { + message: name, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-subprocess' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'COLLAPSED', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [ + "mafe-collapsed-marker-10", + "mafe-collapsed-marker-15", + "mafe-collapsed-marker-21", + "mafe-collapsed-marker-26", + "mafe-collapsed-marker-31" + ] + } + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'START': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'START', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'catch', + evn_message: 'LEAD', + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-start'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-start-empty-16', + 'mafe-event-start-empty-24', + 'mafe-event-start-empty-33', + 'mafe-event-start-empty-41', + 'mafe-event-start-empty-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + case 'INTERMEDIATE': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'INTERMEDIATE', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-intermediate'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + case 'BOUNDARY': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'BOUNDARY', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + style: { + cssClasses: ['mafe-event-boundary'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + drag: 'nodrag' + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + + case 'END': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'END', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'throw', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + style: { + cssClasses: ['mafe-event-end'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-end-empty-16', + 'mafe-event-end-empty-24', + 'mafe-event-end-empty-33', + 'mafe-event-end-empty-41', + 'mafe-event-end-empty-49' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 + } + } + ], + canvas: pmCanvas, + width: 41, + height: 41, + gat_type: 'EXCLUSIVE', + gat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-gateway-exclusive-20', + 'mafe-gateway-exclusive-30', + 'mafe-gateway-exclusive-41', + 'mafe-gateway-exclusive-51', + 'mafe-gateway-exclusive-61' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } + } + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateGatewayLayerClasses(defaultOptions); + customshape = new PMGateway(defaultOptions); + break; + case 'GROUP': + defaultOptions = { + art_name: name, + art_type: 'GROUP', + canvas: pmCanvas, + width: 200, + height: 100, + style: { + cssClasses: ['mafe-artifact-group'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "background-layer", + priority: 1, + visible: true, + style: { + cssClasses: [ + 'mafe-artifact-group' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'annotationResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + } + }, + labels: [ + { + message: "", + width: 0, + height: 0, + position: { + location: 'top', + diffX: 2, + diffY: 0 + }, + attachEvents: false, + updateParent: true, + style: { + cssClasses: [ + 'mafe-label-annotation' + ] + } + } + ], + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMArtifact(defaultOptions); + break; + case 'TEXT_ANNOTATION': + defaultOptions = { + art_name: name, + art_type: 'TEXT_ANNOTATION', + canvas: pmCanvas, + width: 100, + height: 30, + style: { + cssClasses: ['mafe-artifact-annotation'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "background-layer", + priority: 1, + visible: true, + style: { + cssClasses: [ + 'mafe-artifact-annotation' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'annotationResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + } + }, + labels: [ + { + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false, + updateParent: true + } + ], + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMArtifact(defaultOptions); + break; + + case 'DATAOBJECT': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + canvas: pmCanvas, + width: 33, + height: 41, + dat_type: 'DATAOBJECT', + dat_object_type: "dataobject", + dat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-dataobject-50', + 'mafe-dataobject-75', + 'mafe-dataobject-100', + 'mafe-dataobject-125', + 'mafe-dataobject-150' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + markers: [ + { + markerType: 'USERTASK', + x: 10, + y: 10, + position: 0 + } + ], + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateDataMarkerLayerClasses(defaultOptions); + customshape = new PMData(defaultOptions); + break; + + case 'DATASTORE': + defaultOptions = { + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 0 + } + } + ], + canvas: pmCanvas, + width: 41, + height: 41, + dat_type: 'DATASTORE', + dat_name: '', + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-datastore-20', + 'mafe-datastore-30', + 'mafe-datastore-41', + 'mafe-datastore-51', + 'mafe-datastore-61' + ] + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMData(defaultOptions); + break; + case 'PARTICIPANT': + defaultOptions = { + width: 500, + height: 130, + "canvas": this, + "connectAtMiddlePoints": false, + topLeft: true, + connectionType: 'dotted', + resizeBehavior: "participantResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + "style": { + cssClasses: ["mafe-pool"] + + }, + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + }, + attachEvents: false + } + ], + par_name: name, + corona: corona, + focusLabel: true + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMParticipant(defaultOptions); + break; + case 'POOL': + if (options.lns_name) { + name = options.lns_name; + } else if (options.par_name) { + name = options.par_name; + } + defaultOptions = { + width: 700, + height: 200, + "canvas": pmCanvas, + "connectAtMiddlePoints": false, + topLeft: false, + connectionType: 'dotted', + resizeBehavior: "poolResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmcontainer", + selectors: [ + "#TASK", + "#SUB_PROCESS", + "#START", + "#START_MESSAGE", + "#START_TIMER", + "#END", + "#END_MESSAGE", + "#END_EMAIL", + "#INTERMEDIATE_SENDMESSAGE", + "#INTERMEDIATE_RECEIVEMESSAGE", + "#INTERMEDIATE_EMAIL", + "#INTERMEDIATE_TIMER", + "#EXCLUSIVE", + "#PARALLEL", + "#INCLUSIVE", + "#DATAOBJECT", + "#DATASTORE", + "#TEXT_ANNOTATION", + "#LANE", + "#GROUP", + ".mafe-event-start", + ".mafe-event-intermediate", + ".mafe-event-end", + ".pmui-pmactivity", + ".pmui-pmgateway", + ".pmui-pmdata", + ".mafe-artifact-annotation", + ".mafe-artifact-group", + ".port" + ] + }, + container: "pool", + "style": { + cssClasses: ["mafe-pool"] + + }, + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + }, + attachEvents: false + } + ], + lns_name: name, + focusLabel: true, + corona: corona + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMPool(defaultOptions); + break; + case 'LANE': + defaultOptions = { + width: 500, + height: 200, + "canvas": pmCanvas, + "connectAtMiddlePoints": false, + topLeft: true, + connectionType: 'dotted', + resizeBehavior: "laneResize", + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' + } + }, + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' + } + } + }, + "drop": { + type: "pmcontainer", + selectors: [ + "#TASK", + "#SUB_PROCESS", + "#START", + "#START_MESSAGE", + "#START_TIMER", + "#END", + "#END_MESSAGE", + "#END_EMAIL", + "#INTERMEDIATE_SENDMESSAGE", + "#INTERMEDIATE_RECEIVEMESSAGE", + "#INTERMEDIATE_EMAIL", + "#INTERMEDIATE_TIMER", + "#EXCLUSIVE", + "#PARALLEL", + "#INCLUSIVE", + "#DATAOBJECT", + "#DATASTORE", + "#GROUP", + "#TEXT_ANNOTATION", + ".mafe-event-start", + ".mafe-event-intermediate", + ".mafe-event-end", + ".pmui-pmactivity", + ".pmui-pmgateway", + ".pmui-pmdata", + ".mafe-artifact-annotation", + ".mafe-artifact-group" + ] + }, + container: "lane", + layers: [ + { + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssProperties: {} + } + } + + ], + labels: [ + { + message: name, + width: 0, + height: 0, + orientation: 'vertical', + position: { + location: 'center-left', + diffX: 15, + diffY: 0 + } + } + ], + lan_name: name, + focusLabel: true + + }; + jQuery.extend(true, defaultOptions, options); + customshape = new PMLane(defaultOptions); + break; + + } + if (customshape && !pmCanvas.readOnly) { + customshape.attachListeners(); + customshape.extendedType = type; + menuShape = PMDesigner.getMenuFactory(type); + customshape.getHTML(); + customshape.setContextMenu(menuShape); + } + return customshape; + }; + PMDesigner.updateLayerClasses = function (options) { + return [ + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-16', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-24', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-33', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-41', + 'mafe-event-' + options.evn_type.toLowerCase() + '-' + options.evn_marker.toLowerCase() + '-49' + ]; + }; + PMDesigner.updateGatewayLayerClasses = function (options) { + return [ + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-20', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-30', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-41', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-51', + 'mafe-gateway-' + options.gat_type.toLowerCase() + '-61' + ]; + }; + PMDesigner.updateMarkerLayerClasses = function (options) { + if (options.act_task_type !== 'EMPTY') { + return [ + "mafe-" + options.act_task_type.toLowerCase() + "-marker-10", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-15", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-21", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-26", + "mafe-" + options.act_task_type.toLowerCase() + "-marker-31" + ]; + } + }; + PMDesigner.updateLoopLayerClasses = function (options) { + if (options.act_loop_type !== 'EMPTY') { + return [ + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-10", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-15", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-21", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-26", + "mafe-" + options.act_loop_type.toLowerCase() + "-marker-31" + ]; + } + }; + PMDesigner.updateDataMarkerLayerClasses = function (options) { + var type = options.dat_object_type.toLowerCase(); + if (type !== 'dataobject') { + return [ + "mafe-" + type + "-marker-10", + "mafe-" + type + "-marker-15", + "mafe-" + type + "-marker-21", + "mafe-" + type + "-marker-26", + "mafe-" + type + "-marker-31" + ]; + } + }; + /** + * Save a process and open the settings + * @param shape + * @param callback + */ + PMDesigner.saveAndOpenSettings= function (shape, callback) { + var splitedID; + + if(shape) { + splitedID = shape.getID().split("-"); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + if(callback) { + callback(shape); + } + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + callback(shape); + } + } + + + }; +}()); +PMDesigner.sidebar = []; + +PMDesigner.sidebar.push( + new ToolbarPanel({ + buttons: [ + { + selector: 'TASK', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-task' + ], + tooltip: "Task".translate() + }, + { + selector: 'SUB_PROCESS', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-subprocess' + ], + tooltip: "Sub Process".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'EXCLUSIVE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-exclusive' + ], + tooltip: "Exclusive Gateway".translate() + }, + { + selector: 'PARALLEL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-parallel' + ], + tooltip: "Parallel gateway".translate() + }, + { + selector: 'INCLUSIVE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-gateway-inclusive' + ], + tooltip: "Inclusive Gateway".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'START', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-start' + ], + tooltip: "Start Event".translate() + }, + { + selector: 'START_TIMER', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-event-start-timer' + ], + tooltip: "Start Timer Event".translate() + }, + { + selector: 'INTERMEDIATE_EMAIL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-intermediate-send-mesage' + ], + tooltip: "Intermediate Email Event".translate() + }, + { + selector: 'INTERMEDIATE_TIMER', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-event-intermediate-timer' + ], + tooltip: "Intermediate Timer Event".translate() + }, + { + selector: 'END', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-end' + ], + tooltip: "End Event".translate() + }, + { + selector: 'END_EMAIL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-end-message' + ], + tooltip: "End Email Event ".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'DATAOBJECT', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-data-object' + ], + tooltip: "Data Object".translate() + }, + { + selector: 'DATASTORE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-data-store' + ], + tooltip: "Data Store".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'PARTICIPANT', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-blackbox' + ], + tooltip: " Black Box Pool".translate() + }, + { + selector: 'POOL', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-pool' + ], + tooltip: "Pool".translate() + }, + { + selector: 'LANE', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-lane' + ], + tooltip: "Lane".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'GROUP', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-group' + ], + tooltip: "Group".translate() + }, + { + selector: 'TEXT_ANNOTATION', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-annotation' + ], + tooltip: "Text Annotation".translate() + } + ] + }), + new ToolbarPanel({ + buttons: [ + { + selector: 'LASSO', + className: [ + 'mafe-designer-icon', + 'mafe-toolbar-lasso' + ], + tooltip: "Lasso".translate() + } + + ] + }) +); +ListDynaform = function () { + this.superTitle = 'Dynaforms'.translate(); + this.tableContainerHeight = 374; + this.buttonCreate = null; + this.onCreate = new Function(); + this.onShowId = new Function(); + this.onEdit = new Function(); + this.onDel = new Function(); + this.loaded = false; + this.clickedClose = true; + Mafe.Grid.call(this); + ListDynaform.prototype.init.call(this); +}; +ListDynaform.prototype = new Mafe.Grid(); +ListDynaform.prototype.init = function () { + var that = this; + that.buttonCreate = new PMUI.ui.Button({ + id: 'dynaformButtonNew', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: {cssClasses: ['mafe-button-create']}, + handler: function (event) { + that.onCreate(event); + } + }); + that.buttonCreate.defineEvents(); + that.setID('idListDynaform'); + that.setColumns([{ + id: 'copyuid', + title: 'Show ID'.translate(), + dataType: 'button', + buttonLabel: 'Show ID'.translate(), + buttonStyle: {cssClasses: ['mafe-button-show']}, + onButtonClick: function (row, grid) { + that.onShowId(row, grid); + } + }, { + id: 'dynaformGridPanelTitle', + title: 'Title'.translate(), + dataType: 'string', + width: '460px', + alignmentCell: 'left', + sortable: true, + columnData: 'dyn_title' + }, { + id: 'dynaformGridPanelEdit', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-edit']}, + buttonLabel: function (row, data) { + return 'Edit'.translate(); + }, + onButtonClick: function (row, grid) { + that.onEdit(row, grid); + } + }, { + id: 'dynaformGridPanelDelete', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-delete']}, + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + onButtonClick: function (row, grid) { + that.onDel(row, grid); + } + } + ]); +}; +ListDynaform.prototype.createHTML = function () { + Mafe.Grid.prototype.createHTML.call(this); + this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); + return this.html; +}; +ListDynaform.prototype.load = function () { + var that = this; + that.clearItems(); + (new PMRestClient({ + endpoint: 'dynaforms', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.setDataItems(response); + that.sort('dyn_title', 'asc'); + that.loaded = true; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + that.loaded = false; + }, + messageError: 'There are problems getting the list of dynaforms, please try again.'.translate() + })).executeRestClient(); +}; +ListDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +BlankDynaform = function () { + this.superTitle = 'Create Blank Dynaform'.translate(); + this.onSave = new Function(); + this.onSaveOpen = new Function(); + this.onCancel = new Function(); + this.buttons = null; + Mafe.Form.call(this); + BlankDynaform.prototype.init.call(this); +}; +BlankDynaform.prototype = new Mafe.Form(); +BlankDynaform.prototype.init = function () { + var that = this; + that.setID('formDynaformInformation'); + that.setTitle('Dynaform Information'.translate()); + that.setItems([{ + id: 'formDynaformInformationTitle', + pmType: 'text', + label: 'Title'.translate(), + value: '', + maxLength: 255, + placeholder: 'The Dynaform title'.translate(), + name: 'dyn_title', + required: true, + controlsWidth: 303 + }, { + id: 'formDynaformInformationDescription', + pmType: 'textarea', + rows: 200, + name: 'dyn_description', + width: 200, + label: 'Description'.translate(), + style: {cssClasses: ['mafe-textarea-resize']} + } + ]); + that.buttons = [ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSaveOpen', + text: 'Save & Open'.translate(), + buttonType: 'success', + handler: function () { + that.onSaveOpen(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSave', + text: 'Save'.translate(), + buttonType: 'success', + handler: function () { + that.onSave(); + } + }) + ]; +}; +BlankDynaform.prototype.getButtons = function () { + return this.buttons; +}; +BlankDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +Dynaform = function (settings) { + this.listDynaform = null; + this.blankDynaform = null; + Mafe.Window.call(this, settings); + Dynaform.prototype.init.call(this, settings); +}; +Dynaform.prototype = new Mafe.Window(); +Dynaform.prototype.init = function (settings) { + var that = this; + that.listDynaform = new ListDynaform(); + that.setOnBeforeCloseHandler(function () { + this.clickedClose = true; + if (!that.blankDynaform.isVisible()) { + that.close(); + } else { + that.blankDynaform.onCancel(); + } + }); + that.listDynaform.load(); + that.listDynaform.onShowId = function (row, grid) { + showUID(row.getData().dyn_uid); + }; + that.listDynaform.onCreate = function () { + that.resetView(); + that.setTitle(that.blankDynaform.getSuperTitle()); + that.blankDynaform.setVisible(true); + that.setButtons(that.blankDynaform.getButtons()); + }; + that.listDynaform.onEdit = function (row, grid) { + that.edit(row, grid); + }; + that.listDynaform.onDel = function (row, grid) { + that.del(row, grid); + }; + + that.blankDynaform = new BlankDynaform(); + that.blankDynaform.onSave = function () { + that.saveBlank(false); + }; + that.blankDynaform.onSaveOpen = function () { + that.saveBlank(true); + }; + that.blankDynaform.onCancel = function () { + $("input,select,textarea").blur(); + var title = ""; + that.blankDynaform.loseChanges(title); + }; + that.blankDynaform.onYesConfirmCancellation = function () { + if (that.clickedClose) { + that.close(); + } + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + }; + + that.addItem(that.listDynaform); + that.addItem(that.blankDynaform); + + that.open(); + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + + // hard coding dyn_title textfield because enter keypress reload the current page + if (that.blankDynaform.getItems()[0] + && that.blankDynaform.getItems()[0].controls[0] + && that.blankDynaform.getItems()[0].controls[0].html) { + $(that.blankDynaform.getItems()[0].controls[0].html).keypress(function (e) { + if (e.which == 13) { + e.preventDefault(); + } + }); + } +}; +Dynaform.prototype.saveBlank = function (open) { + var that = this, + data, + restClient, + flagAux; + + if (!that.blankDynaform.isValid()) { + flagAux = that.blankDynaform.visible; + } else { + flagAux = that.blankDynaform.isValid(); + } + + if (flagAux) { + if (getData2PMUI(that.blankDynaform.html).dyn_title == "") { + return false; + } + } + + data = getData2PMUI(that.blankDynaform.html); + data['dyn_version'] = 2; + data['dyn_type'] = 'xmlform'; + restClient = new PMRestClient({ + endpoint: 'dynaform', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + if (open) { + that.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(response); + } else { + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + that.listDynaform.load(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems creating the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform saved successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); +}; +Dynaform.prototype.edit = function (row, grid) { + this.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(row.getData()); +}; +Dynaform.prototype.del = function (row, grid) { + var that = this, + confirmDeletion = new Mafe.ConfirmDeletion(); + confirmDeletion.setMessage('Do you want to delete this DynaForm?'.translate()); + confirmDeletion.setTitle("Dynaform".translate()); + confirmDeletion.onDelete = function () { + var restClient = new PMRestClient({ + endpoint: 'dynaform/' + row.getData().dyn_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.listDynaform.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems deleting the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform deleted successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); + }; +}; + +(function () { + PMDesigner.dynaform = function () { + var dynaform = new Dynaform(); + }; + PMDesigner.dynaform.create = function () { + var dynaform = new Dynaform(); + dynaform.resetView(); + dynaform.setTitle(dynaform.blankDynaform.getSuperTitle()); + dynaform.blankDynaform.setVisible(true); + dynaform.setButtons(dynaform.blankDynaform.getButtons()); + }; +}()); + +/** + * Updates the granular export feature after enabled features are loaded. + */ +var navbarExportUpdate = function () { + //Code export - export granular (handler) + var handlerExportNormal = function () { + var ws = enviromentVariables('WORKSPACE'); + if (!HTTP_SERVER_HOSTNAME) { + HTTP_SERVER_HOSTNAME = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); + } + location.href = HTTP_SERVER_HOSTNAME + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + "/export?access_token=" + PMDesigner.project.keys.access_token; + }; + + var handlerExportGranular = function () { + var optionExportNormal = $("
" + "Normal".translate() + "
"), + optionExportGranular = $("
" + "Custom".translate() + "
"), + menuExport = $("").hide(), + $item = $("#idNavBar").find(".mafe-button-export-process").closest("li"); + + menuExport.append(optionExportNormal).append(optionExportGranular); + if (!$item.find(".mafe-button-menu-container").length) { + $item.append(menuExport); + } + $(".ui-tooltip").hide(); + $(menuExport).slideToggle("slow"); + $item.on("mouseleave", function (e) { + if ($(this).find(".mafe-button-menu-container").eq(0).is(":visible")) { + var that = this; + $(that).find(".mafe-button-menu-container").remove(); + } + }); + + $(".sub-nav").on("click", ".normalExport", function (event) { + var ws = enviromentVariables('WORKSPACE'), + locationOrigin; + if (!window.location.origin) { + locationOrigin = window.location.protocol + "//" + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { + locationOrigin = HTTP_SERVER_HOSTNAME; + } else { + locationOrigin = window.location.origin; + } + location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + "/export?access_token=" + PMDesigner.project.keys.access_token; + }); + + $(".sub-nav").on("click", ".granularExport", function (event) { + PMDesigner.granularProcessExport(); + }); + }; + if (inArray("jXsSi94bkRUcVZyRStNVExlTXhEclVadGRRcG9xbjNvTWVFQUF3cklKQVBiVT0=", ENABLED_FEATURES)) { + handler = handlerExportGranular; + } else { + handler = handlerExportNormal; + } + +}; + +function inArray(needle, haystack) { + var i, + length = haystack.length; + for (i = 0; i < length; i += 1) { + if (haystack[i] == needle) return true; + } + return false; +} + +var defaultNavbarPanelMenus = { + array: [], + init: function () { + var closeVar = { + id: 'closeButton', + name: 'Close', + htmlProperty: { + id: 'closeButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-close', + child: [ + { + element: 'span', + class: 'mafe-button-close' + } + ] + } + + ] + }, + actions: { + selector: ".mafe-button-close", + tooltip: "Close".translate(), + execute: true, + handler: function () { + var message_window, + browser = PMDesigner.getBrowser(), + url = parent.location.href; + + if (PMDesigner.project.isDirty() && !PMDesigner.project.isSave) { + var message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: "cancelSaveSubprocPropertiesWin", + title: PMDesigner.project.projectName, + message: 'Save your changes and exit ?'.translate(), + footerItems: [ + { + pmType: 'label', + text: ' ' + }, { + text: "No".translate(), + handler: function () { + PMDesigner.project.isClose = true; + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + window.close(); + } else { + parent.location.href = url; + } + }, + buttonType: "error" + }, + + { + text: "Yes".translate(), + handler: function () { + PMDesigner.project.saveClose(true); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + window.close(); + } else { + parent.location.href = url; + } + } + } + } + }, + helpVar = { + id: 'helpButton', + name: 'Help', + htmlProperty: { + id: 'helpButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-help', + child: [ + { + element: 'span', + class: 'mafe-toolbar-help' + } + ] + } + ] + }, + actions: { + selector: ".mafe-toolbar-help", + tooltip: "Help".translate(), + execute: true, + handler: function () { + var canvas = PMUI.getActiveCanvas(); + PMDesigner.helper.startIntro(); + if (canvas && canvas.getHTML()) { + canvas.getHTML().classList.remove("pmui-pmcanvas"); + } + } + } + }, + saveVar = { + id: 'saveButton', + name: 'Save', + htmlProperty: { + id: 'saveButton', + element: 'li', + class: 'mafe-save-process', + child: [ + { + element: 'a', + class: 'mafe-button-save' + }, + { + element: 'span', + class: 'mafe-button-menu', + child: [ + { + element: 'img', + src: '/lib/img/caret-down.png' + } + ] + } + ] + }, + actions: { + selector: ".mafe-button-save", + tooltip: "Save process".translate(), + label: { + text: "Save".translate() + }, + execute: true, + handler: function () { + if (PMDesigner.project.isDirty() && PMDesigner.project.isSave === false) { + PMDesigner.project.isSave = true; + document.getElementsByClassName("mafe-save-process")[0].childNodes[0].text = "Saving"; + PMDesigner.project.save(true); + } + } + } + }, + exportButton = { + id: 'exportButton', + name: 'ExportButton', + htmlProperty: { + id: 'exportButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-export-process' + } + ] + }, + actions: { + selector: ".mafe-button-export-process", + tooltip: "Export process".translate(), + label: { + text: "Export Process".translate() + }, + execute: true, + handler: function () { + handler(); + } + } + }, + exportBpmnButton = { + id: 'exportBpmnButton', + name: 'ExportBpmn', + htmlProperty: { + id: 'exportBpmnButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-export-bpmn-process' + } + ] + }, + actions: { + selector: ".mafe-button-export-bpmn-process", + tooltip: "Export Diagram ".translate(), + label: { + text: "Export Diagram".translate() + }, + execute: false, + handler: function () { + } + } + }, + zoomVar = { + id: 'zoomOptions', + name: 'Zoom', + htmlProperty: { + id: 'zoomOptions', + element: 'li', + child: [ + { + element: 'span', + class: 'mafe-zoom-options' + } + ] + }, + actions: { + id: 'zoomOptions', + spanclass: 'mafe-zoom-options', + actions: 'zoom' + }, + aditionalAction: { + execute: PMDesigner.ApplyOptionsZoom() + } + }, + undo = { + id: 'undoButton', + name: 'Undo', + htmlProperty: { + id: 'undoButton', + element: 'li', + class: 'mafe-undo', + child: [ + { + element: 'b', + class: 'mafe-action-undo', + child: [ + { + element: 'span', + class: 'mafe-button-undo' + } + ] + } + ] + }, + actions: { + selector: ".mafe-action-undo", + tooltip: "Undo Action".translate(), + label: { + text: '' + }, + execute: true, + handler: function () { + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().commandStack.undo(); + } + } + }, + redo = { + id: 'redoButton', + name: 'Redo', + htmlProperty: { + id: 'redoButton', + element: 'li', + class: 'mafe-redo', + child: [ + { + element: 'b', + class: 'mafe-action-redo', + child: [ + { + element: 'span', + class: 'mafe-button-redo' + } + ] + } + ] + }, + actions: { + selector: ".mafe-action-redo", + tooltip: "Redo Action".translate(), + label: { + text: '' + }, + execute: true, + handler: function () { + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().commandStack.redo(); + } + } + }, + fullScreen = { + id: 'fullScreenButton', + name: 'FullScreen', + htmlProperty: { + id: 'fullScreenButton', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-button-fullscreen' + } + ] + }, + actions: { + selector: ".mafe-button-fullscreen", + tooltip: "Full Screen".translate(), + execute: true, + handler: function () { + PMDesigner.fullScreen.toggle(this); + } + } + }; + navbarExportUpdate(); + this.array = [ + closeVar, + helpVar, + saveVar, + exportButton, + exportBpmnButton, + zoomVar, + undo, + redo, + fullScreen + ]; + }, + /** + * Get Array of Items of the NavBarPanelMenu + * @returns {Array} + */ + getNavBarPanelMenu: function () { + return this.array; + }, + /** + * Adds one Item To NavBarPanelMenu + * @param item + */ + addItemToNavBarPanelMenu: function (item) { + this.array.push(item); + } +}; + +defaultNavbarPanelMenus.init(); + +/** + * @class PMUI.menu.navBarPanel + * Handles the navbar panel of designer, + * contains all menus for content elements. + * + * @param {array} items Default items + * @constructor + */ +var NavbarPanel = function (items) { + NavbarPanel.prototype.init.call(this, items); +}; + +/** + * Initializes the object. + * + * @param {array} items Array with default values. + */ +NavbarPanel.prototype.init = function (items) { + var item; + if (typeof items === 'undefined') { + items = defaultNavbarPanelMenus.getNavBarPanelMenu(); + } + this.items = new PMUI.util.ArrayList(); + for (item in items) { + if (!items.hasOwnProperty(item)) { + continue; + } + this.items.insert(items[item]); + } +}; + +/** + * This method renders HTML and actions into designer + * + */ +NavbarPanel.prototype.show = function () { + var item = null, + i, + max; + if (PMDesigner.navbarPanel.items instanceof Object) { + for (i = 0, max = PMDesigner.navbarPanel.items.getSize(); i < max; i += 1) { + item = PMDesigner.navbarPanel.items.get(i); + if (typeof item.htmlProperty !== "undefined") { + PMDesigner.navbarPanel.buildHtmlElement(item.htmlProperty); + } + if (typeof item.aditionalAction !== "undefined") { + item.aditionalAction; + } + if (typeof item.actions !== "undefined") { + new PMAction(item.actions); + } + } + } else { + throw new Error('cannot show the elements of the List'); + } + +}; + +/** + * This method creates a html element button into the navBar Panel + * @param {Object} element + * @param {HTMLElement} before + */ +NavbarPanel.prototype.buildHtmlElement = function (element, before) { + var ul = document.getElementById('idNavBarList'), + htmlElement; + if ((typeof ul !== undefined) && (ul !== null)) { + htmlElement = this.getNodeChild(element, ul); + if (typeof before !== "undefined") { + before = document.getElementById(before); + ul.insertBefore(htmlElement, before); + } else { + ul.appendChild(htmlElement); + } + } + +}; + +/** + * This method assembling dependent html elements to the button + * @param {Object} nodeChild + * @param {HTMLElement} nodePattern + * @returns {Element} + */ +NavbarPanel.prototype.getNodeChild = function (nodeChild, nodePattern) { + var node = document.createElement(nodeChild.element), + i; + if (typeof nodeChild.id !== 'undefined') { + node.setAttribute("id", nodeChild.id); + } + if (nodeChild.element === 'a') { + node.setAttribute("href", "return;"); + } + if (typeof(nodeChild.class) !== 'undefined') { + node.setAttribute("class", nodeChild.class); + } + if (typeof(nodeChild.child) !== 'undefined' && nodeChild.child instanceof Array) { + for (i = 0; i < nodeChild.child.length; i += 1) { + this.getNodeChild(nodeChild.child[i], node); + } + } + if (typeof(nodeChild.src) !== 'undefined') { + node.setAttribute("src", nodeChild.src); + } + if ((typeof nodePattern !== undefined) && (nodePattern !== null) && nodePattern.localName !== 'ul') { + nodePattern.appendChild(node); + } + return node; +}; + +/** + * This method removes an html element for the + * NavBar panel array List and delete the HTML from the designer. + * @param {String} idButton + */ +NavbarPanel.prototype.deleteHtmlElement = function (idButton) { + var btn = document.getElementById(idButton), + element = PMDesigner.contentControl.items.find("id", idButton), + remove = PMDesigner.contentControl.items.remove(element); + if (typeof btn !== 'undefined' && remove === true) { + btn.parentNode.removeChild(btn); + } else { + throw new Error('Cannot find the specified button: ' + idButton + '. Please, review this'); + } +}; + +/** + * NavbarPanel get an instance + * @type {NavbarPanel} + */ +PMDesigner.navbarPanel = new NavbarPanel(defaultNavbarPanelMenus.getNavBarPanelMenu()); + +function defaultContentControlMenus() { + var variableCreate = { + id: 'variableCreate', + name: 'Variable', + htmlProperty: { + id: 'variableCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-variable' + }, + { + element: 'a', + class: 'btn_create mafe-menu-variable-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-variable", + label: { + text: "Variables".translate() + }, + execute: true, + handler: function () { + PMDesigner.variables(); + } + }, + createAction: { + selector: ".mafe-menu-variable-create", + label: { + selector: ".mafe-menu-variable-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.variables.create(); + } + } + }, + messageType = { + id: 'messageTypeCreate', + name: 'MessageType', + htmlProperty: { + id: 'messageTypeCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-messagetype' + }, + { + element: 'a', + class: 'btn_create mafe-menu-messagetype-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-messagetype", + label: { + text: "Message Types".translate() + }, + execute: true, + handler: function () { + PMDesigner.messageType(); + } + }, + createAction: { + selector: ".mafe-menu-messagetype-create", + label: { + selector: ".mafe-menu-messagetype-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.messageType.create(); + } + } + }, + dynaformCreate = { + id: 'dynaformCreate', + name: 'Dynaform', + htmlProperty: { + id: 'dynaformCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-dynaform' + }, + { + element: 'a', + class: 'btn_create mafe-menu-dynaform-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-dynaform", + label: { + text: "Dynaforms".translate() + }, + execute: true, + handler: function () { + PMDesigner.dynaform(); + } + }, + createAction: { + selector: ".mafe-menu-dynaform-create", + label: { + selector: ".mafe-menu-dynaform-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.dynaform.create(); + } + } + }, + inputDocumentCreate = { + id: 'inputDocumentCreate', + name: 'InputDocument', + htmlProperty: { + id: 'inputDocumentCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-inputdocuments' + }, + { + element: 'a', + class: 'btn_create mafe-menu-inputdocuments-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-inputdocuments", + label: { + text: "Input Documents".translate() + }, + execute: true, + handler: function () { + var inputDocument = new InputDocument(); + inputDocument.build(); + } + }, + createAction: { + selector: ".mafe-menu-inputdocuments-create", + label: { + selector: ".mafe-menu-inputdocuments-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + var inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.method = "POST"; + } + } + }, + outputDocumentCreate = { + id: 'outputDocumentCreate', + name: 'OutputDocument', + htmlProperty: { + id: 'outputDocumentCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-outputdocuments' + }, + { + element: 'a', + class: 'btn_create mafe-menu-outputdocuments-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-outputdocuments", + label: { + text: "Output Documents".translate() + }, + execute: true, + handler: function () { + PMDesigner.output(); + } + }, + createAction: { + selector: ".mafe-menu-outputdocuments-create", + label: { + selector: ".mafe-menu-outputdocuments-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.output(); + PMDesigner.output.create(); + } + } + }, + triggerCreate = { + id: 'triggerCreate', + name: 'Trigger', + htmlProperty: { + id: 'triggerCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-triggers' + }, + { + element: 'a', + class: 'btn_create mafe-menu-triggers-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-triggers", + label: { + text: "Triggers".translate() + }, + execute: true, + handler: function () { + PMDesigner.trigger(); + } + }, + createAction: { + selector: ".mafe-menu-triggers-create", + label: { + selector: ".mafe-menu-triggers-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.trigger(); + PMDesigner.trigger.create(); + } + } + }, + reportTableCreate = { + id: 'reportTableCreate', + name: 'ReportTable', + htmlProperty: { + id: 'reportTableCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-reporttables' + }, + { + element: 'a', + class: 'btn_create mafe-menu-reporttables-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-reporttables", + label: { + text: "Report Tables".translate() + }, + execute: true, + handler: function () { + PMDesigner.reporttable(); + } + }, + createAction: { + selector: ".mafe-menu-reporttables-create", + label: { + selector: ".mafe-menu-reporttables-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.reporttable(); + PMDesigner.reporttable.create(); + } + } + }, + databaseCreate = { + id: 'databaseCreate', + name: 'Database', + htmlProperty: { + id: 'databaseCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-databaseconnections' + }, + { + element: 'a', + class: 'btn_create mafe-menu-databaseconnections-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-databaseconnections", + label: { + text: "Database Connections".translate() + }, + execute: true, + handler: function () { + PMDesigner.database(); + } + }, + createAction: { + selector: ".mafe-menu-databaseconnections-create", + label: { + selector: ".mafe-menu-databaseconnections-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.database.create(); + } + } + }, + templateCreate = { + id: 'templateCreate', + name: 'TemplateCreate', + htmlProperty: { + id: 'templateCreate', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-templates' + }, + { + element: 'a', + class: 'btn_create mafe-menu-templates-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-templates", + label: { + text: "Templates".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager("templates", "CREATION_NORMAL"); + } + }, + createAction: { + selector: ".mafe-menu-templates-create", + label: { + selector: ".mafe-menu-templates-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager.createFirst("templates", "CREATION_MORE"); + } + } + }, + menuPublic = { + id: 'menuPublic', + name: 'MenuPublic', + htmlProperty: { + id: 'menuPublic', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-public' + }, + { + element: 'a', + class: 'btn_create mafe-menu-public-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-public", + label: { + text: "Public Files".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager("public", "CREATION_NORMAL"); + } + }, + createAction: { + selector: ".mafe-menu-public-create", + label: { + selector: ".mafe-menu-public-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.ProcessFilesManager.createFirst("public", "CREATION_MORE"); + } + } + }, + menuPermission = { + id: 'menuPermission', + name: 'MenuPermission', + htmlProperty: { + id: 'menuPermission', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-permissions' + }, + { + element: 'a', + class: 'btn_create mafe-menu-permissions-create', + child: [ + { + element: 'span' + } + ] + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-permissions", + label: { + text: "Permissions".translate() + }, + execute: true, + handler: function () { + PMDesigner.processPermissions(); + } + }, + createAction: { + selector: ".mafe-menu-permissions-create", + label: { + selector: ".mafe-menu-permissions-create span", + text: "Create".translate() + }, + execute: true, + handler: function () { + PMDesigner.processPermissions.create(); + } + } + }, + menuCaseTracker = { + id: 'menuCaseTracker', + name: 'CaseTracker', + htmlProperty: { + id: 'menuCaseTracker', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-casetracker' + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-casetracker", + label: { + text: "Case Tracker".translate() + }, + execute: true, + handler: function () { + PMDesigner.caseTracker(); + } + } + }, + menuSupervisor = { + id: 'menuSupervisor', + name: 'MenuSupervisor', + htmlProperty: { + id: 'menuSupervisor', + element: 'li', + child: [ + { + element: 'a', + class: 'mafe-menu-supervisors' + } + ] + }, + actions: { + type: 'button', + selector: ".mafe-menu-supervisors", + label: { + text: "Supervisors".translate() + }, + execute: true, + handler: function () { + PMDesigner.assigmentSupervisors(); + } + } + }; + + return [ + variableCreate, + messageType, + dynaformCreate, + inputDocumentCreate, + outputDocumentCreate, + triggerCreate, + reportTableCreate, + databaseCreate, + templateCreate, + menuPublic, + menuPermission, + menuCaseTracker, + menuSupervisor + ]; +}; + +/** + * @class PMUI.menu.contentControl + * Handles the content control menu of designer, + * contains all menus for content elements. + * + * @param {array} items Default items + * @constructor + */ +var ContentControl = function (items) { + ContentControl.prototype.init.call(this, items); +}; + +/** + * Initializes the object. + * + * @param {array} items Array with default values. + */ +ContentControl.prototype.init = function (items) { + this.items = new PMUI.util.ArrayList(); + if (typeof items === 'undefined') { + items = defaultContentControlMenus(); + } + for (var item in items) { + if (!items.hasOwnProperty(item)) { + continue; + } + this.items.insert(items[item]); + } +}; + +/** + * This method renders HTML and actions into designer + * + */ +ContentControl.prototype.show = function () { + var item = null, + i, + max; + if (this.items instanceof Object) { + for (i = 0, max = this.items.getSize(); i < max; i += 1) { + item = this.items.get(i); + if (typeof item.htmlProperty !== "undefined") { + this.buildHtmlElement(item.htmlProperty); + } + if (typeof item.actions !== "undefined") { + new PMAction(item.actions); + } + if (typeof item.createAction !== "undefined") { + new PMAction(item.createAction); + } + } + } else { + throw new Error('Cannot show the elements of the List'); + } +}; + +/** + * This method creates a html element button into the content + * control panel. + * @param {Object} element + * @param {HTMLElement} before + */ +ContentControl.prototype.buildHtmlElement = function (element, before) { + var ul = document.getElementById('contentControlList'), + htmlElement; + if ((typeof ul !== undefined) && (ul !== null)) { + htmlElement = this.getNodeChild(element, ul); + if (typeof before !== "undefined") { + before = document.getElementById(before); + ul.insertBefore(htmlElement, before); + } else { + ul.appendChild(htmlElement); + } + } + +}; + +/** + * This method assembling dependent html elements to the button + * @param {Object} nodeChild + * @param {HTMLElement} nodePattern + * @returns {Element} + */ +ContentControl.prototype.getNodeChild = function (nodeChild, nodePattern) { + var node = document.createElement(nodeChild.element), + i; + if (typeof nodeChild.id !== 'undefined') { + node.setAttribute("id", nodeChild.id); + } + if (nodeChild.element === 'a') { + node.setAttribute("href", "#"); + } + if (typeof(nodeChild.class) !== 'undefined') { + node.setAttribute("class", nodeChild.class); + } + if (typeof(nodeChild.child) !== 'undefined' && nodeChild.child instanceof Array) { + for (i = 0; i < nodeChild.child.length; i += 1) { + this.getNodeChild(nodeChild.child[i], node); + } + } + if (typeof(nodeChild.src) !== 'undefined') { + node.setAttribute("src", nodeChild.src); + } + if ((typeof nodePattern !== undefined) && (nodePattern !== null) && nodePattern.localName !== 'ul') { + nodePattern.appendChild(node); + } + return node; +}; + +/** + * This method removes an html element for the + * Content Control panel array List and delete the HTML from the designer. + * @param {String} idButton + */ +ContentControl.prototype.deleteHtmlElement = function (idButton) { + var btn = document.getElementById(idButton), + element = this.items.find("id", idButton), + remove = this.items.remove(element); + if (typeof btn !== 'undefined' && remove === true) { + btn.parentNode.removeChild(btn); + } else { + throw new Error('Cannot find the specified button: ' + idButton + '. Please, review this'); + } +}; + +/** + * ContentControl get an instance + * @type {ContentControl} + */ +PMDesigner.contentControl = new ContentControl(defaultContentControlMenus()); + +/** + * Input Document module + * @param options + * @constructor + */ +var InputDocument = function (options) { + this.winMainInputDocument = null; + this.externalType = false; + this.inputDocumentOriginDataForUpdate = {}; + this.windowDialog = null; + this.assignAccordion = null; + this.clickedClose = true; + this.onUpdateInputDocumentHandler = null; + InputDocument.prototype.init.call(this, options); +}; +/** + * set close modulo InputDocument constructor + * @param handler, the callback function + */ +InputDocument.prototype.setOnUpdateInputDocumentHandler = function (handler) { + if (typeof handler === "function") { + this.onUpdateInputDocumentHandler = handler; + } + return this; +}; +/** + * constructor + * @param options + */ +InputDocument.prototype.init = function (options) { + var defaults = { + onUpdateInputDocumentHandler: null + }; + $.extend(true, defaults, options); + this.setOnUpdateInputDocumentHandler(defaults.onUpdateInputDocumentHandler); + return this; +}; + +/** + * Puts input document using rest proxy, to update data + * @param inputDocumentUid + * @param data + */ +InputDocument.prototype.inputDocumentPutRestProxy = function (inputDocumentUid, data) { + var that = this, + restProxy; + + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + var message; + if (!that.externalType) { + if (typeof flagInputDocument != 'undefined' && flagInputDocument) { + that.winMainInputDocument.close(); + return; + } + that.inputDocumentsGetRestProxy(); + that.openGridPanelInMainWindow(); + } else { + that.winMainInputDocument.close(); + message = new PMUI.ui.FlashMessage({ + message: 'Input Document edited correctly.'.translate(), + duration: 3000, + severity: 'success', + appendTo: that.windowDialog + }); + message.show(); + } + if (typeof that.onUpdateInputDocumentHandler === "function") { + that.onUpdateInputDocumentHandler(data, that); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document updated successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Deletes an input document + * @param inputDocumentUid + */ +InputDocument.prototype.inputDocumentDeleteRestProxy = function (inputDocumentUid) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.inputDocumentsGetRestProxy(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document deleted successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Creates an input document using rest proxy + * @param data + */ +InputDocument.prototype.inputDocumentPostRestProxy = function (data) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document", + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + that.inputDocumentsGetRestProxy(); + that.openGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Input Document saved successfully'.translate(), + flashContainer: that.grdpnlInputDocument + }); + restProxy.executeRestClient(); +}; +/** + * Gets all input documents to populate the grid + */ +InputDocument.prototype.inputDocumentsGetRestProxy = function () { + var that = this, + restProxy = new PMRestClient({ + endpoint: 'input-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.grdpnlInputDocument.setDataItems(response); + that.grdpnlInputDocument.sort('inp_doc_title', 'asc'); + if (PMVariables.prototype.isWindowActive()) { + PMVariables.prototype.setInputDocumentsFromIDModule(PMUI.getPMUIObject(inp_doc_uid), response); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +/** + * Gets an specific input document data to edit it + * @param inputDocumentUid + */ +InputDocument.prototype.inputDocumentFormGetProxy = function (inputDocumentUid) { + var that = this, + restProxy; + restProxy = new PMRestClient({ + endpoint: "input-document/" + inputDocumentUid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var data = response; + that.method = "PUT"; + that.openFormForEditInMainWindow(data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; + +/** + * Open Edit form and sets to main windows + * @param inputDocumentData + */ +InputDocument.prototype.openFormForEditInMainWindow = function (inputDocumentData) { + var that = this; + + that.inputDocumentOriginDataForUpdate = inputDocumentData; + that.inputDocumentUid = inputDocumentData.inp_doc_uid; + that.frmInputDocument.getField('inp_doc_original').setValue(""); + that.winMainInputDocument.setTitle("Edit Input Document".translate()); + + that.frmInputDocument.getField('inp_doc_title').setValue(inputDocumentData.inp_doc_title); + that.frmInputDocument.getField('inp_doc_description').setValue(inputDocumentData.inp_doc_description); + that.frmInputDocument.getField('inp_doc_form_needed').setValue(inputDocumentData.inp_doc_form_needed); + that.frmInputDocument.getField('inp_doc_original').setValue(inputDocumentData.inp_doc_original); + + if (inputDocumentData.inp_doc_form_needed !== "VIRTUAL") { + that.frmInputDocument.getField('inp_doc_original').setVisible(true); + } else { + that.frmInputDocument.getField('inp_doc_original').setVisible(false); + } + that.frmInputDocument.getField('inp_doc_versioning').setValue(parseInt(inputDocumentData.inp_doc_versioning + "")); + that.frmInputDocument.getField('inp_doc_destination_path').setValue(inputDocumentData.inp_doc_destination_path); + that.frmInputDocument.getField('inp_doc_tags').setValue(inputDocumentData.inp_doc_tags); + that.frmInputDocument.getField('inp_doc_type_file').setValue(inputDocumentData.inp_doc_type_file); + that.frmInputDocument.getField('inp_doc_max_filesize').setValue(inputDocumentData.inp_doc_max_filesize); + that.frmInputDocument.getField('inp_doc_max_filesize_unit').setValue(inputDocumentData.inp_doc_max_filesize_unit); +}; +/** + * Open the grid panel and sets to mai windows + */ +InputDocument.prototype.openGridPanelInMainWindow = function () { + this.grdpnlInputDocument.setVisible(true); + this.frmInputDocument.setVisible(false); + this.winMainInputDocument.setTitle("Input Documents".translate()); + this.winMainInputDocument.hideFooter(); +}; +/** + * Set the option external type of input Document + */ +InputDocument.prototype.setExternalType = function (value) { + if (typeof value === "boolean") { + this.externalType = value; + } + return this; +}; +/** + * Set the option window Dialog, a window that open this class + */ +InputDocument.prototype.setWindowDialog = function (value) { + this.windowDialog = value; + return this; +}; + +InputDocument.prototype.setAssignAccordion = function (obj) { + this.assignAccordion = obj; +}; + +/** + * Open create form an sets to main windows + */ +InputDocument.prototype.openFormInMainWindow = function () { + this.grdpnlInputDocument.setVisible(false); + this.frmInputDocument.setVisible(true); + this.winMainInputDocument.setTitle("Create Input Document".translate()); + this.winMainInputDocument.showFooter(); +}; + +InputDocument.prototype.checkIfValuesAreEqual = function (initialData, finalData) { + var key1, key2; + if (!Object.keys(initialData).length && Object.keys(finalData).length) { + if (finalData['inp_doc_title'] != '' || finalData['inp_doc_form_needed'] != 'VIRTUAL' || finalData['inp_doc_description'] != '' || finalData['inp_doc_versioning'] != '0' || finalData['inp_doc_destination_path'] != '') { + return false; + } + } + + for (key1 in initialData) { + for (key2 in finalData) { + if (typeof(initialData[key1]) != "undefined" && + typeof(finalData[key2]) != "undefined" && + key1 == key2 && + initialData[key1] != finalData[key2] + ) { + //Return + return false; + } + } + } + return true; +}; + +/** + * Generate all ui components(window, form, grid, fields) + */ + +InputDocument.prototype.isDirtyFormInput = function () { + $("input,select,textarea").blur(); + var that = this, message_window; + if (this.frmInputDocument.isVisible()) { + if (!this.externalType) { + if (!(this.checkIfValuesAreEqual(this.inputDocumentOriginDataForUpdate, getData2PMUI(this.frmInputDocument.html)))) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: "Input Documents".translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + if (typeof flagInputDocument != 'undefined' && flagInputDocument) { + if (that.clickedClose) { + message_window.close(); + that.winMainInputDocument.close(); + return; + } else { + that.winMainInputDocument.close(); + flagInputDocument = false; + } + return; + } else { + if (that.clickedClose) { + message_window.close(); + that.winMainInputDocument.close(); + return; + } else { + inputDocumentOption = ""; + that.openGridPanelInMainWindow(); + } + } + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + this.inputDocumentOriginDataForUpdate = {}; + } else { + if (that.clickedClose) { + this.winMainInputDocument.close(); + } else { + inputDocumentOption = ""; + this.openGridPanelInMainWindow(); + } + } + } else { + that.winMainInputDocument.close(); + } + } else { + that.winMainInputDocument.close(); + } +}; + +InputDocument.prototype.build = function () { + var ID = this, + btnSave, + btnCancel, + winMainInputDocument, + frmInputDocument, + grdpnlInputDocument, + btnNew, + inp_doc_destination_path, + inp_doc_tags, + that = this; + + btnSave = new PMUI.ui.Button({ + id: "btnSave", + text: "Save".translate(), + handler: function () { + var flagAux, data; + + if (!ID.frmInputDocument.isValid()) { + flagAux = ID.frmInputDocument.visible; + } else { + flagAux = ID.frmInputDocument.isValid(); + } + + if (flagAux) { + if (getData2PMUI(ID.frmInputDocument.html).inp_doc_title == "") { + return false; + } + } + + if (ID.frmInputDocument.getField("inp_doc_max_filesize").getValue() != "") { + if (!/^\+?(0|[1-9]\d*)$/.test(ID.frmInputDocument.getField("inp_doc_max_filesize").getValue())) { + return false; + } + } + + //validation because getData method do not work in IE + if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { + data = getData2PMUI(that.frmInputDocument.html); + } else { + data = that.frmInputDocument.getData(); + } + + data["inp_doc_versioning"] = parseInt(data["inp_doc_versioning"]); + + switch (that.method) { + case "POST": + that.inputDocumentPostRestProxy(data); + break; + case "PUT": + that.inputDocumentPutRestProxy(that.inputDocumentUid, data); + break; + } + }, + buttonType: 'success' + }); + + btnCancel = new PMUI.ui.Button({ + id: "btnCancel", + text: "Cancel".translate(), + handler: function () { + that.clickedClose = false; + that.isDirtyFormInput(); + }, + buttonType: 'error' + }); + btnNew = new PMUI.ui.Button({ + id: "btnNew", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + that.openFormInMainWindow(); + that.method = "POST"; + that.frmInputDocument.reset(); + } + }); + + /* form panel*/ + this.frmInputDocument = new PMUI.form.Form({ + id: "frmInputDocument", + width: 900, + visibleHeader: false, + items: [ + { + pmType: "text", + label: "Title".translate(), + id: "inputDocTitle", + name: "inp_doc_title", + valueType: 'string', + maxLength: 200, + required: true, + controlsWidth: 300 + }, + { + pmType: "dropdown", + name: "inp_doc_form_needed", + id: "inputDocDocumentType", + label: "Document Type".translate(), + value: "VIRTUAL", + controlsWidth: 130, + options: [ + { + value: "VIRTUAL", + label: "Digital".translate() + }, + { + value: "REAL", + label: "Printed".translate() + }, + { + value: "VREAL", + label: "Digital/Printed".translate() + } + ], + onChange: function (newValue, prevValue) { + var fields = that.frmInputDocument.getFields(); + if (newValue != "VIRTUAL") { + fields[2].setVisible(true); + } else { + fields[2].setVisible(false); + } + } + }, + { + pmType: "dropdown", + id: "inputDocDocumentType", + name: "inp_doc_original", + label: "Format".translate(), + value: "ORIGINAL", + controlsWidth: 105, + visible: false, + options: [ + { + value: "ORIGINAL", + label: "Original".translate() + }, + { + value: "COPYLEGAL", + label: "Legal Copy".translate() + }, + { + value: "COPY", + label: "Copy".translate() + } + ] + }, + { + pmType: "textarea", + id: "inputDocDescription", + name: "inp_doc_description", + label: "Description".translate(), + controlsWidth: 380, + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + pmType: "dropdown", + id: "inputDocEnableVersioning", + name: "inp_doc_versioning", + label: "Enable Versioning".translate(), + value: 0, + controlsWidth: 75, + options: [ + { + value: 0, + label: "NO".translate(), + selected: true + }, + { + value: 1, + label: "YES".translate() + } + ] + } + ], + buttonPanelPosition: 'top' + }); + inp_doc_destination_path = new CriteriaField({ + id: "inputDocDestinationPath", + name: "inp_doc_destination_path", + valueType: "string", + label: "Destination Path".translate(), + maxLength: 200, + controlsWidth: 380 + }); + + inp_doc_tags = new CriteriaField({ + id: "inputDocTags", + name: "inp_doc_tags", + valueType: "string", + label: "Tags".translate(), + maxLength: 200, + value: "INPUT", + controlsWidth: 380 + }); + + inp_doc_allowed = new PMUI.field.TextField({ + label: "Allowed file extensions (Use .* to allow any extension)".translate(), + id: "inputDocAllowedFileExtensions", + name: "inp_doc_type_file", + valueType: 'string', + maxLength: 200, + required: true, + value: ".*", + controlsWidth: 380 + + }); + + inp_doc_maximum = new PMUI.field.TextField({ + label: "Maximum file size (Use zero if unlimited)".translate(), + id: "inputDocMaximumFileSize", + name: "inp_doc_max_filesize", + valueType: 'string', + maxLength: 200, + required: true, + value: "0", + controlsWidth: 380, + validators: [ + { + pmType: "regexp", + criteria: /^\d*$/, + errorMessage: "Please enter a positive integer value".translate() + } + ] + + }); + + inp_doc_maximum_unit = new PMUI.field.DropDownListField({ + id: "inputDocUnit", + name: "inp_doc_max_filesize_unit", + label: "Unit".translate(), + value: "ORIGINAL", + controlsWidth: 105, + visible: true, + options: [ + { + value: "KB", + label: "KB".translate() + }, + { + value: "MB", + label: "MB".translate() + } + ] + }); + + that.frmInputDocument.addItem(inp_doc_destination_path); + that.frmInputDocument.addItem(inp_doc_tags); + that.frmInputDocument.addItem(inp_doc_allowed); + that.frmInputDocument.addItem(inp_doc_maximum); + that.frmInputDocument.addItem(inp_doc_maximum_unit); + + /*grid panel*/ + + this.grdpnlInputDocument = new PMUI.grid.GridPanel({ + id: "grdpnlInputDocument", + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'grdpnlInputDocumentButtonShow', + dataType: "button", + title: "", + buttonLabel: "Show ID".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + showUID(data.inp_doc_uid); + } + }, + { + columnData: "inp_doc_title", + title: "Title".translate(), + width: "607px", + alignment: "left", + sortable: true, + alignmentCell: 'left' + }, + { + id: 'grdpnlInputDocumentButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.inputDocumentOriginDataForUpdate = {}; + that.openFormInMainWindow(); + that.inputDocumentFormGetProxy(data.inp_doc_uid); + + } + }, + { + id: 'grdpnlInputDocumentButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + confirmWindow; + confirmWindow = new PMUI.ui.MessageWindow({ + id: "inputMessageWindowWarning", + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Input Documents".translate(), + message: "Do you want to delete this Input Document?".translate(), + footerItems: [ + { + id: 'confirmWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, + { + id: 'confirmWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + that.inputDocumentDeleteRestProxy(data.inp_doc_uid); + confirmWindow.close(); + confirmWindow.close(); + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = "17px"; + confirmWindow.showFooter(); + } + } + ], + dataItems: null + }); + /* main windows */ + this.winMainInputDocument = new PMUI.ui.Window({ + id: "winMainInputDocument", + title: "Input Documents".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: 'bottom', + footerAlign: 'right', + visibleFooter: true, + footerItems: [ + btnCancel, + btnSave + ], + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFormInput(); + } + }); + // add form and grid to windows + this.winMainInputDocument.addItem(this.grdpnlInputDocument); + this.winMainInputDocument.addItem(this.frmInputDocument); + this.winMainInputDocument.open(); + //custom css + this.frmInputDocument.getField("inp_doc_type_file").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_type_file").html.style.float = "left"; + this.frmInputDocument.getField("inp_doc_max_filesize").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_max_filesize").html.style.float = "left"; + this.frmInputDocument.getField("inp_doc_max_filesize_unit").html.style.padding = "6px 0"; + this.frmInputDocument.getField("inp_doc_max_filesize_unit").html.style.float = "left"; + this.grdpnlInputDocument.setVisible(true); + this.frmInputDocument.setVisible(false); + this.winMainInputDocument.hideFooter(); + /* insert create button to grid*/ + this.grdpnlInputDocument.dom.toolbar.appendChild(btnNew.getHTML()); + btnNew.defineEvents(); + this.inputDocumentsGetRestProxy(); +}; + +(function () { + + var loadValuesStartTimer, openForm, updateStatus; + + PMDesigner.startTimer = function (element) { + + var startTimer = element, + restClient, + loadServerData, + listUsers, + itemsDaly, + itemsWeekly, + loadOptionsRadio, + itemsMonthly, + itemsOneTime, + itemsEvery, + showProperties, + updateCaseScheduler, + buttonCancel, + loadUsers, + loadDataForm, + formCreateCaseScheduler, + schedulerListWindow, + buttonSave, + dataForm; + + loadValuesStartTimer = function ($flag) { + listUsers = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startTimer.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: 'case-scheduler/' + startTimer.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + dataForm = response[1].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: [null, 'There are problems loading the Start Timer, please try again.'.translate()] + }); + restClient.executeRestClient(); + if ($flag) { + return listUsers.length; + } + return true; + }; + + updateCaseScheduler = function (data) { + var restProxy = new PMRestClient({ + endpoint: 'case-scheduler/' + startTimer.evn_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Start Timer updated successfully'.translate(), + messageError: 'There are problems updating the Start Timer, please try again.'.translate(), + flashContainer: document.body + }); + restProxy.executeRestClient(); + }; + + updateStatus = function () { + var status = (typeof dataForm.sch_state !== 'undefined') ? ((dataForm.sch_state === 'ACTIVE') ? 'INACTIVE' : 'ACTIVE') : 'INACTIVE'; + dataForm.sch_state = status; + updateCaseScheduler(dataForm); + }; + + //Items for the form Create and edit Case Scheduler + itemsDaly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + } + ]; + + itemsWeekly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + id: 'daysoftheweek', + pmType: 'checkbox', + label: 'Select the day(s) of the week below'.translate(), + value: '', + name: 'daysoftheweek', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + id: 'monday', + label: 'Monday'.translate(), + value: '1' + }, + { + id: 'tuesday', + label: 'Tuesday'.translate(), + value: '2' + }, + { + id: 'wednesday', + label: 'Wednesday'.translate(), + value: '3' + }, + { + id: 'thursday', + label: 'Thursday'.translate(), + value: '4' + }, + { + id: 'friday', + label: 'Friday'.translate(), + value: '5' + }, + { + id: 'saturday', + label: 'Saturday'.translate(), + value: '6' + }, + { + id: 'sunday', + label: 'Sunday'.translate(), + value: '7' + } + ] + } + ]; + + loadOptionsRadio = function (newVal) { + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(true); + if (newVal === 'dayofmonth') { + paneldaysofMonth.getItems()[0].setVisible(true); + paneldaysofMonth.getItems()[1].setVisible(false); + } else if (newVal === 'day') { + paneldaysofMonth.getItems()[0].setVisible(false); + paneldaysofMonth.getItems()[1].setVisible(true); + } + }; + + itemsMonthly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + datetime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + datetime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + controlsWidth: 580, + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + pmType: 'panel', + id: 'panelDays', + layout: 'hbox', + items: [ + { + id: 'options', + pmType: 'radio', + label: '', + value: '', + name: 'options', + required: false, + controlPositioning: 'vertical', + maxDirectionOptions: 4, + options: [ + { + id: 'dayMonth', + label: 'Day of month'.translate(), + value: 'dayofmonth' + }, + { + id: 'day', + label: 'The day'.translate(), + value: 'day' + } + ], + onChange: function (newVal, oldVal) { + loadOptionsRadio(newVal); + }, + labelWidth: '46%' + }, + { + pmType: 'panel', + id: 'paneldaysofMonth', + layout: 'vbox', + items: [ + { + id: 'dayoftheMonth', + pmType: 'text', + label: '', + value: '', + placeholder: 'Day of the month (example: 1)'.translate(), + required: false, + name: 'dayMonth', + valueType: 'string' + }, + { + pmType: 'panel', + id: 'panelmonth', + layout: 'hbox', + items: [ + { + id: 'first', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'first', + valueType: 'string', + options: [ + { + label: 'First'.translate(), + value: '1' + }, + { + label: 'Second'.translate(), + value: '2' + }, + { + label: 'Third'.translate(), + value: '3' + }, + { + label: 'Fourth'.translate(), + value: '4' + }, + { + label: 'Last'.translate(), + value: '5' + } + ], + controlsWidth: 100 + }, + { + id: 'day', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'day', + valueType: 'string', + options: [ + { + label: 'Monday'.translate(), + value: '1' + }, + { + label: 'Tuesday'.translate(), + value: '2' + }, + { + label: 'Wednesday'.translate(), + value: '3' + }, + { + label: 'Thursday'.translate(), + value: '4' + }, + { + label: 'Friday'.translate(), + value: '5' + }, + { + label: 'Saturday'.translate(), + value: '6' + }, + { + label: 'Sunday'.translate(), + value: '7' + } + ], + controlsWidth: 100 + } + ] + } + ] + } + ] + }, + { + id: 'months', + pmType: 'checkbox', + label: 'Of the month(s)'.translate(), + value: '', + name: 'months', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'jan', + label: 'Jan'.translate(), + value: '1' + }, + { + id: 'feb', + label: 'Feb'.translate(), + value: '2' + }, + { + id: 'mar', + label: 'Mar'.translate(), + value: '3' + }, + { + id: 'apr', + label: 'Apr'.translate(), + value: '4' + }, + { + id: 'may', + label: 'May'.translate(), + value: '5' + }, + { + id: 'jun', + label: 'Jun'.translate(), + value: '6' + }, + { + id: 'jul', + label: 'Jul'.translate(), + value: '7' + }, + { + id: 'aug', + label: 'Aug'.translate(), + value: '8' + }, + { + id: 'sep', + label: 'Sep'.translate(), + value: '9' + }, + { + id: 'oct', + label: 'Oct'.translate(), + value: '10' + }, + { + id: 'nov', + label: 'Nov'.translate(), + value: '11' + }, + { + id: 'dec', + label: 'Dec'.translate(), + value: '12' + } + ] + } + ]; + + itemsOneTime = [{ + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + itemsEvery = [{ + id: 'execttime', + pmType: 'text', + label: 'Execute every Hour(s)'.translate(), + value: '', + required: true, + name: 'execttime', + valueType: 'string', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + showProperties = function (newValue) { + switch (newValue) { + case 'daily': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsDaly); + break; + case 'weekly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsWeekly); + break; + case 'monthly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsMonthly); + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(false); + formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[1].hideColon(); + break; + case 'oneTime': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsOneTime); + break; + case 'every': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsEvery); + validateKeysField(formCreateCaseScheduler.getField('execttime').getControls()[0].getHTML(), ['isnumber', 'iscolon']); + break; + } + }; + + //Form to Edit and create the Case Scheduler + formCreateCaseScheduler = new PMUI.form.Form({ + id: 'formCreateCaseScheduler', + border: false, + visibleHeader: false, + width: '925px', + name: 'formcreate', + title: '', + items: [ + { + id: 'panelProperties', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + height: '350px', + legend: 'Properties'.translate(), + items: [ + { + id: 'state', + pmType: 'dropdown', + label: 'Status'.translate(), + name: 'state', + required: true, + value: '', + controlsWidth: 150, + options: [ + { + value: 'ACTIVE', + label: 'Active'.translate() + }, + { + value: 'INACTIVE', + label: 'Inactive'.translate() + } + ] + }, + { + id: 'username', + pmType: 'dropdown', + label: 'User'.translate(), + name: 'username', + required: true, + controlsWidth: 300, + value: '', + options: [], + onChange: function (newValue, prevValue) { + } + }, + { + id: 'name', + pmType: 'text', + label: 'Name'.translate(), + value: startTimer.evn_name, + required: true, + name: 'name', + visible: false, + valueType: 'string' + }, + { + id: 'performTask', + pmType: 'dropdown', + label: 'Perform this task'.translate(), + name: 'performTask', + required: true, + value: '', + controlsWidth: 300, + options: [ + { + label: '- Select -'.translate(), + value: '', + disabled: true, + selected: true + }, + { + value: 'daily', + label: 'Daily'.translate() + }, + { + value: 'weekly', + label: 'Weekly'.translate() + }, + { + value: 'monthly', + label: 'Monthly'.translate() + }, + { + value: 'oneTime', + label: 'One Time Only'.translate() + }, + { + value: 'every', + label: 'Every'.translate() + } + ], + onChange: function (newValue, prevValue) { + showProperties(newValue); + } + } + ] + }, + { + id: 'panelSelectDate', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + visible: false, + height: '350px', + legend: 'Select the date and time for case(s) to be initiated.'.translate(), + items: [] + } + ] + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelSchedulerButton', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function (event) { + if (formCreateCaseScheduler.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: 'cancelMessageStartTimer', + title: 'Start Timer Event'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + schedulerListWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + } + } + }); + + //Window Buttons + buttonSave = new PMUI.ui.Button({ + id: 'saveSchedulerButton', + text: 'Save'.translate(), + height: 31, + buttonType: 'success', + handler: function (event) { + if (formCreateCaseScheduler.isValid()) { + var dataFormCreate = formCreateCaseScheduler.getData(); + + var dataToSend = { + sch_del_user_name: dataFormCreate.username, + sch_name: startTimer.evn_name, + tas_uid: startTimer.ports.get(0).connection.flo_element_dest, + sch_start_time: '', + sch_start_date: '', + sch_week_days: '', + sch_start_day: '', + sch_start_day_opt_1: '', + sch_start_day_opt_2: '', + sch_months: '', + sch_end_date: '', + sch_repeat_every: '', + sch_state: (dataFormCreate.state !== '') ? dataFormCreate.state : 'ACTIVE', + sch_option: '' + }; + + var perform = dataFormCreate.performTask; + switch (perform) { + case 'daily': + dataToSend.sch_option = '1'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + break; + case 'weekly': + var formdays = eval(dataFormCreate.daysoftheweek); + var days = ''; + for (i = 0; i < formdays.length; i += 1) { + if (i !== (formdays.length - 1)) { + days += formdays[i] + '|'; + } else { + days += formdays[i]; + } + } + + dataToSend.sch_option = '2'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + dataToSend.sch_week_days = days; + break; + case 'monthly': + dataToSend.sch_option = '3'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + if (dataFormCreate.options === 'dayofmonth') { + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '1'; //Day of month + dataToSend.sch_start_day_opt_1 = dataFormCreate.dayMonth;//1 to 31 - day of the month + } else if (dataFormCreate.options === 'day') { + var opt2 = dataFormCreate.first + '|' + dataFormCreate.day; + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '2'; //Day of month + dataToSend.sch_start_day_opt_2 = opt2;//1 to 31 - day of the month + + } + dataToSend.sch_months = months; + break; + case 'oneTime': + dataToSend.sch_option = '4'; + dataToSend.sch_start_time = dataFormCreate.execttime; + break; + case 'every': + dataToSend.sch_option = '5'; + dataToSend.sch_repeat_every = timeToDecimal(dataFormCreate.execttime).toFixed(2); + break; + } + updateCaseScheduler(dataToSend); + } + } + }); + + //load users + loadUsers = function () { + var field = formCreateCaseScheduler.getField('username'); + field.clearOptions(); + for (var i = 0; i < listUsers.length; i += 1) { + field.addOption({ + value: listUsers[i].aas_username, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + var loadTime, + option, + daysVal, + monthsVal, + monthsop, + days, + i, + startTime, + finallyST, + dataEdit; + + loadTime = function (dataEdit, dataForm) { + var starDate, + startTime, + finallyST, + endDate; + starDate = dataForm.sch_start_date ? dataForm.sch_start_date.split(' ') : ['']; + endDate = dataForm.sch_end_date ? dataForm.sch_end_date.split(' ') : ['']; + + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(starDate[0]); + dataEdit[5].setValue(endDate[0]); + dataEdit[6].setValue(finallyST); + }; + + dataEdit = formCreateCaseScheduler.getFields(); + + dataEdit[0].setValue(dataForm.sch_state); + dataEdit[1].setValue(dataForm.sch_del_user_name); + option = 'daily'; + switch (dataForm.sch_option) { + case '1': + option = 'daily'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + break; + case '2': + option = 'weekly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + + daysVal = "[\""; + days = dataForm.sch_week_days.split('|'); + for (i = 0; i < days.length; i += 1) { + if (i !== (days.length - 1)) { + daysVal += days[i] + "\",\""; + } else { + daysVal += days[i] + "\"]"; + } + } + dataEdit[7].setValue(daysVal); + break; + case '3': + option = 'monthly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + days = []; + if (dataForm.sch_start_day !== '') { + days = dataForm.sch_start_day.split('|'); + } + + if (days[0] === '1') { + dataEdit[7].setValue('dayofmonth'); + loadOptionsRadio('dayofmonth'); + dataEdit[8].setValue(days[1]); + } else if (days[0] === '2') { + dataEdit[7].setValue('day'); + loadOptionsRadio('day'); + dataEdit[9].setValue(days[1]); + dataEdit[10].setValue(days[2]); + } + monthsVal = "[\""; + monthsop = dataForm.sch_months.split('|'); + for (i = 0; i < monthsop.length; i += 1) { + if (i !== (monthsop.length - 1)) { + monthsVal += monthsop[i] + "\",\""; + } else { + monthsVal += monthsop[i] + "\"]"; + } + } + dataEdit[11].setValue(monthsVal); + break; + case '4': + option = 'oneTime'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(finallyST); + break; + case '5': + option = 'every'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + dataEdit[4].setValue(decimalToTime(parseFloat(dataForm.sch_repeat_every))); + break; + } + }; + + //Main window Case Scheduler + schedulerListWindow = new PMUI.ui.Window({ + id: 'schedulerListWindow', + title: 'Start Timer Event'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: 'top', + buttons: [ + buttonSave, + {pmType: 'label', text: 'or'}, + buttonCancel + ] + }); + + openForm = function () { + schedulerListWindow.addItem(formCreateCaseScheduler); + schedulerListWindow.open(); + loadUsers(); + loadDataForm(); + applyStyleWindowForm(schedulerListWindow); + schedulerListWindow.showFooter(); + schedulerListWindow.defineEvents(); + }; + }; + + PMDesigner.startTimer.openForm = function (element) { + openForm(); + }; + + PMDesigner.startTimer.validate = function (element) { + if (element.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 3000, 5); + return false; + } + PMDesigner.startTimer(element); + if (loadValuesStartTimer(true) === 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 3000, 5); + return false; + } + return true; + }; + +}()); +( + function () { + var dataBaseConnectionOption, + winFrmDataBaseConnectionShow, + frmDataBaseConnection, + closeClicked = true; + + PMDesigner.database = function (event) { + var winGrdpnlDataBaseConnection, + panelTest, + grdpnlDataBaseConnection, + flagError, + titleOld, + btnNew, + btnTestConnection, + btnCreate, + btnCancel, + testShow, + isDirtyFrmDataBaseConnection, + showForm, + listDBConnection, + refreshGridPanelInMainWindow, + dataBaseConnectionsGetRestProxy, + dataBaseConnectionPostTestRestProxy, + dataBaseConnectionGetRestProxy, + dataBaseConnectionPutRestProxy, + dataBaseConnectionDeleteRestProxy, + dataBaseConnectionPostRestProxy, + cboEngineSetOptionsRestProxy, + showEncoderOptions, + hideEncoderOptions, + cboConnectionTypeOracleSetOptions, + cboEncodeSetOptionsRestProxy, + winFrmDataBaseConnectionShow, + cboEngine, + txtUID, + cboEncode, + txtTns, + txtServer, + txtDataBaseName, + disableAllItems, + txtUsername, + txtPassword, + txtPort, + btnBack, + txtDescription, + cboConnectionTypeOracle, + dataBaseConnectionData; + + disableAllItems = function () { + winGrdpnlDataBaseConnection.getItems()[0].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(false); + + txtUID.setVisible(false); + btnTestConnection.setVisible(false); + btnBack.setVisible(false); + btnCreate.setVisible(false); + btnCancel.setVisible(false); + }; + + testShow = function (testData) { + var msg = "", titleSummary, style, i, flag; + flagError = 0; + disableAllItems(); + titleOld = winGrdpnlDataBaseConnection.getTitle(); + winGrdpnlDataBaseConnection.setTitle("Testing Server Connection".translate()); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(true); + + for (i = 0; i <= testData.length - 1; i += 1) { + flag = (typeof(testData[i].error) != "undefined") ? 1 : 0; + if (flag != 1) { + msg = msg + "" + testData[i].test + "
"; + } else { + msg = msg + "" + testData[i].error + "
"; + } + + if (typeof(testData[i].error) != "undefined" && flagError == 0) { + flagError = 1; + } + } + if (flag == 0) { + btnCreate.setVisible(true); + btnBack.setVisible(true); + } else { + btnBack.setVisible(true); + } + + titleSummary = "
Testing Database Server configuration
"; + + style = $('#panelTest').attr("style"); + titleSummary = titleSummary + "
" + msg + "
"; + $('#panelTest').empty(); + style = style + ' background: #FFFFFF; font: normal 0.8em arial;'; + $('#panelTest').attr("style", style); + $('#panelTest').append(titleSummary); + }; + + isDirtyFrmDataBaseConnection = function () { + var message_window; + $("input,select,textarea").blur(); + if (frmDataBaseConnection.isVisible()) { + if (frmDataBaseConnection.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Database Connections".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + dataBaseConnectionOption = ""; + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } + refreshGridPanelInMainWindow(false); + }, + buttonType: "success" + } + ], + title: 'Confirm'.translate() + }); + message_window.open(); + message_window.showFooter(); + } else { + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } else { + dataBaseConnectionOption = ""; + refreshGridPanelInMainWindow(false); + } + } + } else { + winGrdpnlDataBaseConnection.close(); + } + }; + showForm = function () { + disableAllItems(); + winGrdpnlDataBaseConnection.setTitle(titleOld); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); + } + + refreshGridPanelInMainWindow = function (load) { + disableAllItems(); + winGrdpnlDataBaseConnection.hideFooter(); + dataBaseConnectionOption = ""; + winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); + winGrdpnlDataBaseConnection.setTitle("Database Connections".translate()); + load = load != null ? load : true; + if (load) { + dataBaseConnectionsGetRestProxy(grdpnlDataBaseConnection); + } + }; + + dataBaseConnectionsGetRestProxy = function (grdpnl) { + var restProxy = new PMRestClient({ + endpoint: "database-connections", + typeRequest: "get", + functionSuccess: function (xhr, response) { + listDBConnection = response; + grdpnl.setDataItems(listDBConnection); + grdpnl.sort('dbs_database_name', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostTestRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/test", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + testShow(response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionGetRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response; + dataBaseConnectionOption = "PUT"; + winFrmDataBaseConnectionShow("PUT", data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPutRestProxy = function (dataBaseConnectionUid, data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Database connection edited successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + + restProxy.executeRestClient(); + }; + + dataBaseConnectionDeleteRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "remove", + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Database connection deleted successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + refreshGridPanelInMainWindow(); + }, + messageError: 'An unexpected error while deleting the DB Connection, please try again later.'.translate(), + messageSuccess: 'Database connection saved successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + + restProxy.executeRestClient(); + }; + + cboEngineSetOptionsRestProxy = function (cboEngine, cboEncode) { + cboEngine.clearOptions(); + var restProxy = new PMRestClient({ + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, + i, + arrayOptions = []; + for (i = 0; i <= data.length - 1; i += 1) { + arrayOptions.push( + { + value: data[i].id, + label: data[i].name + } + ); + } + cboEngine.setOptions(arrayOptions); + cboEngine.setValue(arrayOptions[0].value); + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.setBaseEndPoint("system/db-engines"); + restProxy.executeRestClient(); + }; + + hideEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(true); + }; + + showEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(false); + }; + cboConnectionTypeOracleSetOptions = function (cboConnectionTypeOracle) { + var arrayEnconde = [], + i, + arrayOptions = []; + cboConnectionTypeOracle.clearOptions(); + + arrayEnconde = [ + {"value": "NORMAL", "text": "Normal"}, + {"value": "TNS", "text": "TNS"} + ]; + + for (i = 0; i <= arrayEnconde.length - 1; i += 1) { + arrayOptions.push( + { + value: arrayEnconde[i].value, + label: arrayEnconde[i].text + } + ); + } + + cboConnectionTypeOracle.setOptions(arrayOptions); + }; + cboEncodeSetOptionsRestProxy = function (selectedCboEngineValue, cboEncode) { + var arrayEnconde = [], + arrayNewEnconde, + i, + portsDefault, + arrayOptions, + encode = selectedCboEngineValue; + cboEncode.clearOptions(); + + arrayEnconde["mysql"] = [ + {"value": "big5", "text": "big5 - Big5 Traditional Chinese"}, + {"value": "dec8", "text": "dec8 - DEC West European"}, + {"value": "cp850", "text": "cp850 - DOS West European"}, + {"value": "hp8", "text": "hp8 - HP West European"}, + {"value": "koi8r", "text": "koi8r - KOI8-R Relcom Russian"}, + {"value": "latin1", "text": "latin1 - cp1252 West European"}, + {"value": "latin2", "text": "latin2 - ISO 8859-2 Central European"}, + {"value": "swe7", "text": "swe7 - 7bit Swedish"}, + {"value": "ascii", "text": "ascii - US ASCII"}, + {"value": "ujis", "text": "ujis - EUC-JP Japanese"}, + {"value": "sjis", "text": "sjis - Shift-JIS Japanese"}, + {"value": "hebrew", "text": "hebrew - ISO 8859-8 Hebrew"}, + {"value": "tis620", "text": "tis620 - TIS620 Thai"}, + {"value": "euckr", "text": "euckr - EUC-KR Korean"}, + {"value": "koi8u", "text": "koi8u - KOI8-U Ukrainian"}, + {"value": "gb2312", "text": "gb2312 - GB2312 Simplified Chinese"}, + {"value": "greek", "text": "greek - ISO 8859-7 Greek"}, + {"value": "cp1250", "text": "cp1250 - Windows Central European"}, + {"value": "gbk", "text": "gbk - GBK Simplified Chinese"}, + {"value": "latin5", "text": "latin5 - ISO 8859-9 Turkish"}, + {"value": "armscii8", "text": "armscii8 - ARMSCII-8 Armenian"}, + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"}, + {"value": "ucs2", "text": "ucs2 - UCS-2 Unicode"}, + {"value": "cp866", "text": "cp866 - DOS Russian"}, + {"value": "keybcs2", "text": "keybcs2 - DOS Kamenicky Czech-Slovak"}, + {"value": "macce", "text": "macce - Mac Central European"}, + {"value": "macroman", "text": "macroman - Mac West European"}, + {"value": "cp852", "text": "cp852 - DOS Central European"}, + {"value": "latin7", "text": "atin7 - ISO 8859-13 Baltic"}, + {"value": "cp1251", "text": "cp1251 - Windows Cyrillic"}, + {"value": "cp1256", "text": "cp1256 - Windows Arabic"}, + {"value": "cp1257", "text": "cp1257 - Windows Baltic"}, + {"value": "binary", "text": "binary - Binary pseudo charset"}, + {"value": "geostd8", "text": "geostd8 - GEOSTD8 Georgian"}, + {"value": "cp932", "text": "cp932] - SJIS for Windows Japanese"}, + {"value": "eucjpms", "text": "eucjpms - UJIS for Windows Japanese"} + ]; + + arrayEnconde["pgsql"] = [ + {"value": "BIG5", "text": "BIG5"}, + {"value": "EUC_CN", "text": "EUC_CN"}, + {"value": "EUC_JP", "text": "EUC_JP"}, + {"value": "EUC_KR", "text": "EUC_KR"}, + {"value": "EUC_TW", "text": "EUC_TW"}, + {"value": "GB18030", "text": "GB18030"}, + {"value": "GBK", "text": "GBK"}, + {"value": "ISO_8859_5", "text": "ISO_8859_5"}, + {"value": "ISO_8859_6", "text": "ISO_8859_6"}, + {"value": "ISO_8859_7", "text": "ISO_8859_7"}, + {"value": "ISO_8859_8", "text": "ISO_8859_8"}, + {"value": "JOHAB", "text": "JOHAB"}, + {"value": "KOI8", "text": "KOI8"}, + {"value": "selected", "text": "LATIN1"}, + {"value": "LATIN2", "text": "LATIN2"}, + {"value": "LATIN3", "text": "LATIN3"}, + {"value": "LATIN4", "text": "LATIN4"}, + {"value": "LATIN5", "text": "LATIN5"}, + {"value": "LATIN6", "text": "LATIN6"}, + {"value": "LATIN7", "text": "LATIN7"}, + {"value": "LATIN8", "text": "LATIN8"}, + {"value": "LATIN9", "text": "LATIN9"}, + {"value": "LATIN10", "text": "LATIN10"}, + {"value": "SJIS", "text": "SJIS"}, + {"value": "SQL_ASCII", "text": "SQL_ASCII"}, + {"value": "UHC", "text": "UHC"}, + {"value": "UTF8", "text": "UTF8"}, + {"value": "WIN866", "text": "WIN866"}, + {"value": "WIN874", "text": "WIN874"}, + {"value": "WIN1250", "text": "WIN1250"}, + {"value": "WIN1251", "text": "WIN1251"}, + {"value": "WIN1252", "text": "WIN1252"}, + {"value": "WIN1256", "text": "WIN1256"}, + {"value": "WIN1258", "text": "WIN1258"} + ]; + + arrayEnconde["mssql"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; + + arrayEnconde["oracle"] = [ + {"value": "UTF8", "text": "UTF8 - Unicode 3.0 UTF-8 Universal character set, CESU-8 compliant"}, + {"value": "UTFE", "text": "UTFE - EBCDIC form of Unicode 3.0 UTF-8 Universal character set"}, + {"value": "AL16UTF16", "text": "AL16UTF16 - Unicode 3.1 UTF-16 Universal character set"}, + {"value": "AL32UTF8", "text": "AL32UTF8 - Unicode 3.1 UTF-8 Universal character set"} + ]; + + arrayEnconde["sqlsrv"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; + + arrayNewEnconde = (typeof(arrayEnconde[encode]) != "undefined") ? arrayEnconde[encode] : []; + arrayOptions = []; + + for (i = 0; i <= arrayNewEnconde.length - 1; i += 1) { + arrayOptions.push( + { + value: arrayNewEnconde[i].value, + label: arrayNewEnconde[i].text + } + ); + } + + cboEncode.setOptions(arrayOptions); + cboEncode.setValue('utf8'); + + portsDefault = ["3306", "5432", "1433", "1521"]; + switch (encode) { + case "mysql": + txtPort.setValue(portsDefault[0]); + showEncoderOptions(); + break; + case "pgsql": + txtPort.setValue(portsDefault[1]); + showEncoderOptions(); + break; + case "mssql": + txtPort.setValue(portsDefault[2]); + showEncoderOptions(); + break; + case "oracle": + txtPort.setValue(portsDefault[3]); + hideEncoderOptions(); + break; + } + }; + + winFrmDataBaseConnectionShow = function (option, data) { + disableAllItems(); + dataBaseConnectionData = data; + frmDataBaseConnection.reset(); + cboEngineSetOptionsRestProxy(cboEngine, cboEncode); + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); + winGrdpnlDataBaseConnection.showFooter(); + + switch (option) { + case "POST": + winGrdpnlDataBaseConnection.setTitle("Create Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + txtServer.setVisible(true); + txtServer.setRequired(true); + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + txtPort.setVisible(true); + txtPort.setRequired(true); + txtPort.setValue("3306"); + break; + case "PUT": + winGrdpnlDataBaseConnection.setTitle("Edit Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtUID.setVisible(true); + txtUID.setValue(dataBaseConnectionData.dbs_uid); + cboEngine.setValue(dataBaseConnectionData.dbs_type); + cboEncodeSetOptionsRestProxy(dataBaseConnectionData.dbs_type, cboEncode); + cboEncode.setValue(dataBaseConnectionData.dbs_encode); + txtServer.setValue(dataBaseConnectionData.dbs_server); + txtDataBaseName.setValue(dataBaseConnectionData.dbs_database_name); + txtUsername.setValue(dataBaseConnectionData.dbs_username); + txtPassword.setValue(dataBaseConnectionData.dbs_password); + txtPort.setValue(dataBaseConnectionData.dbs_port); + txtDescription.setValue(dataBaseConnectionData.dbs_description); + + if (dataBaseConnectionData.dbs_type == "oracle") { + cboConnectionTypeOracle.setValue(dataBaseConnectionData.dbs_connection_type); + cboConnectionTypeOracle.setVisible(true); + + if (dataBaseConnectionData.dbs_connection_type == "TNS" && dataBaseConnectionData.dbs_tns != "") { + txtTns.setValue(dataBaseConnectionData.dbs_tns); + txtTns.setVisible(true); + txtTns.setRequired(true); + + txtServer.setValue(""); + txtServer.setVisible(false); + txtServer.setRequired(false); + + txtDataBaseName.setValue(""); + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); + + txtPort.setValue(""); + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + break; + } + frmDataBaseConnection.setFocus(); + }; + + txtUID = new PMUI.field.TextField({ + id: "txtUID", + name: "txtUID", + valueType: "string", + controlsWidth: 300, + label: "UID".translate(), + maxLength: 200, + readOnly: true, + visible: false + }); + + cboEngine = new PMUI.field.DropDownListField({ + id: "cboEngine", + name: "cboEngine", + label: "Engine".translate(), + options: null, + controlsWidth: 150, + onChange: function (newValue, prevValue) { + if (cboEngine.getValue() == "oracle") { + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setVisible(true); + txtPort.setRequired(true); + } + + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); + } + }); + + cboEncode = new PMUI.field.DropDownListField({ + id: "cboEncode", + name: "cboEncode", + label: "Encode".translate(), + options: null, + controlsWidth: 300 + }); + + cboConnectionTypeOracle = new PMUI.field.DropDownListField({ + id: "cboConnectionTypeOracle", + name: "cboConnectionTypeOracle", + label: "Select Connection Type".translate(), + options: null, + controlsWidth: 300, + + onChange: function (newValue, prevValue) { + if (cboConnectionTypeOracle.getValue() != "NORMAL") { + txtTns.setVisible(true); + txtTns.setRequired(true); + + txtServer.setVisible(false); + txtServer.setRequired(false); + + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); + + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); + + txtServer.setVisible(true); + txtServer.setRequired(true); + + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + + txtPort.setValue("1521"); + txtPort.setVisible(true); + txtPort.setRequired(true); + } + } + }); + + txtTns = new PMUI.field.TextField({ + id: "txtTns", + name: "txtTns", + valueType: "txtTns", + controlsWidth: 300, + label: "TNS".translate(), + maxLength: 200, + visible: false, + required: true + }); + + txtServer = new PMUI.field.TextField({ + id: "txtServer", + name: "txtServer", + valueType: "string", + controlsWidth: 300, + label: "Server".translate(), + maxLength: 200, + required: true + }); + + txtDataBaseName = new PMUI.field.TextField({ + id: "txtDataBaseName", + name: "txtDataBaseName", + valueType: "string", + controlsWidth: 300, + label: "Database Name".translate(), + maxLength: 200, + required: true + }); + + txtUsername = new PMUI.field.TextField({ + id: "txtUsername", + name: "txtUsername", + valueType: "string", + controlsWidth: 300, + label: "Username".translate(), + maxLength: 200, + required: true + }); + + txtPassword = new PMUI.field.PasswordField({ + id: "txtPassword", + name: "txtPassword", + valueType: "string", + controlsWidth: 300, + label: "Password".translate(), + maxLength: 200 + }); + + txtPort = new PMUI.field.TextField({ + id: "txtPort", + name: "txtPort", + valueType: "string", + controlsWidth: 300, + label: "Port".translate(), + value: "3306", + controlsWidth: 300, + maxLength: 200, + required: true + }); + + txtDescription = new PMUI.field.TextAreaField({ + id: "txtDescription", + name: "txtDescription", + valueType: "string", + controlsWidth: 500, + label: "Description".translate(), + height: "200px", + style: {cssClasses: ['mafe-textarea-resize']} + }); + + btnTestConnection = new PMUI.ui.Button({ + id: "btnTestConnection", + text: "Test Connection".translate(), + buttonType: 'success', + handler: function () { + var data; + if (frmDataBaseConnection.isValid()) { + if (cboEngine.getValue() == "oracle") { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_connection_type: cboConnectionTypeOracle.getValue(), + dbs_tns: txtTns.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } else { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } + dataBaseConnectionPostTestRestProxy(data); + } + } + }); + + btnCreate = new PMUI.ui.Button({ + id: "btnCreate", + text: "Save".translate(), + buttonType: "success", + handler: function () { + var data; + if (cboEngine.getValue() == "oracle") { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_connection_type: cboConnectionTypeOracle.getValue(), + dbs_tns: txtTns.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: getData2PMUI(frmDataBaseConnection.html).txtPassword, + dbs_port: parseInt(getData2PMUI(frmDataBaseConnection.html).txtPort), + dbs_description: txtDescription.getValue() + }; + } else { + data = { + dbs_type: cboEngine.getValue(), + dbs_encode: cboEncode.getValue(), + dbs_server: txtServer.getValue(), + dbs_database_name: txtDataBaseName.getValue(), + dbs_username: txtUsername.getValue(), + dbs_password: txtPassword.getValue(), + dbs_port: parseInt(txtPort.getValue()), + dbs_description: txtDescription.getValue() + }; + } + + switch (dataBaseConnectionOption) { + case "POST": + if (frmDataBaseConnection.isValid()) { + dataBaseConnectionPostRestProxy(data); + } else { + return; + } + break; + case "PUT": + if (frmDataBaseConnection.isValid()) { + dataBaseConnectionPutRestProxy(dataBaseConnectionData.dbs_uid, data); + } else { + return; + } + break; + } + } + }); + + btnCancel = new PMUI.ui.Button({ + id: "btnCancel", + text: "Cancel".translate(), + buttonType: 'error', + handler: function () { + closeClicked = false; + isDirtyFrmDataBaseConnection(); + } + }); + + btnBack = new PMUI.ui.Button({ + id: "btnBack", + text: "Back".translate(), + handler: function () { + showForm(); + } + }); + + frmDataBaseConnection = new PMUI.form.Form({ + id: "frmDataBaseConnection", + width: DEFAULT_WINDOW_WIDTH - 70, + items: [ + txtUID, + cboEngine, + cboEncode, + cboConnectionTypeOracle, + txtTns, + txtServer, + txtDataBaseName, + txtUsername, + txtPassword, + txtPort, + txtDescription + ] + }); + + txtPort.controls[0].onKeyUp = function () { + var txtPortfinalValue, + txtPortValue = getData2PMUI(frmDataBaseConnection.html).txtPort; + if (/\D/.test(txtPortValue)) { + if (isNaN(parseInt(txtPortValue))) { + txtPortfinalValue = ""; + } else { + txtPortfinalValue = parseInt(txtPortValue); + } + txtPort.setValue(txtPortfinalValue); + } + }; + + btnNew = new PMUI.ui.Button({ + id: "btnNew", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + dataBaseConnectionOption = "POST"; + winFrmDataBaseConnectionShow("POST", {}); + } + }); + + grdpnlDataBaseConnection = new PMUI.grid.GridPanel({ + id: "grdpnlDataBaseConnection", + filterable: true, + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'grdpnlDataBaseConnectionButtonShow', + dataType: "button", + title: "", + buttonLabel: "Show ID".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + width: "100px", + onButtonClick: function (row, grid) { + showUID(row.getData().dbs_uid); + } + }, + { + columnData: "dbs_type", + title: "Type".translate(), + width: "100px", + sortable: true, + alignmentCell: 'left' + }, + { + columnData: "dbs_server", + title: "Server".translate(), + width: "155px", + alignmentCell: 'left' + }, + { + columnData: "dbs_database_name", + title: "Database Name".translate(), + width: "160px", + sortable: true, + alignmentCell: 'left' + }, + { + columnData: "dbs_description", + title: "Description".translate(), + width: "200px", + alignmentCell: 'left' + }, + { + id: 'grdpnlDataBaseConnectionButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + dataBaseConnectionGetRestProxy(row.getData().dbs_uid); + } + }, + { + id: 'grdpnlDataBaseConnectionButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + var msgWarning = new PMUI.ui.MessageWindow({ + id: "msgWarning", + title: 'Database Connections'.translate(), + windowMessageType: 'warning', + width: 490, + message: "Do you want to delete this DB Connection?".translate(), + buttons: [ + { + text: "No".translate(), + handler: function () { + msgWarning.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + dataBaseConnectionDeleteRestProxy(data.dbs_uid); + msgWarning.close(); + }, + buttonType: "success" + } + ] + }); + msgWarning.open(); + msgWarning.showFooter(); + } + } + ], + dataItems: null + }); + + panelTest = new PMUI.core.Panel({ + id: 'panelTest', + height: DEFAULT_WINDOW_HEIGHT - 71, + display: 'inline-block' + }); + + winGrdpnlDataBaseConnection = new PMUI.ui.Window({ + id: "winGrdpnlDataBaseConnection", + title: "Database Connections".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + buttonPanelPosition: "bottom", + buttons: [btnCancel, btnBack, btnTestConnection, btnCreate], + onBeforeClose: function () { + closeClicked = true; + isDirtyFrmDataBaseConnection(); + } + }); + + winGrdpnlDataBaseConnection.addItem(grdpnlDataBaseConnection); + winGrdpnlDataBaseConnection.addItem(frmDataBaseConnection); + winGrdpnlDataBaseConnection.addItem(panelTest); + + refreshGridPanelInMainWindow(); + if (typeof listDBConnection !== "undefined") { + winGrdpnlDataBaseConnection.open(); + frmDataBaseConnection.panel.html.style.padding = "10px"; + $('#grdpnlDataBaseConnection .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + winGrdpnlDataBaseConnection.defineEvents(); + applyStyleWindowForm(winGrdpnlDataBaseConnection); + winGrdpnlDataBaseConnection.footer.html.style.textAlign = 'right'; + $(btnNew.getHTML()).css({float: "right"}) + grdpnlDataBaseConnection.dom.toolbar.appendChild(btnNew.getHTML()); + btnNew.defineEvents(); + + disableAllItems(); + winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); + } + }; + + PMDesigner.database.create = function () { + PMDesigner.database(); + dataBaseConnectionOption = "POST"; + winFrmDataBaseConnectionShow("POST", {}); + }; + }() +); + +(function () { + var openTinyInMainWindow, + dataOutPutDocument, + openFormInMainWindow, + messageRequired; + + PMDesigner.output = function (event) { + var winMainOutputDocument, formOutput, rowData, updateOutPut, restClient, isDirtyFormOutput, clickedClose = true, that = this, + setDataRow, + clearDataRow, + getGridOutput, + disableAllItems, + deleteDataRow, + updateOutput, + refreshGridPanelInMainWindow, + openGridPanelInMainWindow, + openFormForEditInMainWindow, + editorTiny, + outputFormDocPdfSecurityOpen, + docMargin, + password, + outputFormDocPdfSecurityOwner, + outputFormDocPdfSecurityEnabled, + btnCloseWindowOutputDoc, + btnSaveWindowOutputDoc, + btnCancelTiny, + newButtonOutput, + gridOutput, + winMainOutputDocument, + btnSaveTiny, + listOutputDocs; + + + setDataRow = function (row) { + dataOutPutDocument = row.getData(); + rowData = row; + }; + + clearDataRow = function () { + dataOutPutDocument = ''; + rowData = ''; + }; + + isDirtyFormOutput = function () { + var message_window; + $("input,select,textarea").blur(); + if (formOutput.isVisible()) { + if (formOutput.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: "Output Documents".translate(), + windowMessageType: "warning", + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + clearDataRow(); + message_window.close(); + if (clickedClose) { + tinymce.EditorManager.execCommand('mceRemoveControl', true, 'tinyeditor'); + winMainOutputDocument.close(); + } else { + clearDataRow(); + openGridPanelInMainWindow(); + } + + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + clearDataRow(); + if (clickedClose) { + tinymce.EditorManager.execCommand('mceRemoveControl', true, 'tinyeditor'); + winMainOutputDocument.close() + } else { + openGridPanelInMainWindow(); + } + } + } else { + winMainOutputDocument.close(); + } + }; + getGridOutput = function () { + var restClientGet = new PMRestClient({ + endpoint: 'output-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listOutputDocs = response; + gridOutput.setDataItems(listOutputDocs); + gridOutput.sort('out_doc_title', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + restClientGet.executeRestClient(); + }; + + disableAllItems = function () { + winMainOutputDocument.hideFooter(); + formOutput.reset(); + + winMainOutputDocument.getItems()[0].setVisible(false); + winMainOutputDocument.getItems()[1].setVisible(false); + for (var i = 0; i <= winMainOutputDocument.getItems()[1].getItems().length - 1; i += 1) { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(false); + } + btnSaveWindowOutputDoc.setVisible(false); + btnCloseWindowOutputDoc.setVisible(false); + btnSaveTiny.setVisible(false); + btnCancelTiny.setVisible(false); + + winMainOutputDocument.footer.getItems()[2].setVisible(false); + }; + + refreshGridPanelInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + winMainOutputDocument.setTitle("Output Documents".translate()); + getGridOutput(); + }; + + openGridPanelInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + winMainOutputDocument.setTitle("Output Documents".translate()); + $(winMainOutputDocument.body).removeClass("pmui-background"); + }; + + openFormInMainWindow = function () { + disableAllItems(); + winMainOutputDocument.showFooter(); + winMainOutputDocument.getItems()[1].setVisible(true); + for (var i = 0; i < winMainOutputDocument.getItems()[1].getItems().length; i += 1) { + if (winMainOutputDocument.getItems()[1].getItems()[i].type !== "PMTinyField") { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(true); + } + } + btnSaveWindowOutputDoc.setVisible(true); + btnCloseWindowOutputDoc.setVisible(true); + winMainOutputDocument.footer.getItems()[2].setVisible(true); + password.setVisible(false); + winMainOutputDocument.setTitle("Create Output Document".translate()); + winMainOutputDocument.setHeight(520); + formOutput.panel.style.addProperties({padding: '20px 10px'}); + formOutput.setFocus(); + + }; + + openFormForEditInMainWindow = function (outputDocumentData) { + disableAllItems(); + winMainOutputDocument.showFooter(); + btnSaveWindowOutputDoc.setVisible(true); + btnCloseWindowOutputDoc.setVisible(true); + winMainOutputDocument.footer.getItems()[1].setVisible(false); + formOutput.setWidth(700); + winMainOutputDocument.getItems()[1].setVisible(true); + winMainOutputDocument.setTitle("Edit Output Document".translate()); + $(winMainOutputDocument.body).addClass("pmui-background"); + for (var i = 0; i < winMainOutputDocument.getItems()[1].getItems().length; i += 1) { + if (winMainOutputDocument.getItems()[1].getItems()[i].type !== "PMTinyField") { + winMainOutputDocument.getItems()[1].getItems()[i].setVisible(true); + } + } + + password.setVisible(false); + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + var dataEdit = formOutput.getFields(); + dataEdit[0].setValue(dataOutPutDocument['out_doc_title']); + dataEdit[1].setValue(dataOutPutDocument['out_doc_filename']); + dataEdit[2].setValue(dataOutPutDocument['out_doc_description']); + dataEdit[3].setValue(dataOutPutDocument['out_doc_report_generator']); + dataEdit[4].setValue(dataOutPutDocument['out_doc_media']); + dataEdit[5].setValue(dataOutPutDocument['out_doc_landscape']); + dataEdit[6].setValue(dataOutPutDocument['out_doc_left_margin']); + dataEdit[7].setValue(dataOutPutDocument['out_doc_right_margin']); + dataEdit[8].setValue(dataOutPutDocument['out_doc_top_margin']); + dataEdit[9].setValue(dataOutPutDocument['out_doc_bottom_margin']); + dataEdit[10].setValue(dataOutPutDocument['out_doc_generate']); + + if (dataOutPutDocument["out_doc_generate"] != "DOC") { + dataEdit[11].setVisible(true); + } else { + dataEdit[11].setVisible(false); + } + + dataEdit[11].setValue(dataOutPutDocument['out_doc_pdf_security_enabled']); + if (dataOutPutDocument['out_doc_pdf_security_enabled'] != 0) { + password.setVisible(true); + } + dataEdit[12].setValue(dataOutPutDocument['out_doc_pdf_security_open_password']); + dataEdit[13].setValue(dataOutPutDocument['out_doc_pdf_security_owner_password']); + + dataOutPutDocument['out_doc_pdf_security_permissions'] = dataOutPutDocument['out_doc_pdf_security_permissions'].split("|"); + dataEdit[14].setValue(JSON.stringify(dataOutPutDocument['out_doc_pdf_security_permissions'])); + + dataEdit[15].setValue(dataOutPutDocument['out_doc_versioning']); + dataEdit[16].setValue(dataOutPutDocument['out_doc_destination_path']); + dataEdit[17].setValue(dataOutPutDocument['out_doc_tags']); + dataEdit[18].setValue(dataOutPutDocument["out_doc_open_type"]); + } + winMainOutputDocument.setHeight(520); + formOutput.panel.style.addProperties({padding: '20px 10px'}); + formOutput.setFocus(); + }; + + openTinyInMainWindow = function (outputDocumentData) { + //Fix for IE11 + var isIe11 = /Trident\/7\.0;.*rv\s*\:?\s*11/.test(navigator.userAgent); + + if (isIe11) { + tinyMCE.isGecko = false; + } + + //Set TinyMCE + disableAllItems(); + winMainOutputDocument.showFooter(); + tinyEditorField = 13; + winMainOutputDocument.getItems()[1].setVisible(true); + winMainOutputDocument.getItems()[1].getItems()[tinyEditorField].setVisible(true); + formOutput.setWidth(890); + btnSaveTiny.setVisible(true); + btnCancelTiny.setVisible(true); + if (!editorTiny.isInitialized) { + editorTiny.createHTML(); + editorTiny.setParameterTiny(); + editorTiny.isInitialized = true; + } else { + tinyMCE.execCommand('mceFocus', false, 'tinyeditor'); + } + var dataEdit = formOutput.getFields(); + winMainOutputDocument.setTitle("Edit Output Document".translate()); + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + dataOutPutDocument['out_doc_template'] = (dataOutPutDocument['out_doc_template'] != null) ? dataOutPutDocument['out_doc_template'] : ' '; + dataEdit[19].setValue(dataOutPutDocument['out_doc_template']); + dataEdit[19].setValueTiny(dataOutPutDocument['out_doc_template']); + dataEdit[19].setHeight(425); + + dataEdit[18].setVisible(false); + dataEdit[19].setVisible(true); + } + formOutput.panel.style.addProperties({padding: '0px 10px'}); + winMainOutputDocument.setHeight(520); + if (!editorTiny.isInitialized) + tinymce.execCommand('mceFocus', false, 'tinyeditor'); + }; + + deleteDataRow = function () { + confirmWindow = new PMUI.ui.MessageWindow({ + id: "outputMessageWindowWarning", + windowMessageType: 'warning', + bodyHeight: 'auto', + width: 490, + title: "Output Documents".translate(), + message: "Do you want to delete this Output Document?".translate(), + footerItems: [ + { + id: 'confirmWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + id: 'confirmWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + var restClient; + confirmWindow.close(); + restClient = new PMRestClient({ + endpoint: "output-document/" + dataOutPutDocument.out_doc_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems deleting the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document deleted successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + }, + buttonType: "success" + }, + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = "17px"; + confirmWindow.showFooter(); + }; + + updateOutput = function (data) { + dataOutPutDocument = ''; + var restClientUpdate = new PMRestClient({ + endpoint: "output-document/" + data.out_doc_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + dataOutPutDocument = data; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document edited successfully'.translate(), + flashContainer: gridOutput + }); + restClientUpdate.executeRestClient(); + }; + + editorTiny = new PMTinyField({ + id: 'outputEditorTiny', + theme: "advanced", + plugins: "advhr,advimage,advlink,advlist,autolink,autoresize,contextmenu,directionality,emotions,example,example_dependency,fullpage,fullscreen,iespell,inlinepopups,insertdatetime,layer,legacyoutput,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,style,tabfocus,table,template,visualblocks,visualchars,wordcount,xhtmlxtras,pmSimpleUploader,pmVariablePicker,style", + mode: "specific_textareas", + editorSelector: "tmceEditor", + widthTiny: DEFAULT_WINDOW_WIDTH - 58, + heightTiny: DEFAULT_WINDOW_HEIGHT - 100, + directionality: 'ltr', + verifyHtml: false, + themeAdvancedButtons1: "pmSimpleUploader,|,pmVariablePicker,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,cut,copy,paste,|,bullist,numlist,|,outdent,indent,blockquote", + themeAdvancedButtons2: "tablecontrols,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor,styleprops,|,hr,removeformat,visualaid,|,sub,sup,|,ltr,rtl,|,code", + popupCss: "/js/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialogTinyBpmn.css", + contentCss: "/css/fonts.css,/fonts/styles.php", + themeAdvancedFonts: tcPdfFonts, + skin: "o2k7", + skin_variant: "silver" + }); + + docMargin = new PMUI.form.FormPanel({ + fieldset: true, + layout: 'hbox', + legend: "Margin".translate(), + items: [ + { + pmType: 'panel', + proportion: 0.7 + }, + { + pmType: "panel", + layout: 'vbox', + items: [ + { + id: 'outputDocMarginLeft', + pmType: "text", + label: "Left".translate(), + required: true, + value: 20, + name: "out_doc_left_margin", + controlsWidth: 50, + labelWidth: '35%' + }, { + id: 'outputDocMarginRight', + pmType: "text", + label: "Right".translate(), + required: true, + value: 20, + name: "out_doc_right_margin", + controlsWidth: 50, + labelWidth: '35%' + } + ] + }, + { + pmType: "panel", + layout: 'vbox', + proportion: 1.5, + items: [ + { + id: 'outputDocMarginTop', + pmType: "text", + label: "Top".translate(), + required: true, + value: 20, + name: "out_doc_top_margin", + controlsWidth: 50, + labelWidth: '27%' + }, { + id: 'outputDocMarginBottom', + pmType: "text", + label: "Bottom".translate(), + required: true, + value: 20, + name: "out_doc_bottom_margin", + controlsWidth: 50, + labelWidth: '27%' + } + ] + } + ] + }); + + //Field "Open Password - Owner Password" + outputFormDocPdfSecurityOpen = new PMUI.field.PasswordField({ + id: "outputFormDocPdfSecurityOpen", + name: "out_doc_pdf_security_open_password", + value: "", + label: "Open Password ".translate(), + required: true, + controlsWidth: 300 + }); + + outputFormDocPdfSecurityOwner = new PMUI.field.PasswordField({ + id: "outputFormDocPdfSecurityOwner", + name: "out_doc_pdf_security_owner_password", + value: "", + label: "Owner Password ".translate(), + required: true, + controlsWidth: 300 + + }); + + password = new PMUI.form.FormPanel({ + width: 500, + height: 130, + fieldset: true, + visible: false, + legend: "", + items: [ + { + pmType: "panel", + layout: 'vbox', + items: [ + outputFormDocPdfSecurityOpen, + outputFormDocPdfSecurityOwner + ] + }, + { + pmType: "panel", + layout: 'vbox', + items: [ + { + id: 'outputFormDocPdfSecurityPermissions', + pmType: 'checkbox', + label: "Allowed Permissions".translate(), + value: '', + name: 'out_doc_pdf_security_permissions', + required: false, + controlPositioning: 'horizontal', + separator: "|", + maxDirectionOptions: 4, + options: [ + { + id: 'monday', + label: "print".translate(), + value: 'print' + }, + { + id: 'monday', + label: "modify".translate(), + value: 'modify' + }, + { + id: 'monday', + label: "copy".translate(), + value: 'copy' + }, + { + id: 'monday', + label: "forms".translate(), + value: 'forms' + } + + ] + } + ] + } + ], + layout: "vbox" + }); + + //Field "PDF security" + outputFormDocPdfSecurityEnabled = new PMUI.field.DropDownListField({ + id: "outputDocDPFSecurity", + name: "out_doc_pdf_security_enabled", + label: "PDF security".translate(), + labelWidth: "27%", + valueType: "number", + visible: false, + + options: [ + { + value: 0, + label: "Disabled".translate(), + selected: true + }, + { + value: 1, + label: "Enabled".translate() + + } + ], + + controlsWidth: 100, + + onChange: function (newValue, prevValue) { + var visible = true; + + if (newValue == 0) { + visible = false; + + outputFormDocPdfSecurityOpen.setValue(""); + outputFormDocPdfSecurityOwner.setValue(""); + } + + password.setVisible(visible); + } + }); + + //the form is 700px width, but with the tiny grows to 890 + formOutput = new PMUI.form.Form({ + id: 'outputForm', + name: 'outputForm', + fieldset: true, + title: "", + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 43, + items: [ + { + id: 'outputDocTitle', + pmType: "text", + name: 'out_doc_title', + label: "Title".translate(), + labelWidth: '27%', + controlsWidth: 300, + required: true + }, + new CriteriaField({ + id: 'outputDocFilenameGenerated', + pmType: "text", + name: 'out_doc_filename', + label: "Filename generated".translate(), + labelWidth: '27%', + controlsWidth: 300, + required: true + }), + { + id: 'outputDocDescription', + pmType: "textarea", + name: 'out_doc_description', + label: "Description".translate(), + labelWidth: '27%', + controlsWidth: 500, + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: 'outputDocReportGenerator', + pmType: "dropdown", + name: 'out_doc_report_generator', + label: "Report Generator".translate(), + labelWidth: '27%', + require: true, + controlsWidth: 165, + options: [ + { + label: "TCPDF".translate(), + value: "TCPDF" + }, + { + label: "HTML2PDF (Old Version)".translate(), + value: "HTML2PDF" + } + ], + value: "TCPDF" + }, + { + id: 'outputDocMedia', + pmType: "dropdown", + name: 'out_doc_media', + label: "Media".translate(), + labelWidth: '27%', + controlsWidth: 165, + options: [ + {label: "Letter".translate(), value: "Letter"}, + {label: "Legal".translate(), value: "Legal"}, + {label: "Executive".translate(), value: "Executive"}, + {label: "B5".translate(), value: "B5"}, + {label: "Folio".translate(), value: "Folio"}, + {label: "A0Oversize".translate(), value: "A0Oversize"}, + {label: "A0".translate(), value: "A0"}, + {label: "A1".translate(), value: "A1"}, + {label: "A2".translate(), value: "A2"}, + {label: "A3".translate(), value: "A3"}, + {label: "A4".translate(), value: "A4"}, + {label: "A5".translate(), value: "A5"}, + {label: "A6".translate(), value: "A6"}, + {label: "A7".translate(), value: "A7"}, + {label: "A8".translate(), value: "A8"}, + {label: "A9".translate(), value: "A9"}, + {label: "A10", value: "A10"}, + {label: "Screenshot640".translate(), value: "SH640"}, + {label: "Screenshot800".translate(), value: "SH800"}, + {label: "Screenshot1024".translate(), value: "SH1024"} + ] + }, + { + id: 'outputDocOrientation', + pmType: "dropdown", + name: 'out_doc_landscape', + labelWidth: '27%', + label: "Orientation".translate(), + controlsWidth: 165, + options: [ + { + label: "Portrait".translate(), + selected: true, + value: 0 + }, + { + label: "Landscape".translate(), + value: 1 + } + ], + valueType: 'number' + }, + docMargin, + { + id: 'outputDocToGenerate', + pmType: "dropdown", + name: 'out_doc_generate', + controlsWidth: 70, + labelWidth: '27%', + label: "Output Document to Generate".translate(), + options: [ + { + label: "Both".translate(), + value: "BOTH" + }, + { + label: "Doc".translate(), + value: "DOC" + }, + { + label: "Pdf".translate(), + value: "PDF" + } + ], + value: "BOTH", + onChange: function (newValue, prevValue) { + if (newValue == "DOC") { + formOutput.getFields()[11].setVisible(false); + outputFormDocPdfSecurityEnabled.setVisible(false); + outputFormDocPdfSecurityEnabled.setValue(0); + password.setVisible(false); + outputFormDocPdfSecurityOpen.setValue(""); + outputFormDocPdfSecurityOwner.setValue(""); + } else { + formOutput.getFields()[11].setVisible(true); + } + } + }, + outputFormDocPdfSecurityEnabled, + password, + { + id: 'outputDocEnableVersioning', + pmType: "dropdown", + name: "out_doc_versioning", + controlsWidth: 70, + labelWidth: '27%', + label: 'Enable versioning'.translate(), + options: [ + { + label: "Yes".translate(), + value: 1 + }, + { + label: "No".translate(), + selected: true, + value: 0 + } + ], + valueType: 'number' + }, + new CriteriaField({ + id: 'outputDocDestinationPath', + pmType: "text", + name: "out_doc_destination_path", + labelWidth: '27%', + label: "Destination Path".translate(), + controlsWidth: 340 + }), + new CriteriaField({ + id: 'outputDocTags', + pmType: "text", + name: "out_doc_tags", + labelWidth: '27%', + label: "Tags".translate(), + controlsWidth: 340 + }), + { + id: "outputDocGenerateFileLink", + name: "cboByGeneratedFile", + pmType: "dropdown", + controlsWidth: 155, + labelWidth: "27%", + label: "By clicking on the generated file link".translate(), + + options: [ + { + value: 0, + label: "Open the file".translate() + }, + { + label: "Download the file".translate(), + value: 1, + selected: true + } + ], + + valueType: "number" + } + ], + style: { + cssProperties: { + marginLeft: '20px' + } + } + }); + + formOutput.style.addProperties({marginLeft: '20px'}); + gridOutput = new PMUI.grid.GridPanel({ + id: 'gridOutput', + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'gridOutputButtonShow', + title: '', + dataType: 'button', + buttonLabel: 'Show ID'.translate(), + columnData: "out_doc_uid", + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + showUID(data.out_doc_uid); + } + }, + { + title: 'Title'.translate(), + dataType: 'string', + width: '392px', + alignment: "left", + columnData: "out_doc_title", + sortable: true, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: '100px', + alignmentCell: 'left', + columnData: "out_doc_type", + sortable: true + }, + { + id: 'gridOutputButtonEdit', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + buttonLabel: 'Edit'.translate(), + onButtonClick: function (row, grid) { + messageRequired.hide(); + setDataRow(row); + openFormForEditInMainWindow(); + } + }, + { + id: 'gridOutputButtonProperties', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + buttonLabel: 'Open Editor'.translate(), + onButtonClick: function (row, grid) { + setDataRow(row); + openTinyInMainWindow(row); + } + }, + { + id: 'gridOutputButtonDelete', + title: '', + dataType: 'button', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + setDataRow(row); + deleteDataRow(); + } + } + ] + }); + + btnSaveWindowOutputDoc = new PMUI.ui.Button({ + id: 'btnSaveWindowOutputDoc', + text: "Save".translate(), + handler: function () { + var dataAux = getData2PMUI(formOutput.html); + if (dataAux.out_doc_title != "" && dataAux.out_doc_filename != "") { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + itemOutPut = getData2PMUI(formOutput.html); + } else { + itemOutPut = formOutput.getData(); + } + + itemOutPut['out_doc_type'] = "HTML"; + + var items = jQuery.parseJSON(itemOutPut['out_doc_pdf_security_permissions']); + itemOutPut['out_doc_pdf_security_permissions'] = ''; + for (var i = 0; i < items.length; i += 1) { + itemOutPut['out_doc_pdf_security_permissions'] += (i == 0) ? items[i] : '|' + items[i]; + } + + itemOutPut["out_doc_landscape"] = parseInt(itemOutPut["out_doc_landscape"]); + itemOutPut["out_doc_pdf_security_enabled"] = parseInt(itemOutPut["out_doc_pdf_security_enabled"]); + itemOutPut["out_doc_versioning"] = parseInt(itemOutPut["out_doc_versioning"]); + itemOutPut["out_doc_open_type"] = parseInt(getData2PMUI(formOutput.html).cboByGeneratedFile); + + if (dataOutPutDocument != '' && dataOutPutDocument != undefined) { + itemOutPut['out_doc_uid'] = dataOutPutDocument.out_doc_uid; + restClient = new PMRestClient({ + endpoint: "output-document/" + dataOutPutDocument.out_doc_uid, + typeRequest: 'update', + data: itemOutPut, + functionSuccess: function (xhr, response) { + dataOutPutDocument = itemOutPut; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document edited successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + } else { + if (1 === parseInt(dataAux.out_doc_pdf_security_enabled) && (dataAux.out_doc_pdf_security_open_password.trim() === "" || dataAux.out_doc_pdf_security_owner_password.trim() === "")) { + password.getItems()[0].getItems()[0].isValid(); + password.getItems()[0].getItems()[1].isValid(); + return false; + } + itemOutPut['out_doc_uid'] = ''; + restClient = new PMRestClient({ + endpoint: "output-document", + typeRequest: 'post', + data: itemOutPut, + functionSuccess: function (xhr, response) { + dataOutPutDocument = itemOutPut; + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems saved the OutputDocument, please try again.".translate(), + messageSuccess: 'Output Document saved successfully'.translate(), + flashContainer: gridOutput + }); + restClient.executeRestClient(); + } + clearDataRow(); + } else { + formOutput.getField("out_doc_title").isValid(); + formOutput.getField("out_doc_filename").isValid(); + } + }, + buttonType: 'success' + }); + + btnCloseWindowOutputDoc = new PMUI.ui.Button({ + id: 'btnCloseWindowOutputDoc', + text: "Cancel".translate(), + handler: function () { + clickedClose = false; + isDirtyFormOutput(); + }, + buttonType: 'error' + }); + + newButtonOutput = new PMUI.ui.Button({ + id: 'outputButtonNew', + text: 'Create'.translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + clearDataRow(); + openFormInMainWindow(); + } + }); + + btnCancelTiny = new PMUI.ui.Button({ + id: 'btnCloseTiny', + text: 'Cancel'.translate(), + handler: function () { + /*if (typeof dataOutPutDocument['externalType'] != 'undefined' && dataOutPutDocument['externalType']) { + winMainOutputDocument.close(); + return; + }*/ + PMDesigner.hideAllTinyEditorControls(); + clickedClose = false; + isDirtyFormOutput(); + }, + buttonType: 'error' + }); + + btnSaveTiny = new PMUI.ui.Button({ + id: 'btnSaveTiny', + text: 'Save'.translate(), + handler: function () { + PMDesigner.hideAllTinyEditorControls(); + dataOutPutDocument['out_doc_template'] = tinyMCE.activeEditor.getContent(); + updateOutput(dataOutPutDocument); + if (typeof dataOutPutDocument['externalType'] != 'undefined' && dataOutPutDocument['externalType']) { + winMainOutputDocument.close(); + return; + } + clearDataRow(); + refreshGridPanelInMainWindow(); + }, + buttonType: 'success' + }); + + winMainOutputDocument = new PMUI.ui.Window({ + id: "winMainOutputDocument", + title: "Output Documents".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: "bottom", + onBeforeClose: function () { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = true; + isDirtyFormOutput(); + }, + footerItems: [ + btnCancelTiny, + btnSaveTiny, + btnCloseWindowOutputDoc, + btnSaveWindowOutputDoc] + }); + + formOutput.addItem(editorTiny); + formOutput.footer.setVisible(false); + + winMainOutputDocument.addItem(gridOutput); + winMainOutputDocument.addItem(formOutput); + + refreshGridPanelInMainWindow(); + + validateKeysField(docMargin.getField('out_doc_left_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_right_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_top_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + validateKeysField(docMargin.getField('out_doc_bottom_margin').getControls()[0].getHTML(), ['isbackspace', 'isnumber']); + + if (typeof listOutputDocs !== "undefined") { + winMainOutputDocument.open(); + $('#gridOutput .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + messageRequired = $(document.getElementById("requiredMessage")); + applyStyleWindowForm(winMainOutputDocument); + + editorTiny.isInitialized = false; + winMainOutputDocument.footer.html.style.textAlign = 'right'; + + gridOutput.dom.toolbar.appendChild(newButtonOutput.getHTML()); + newButtonOutput.defineEvents(); + winMainOutputDocument.defineEvents(); + disableAllItems(); + winMainOutputDocument.getItems()[0].setVisible(true); + } + }; + + PMDesigner.output.showTiny = function (uid) { + getItemdOutput = function () { + var restClientGet = new PMRestClient({ + endpoint: 'output-document/' + uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + dataOutPutDocument = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + restClientGet.executeRestClient(); + }; + getItemdOutput(); + dataOutPutDocument['externalType'] = true; + openTinyInMainWindow(dataOutPutDocument); + }; + + PMDesigner.output.create = function () { + openFormInMainWindow(); + }; +}()); + +( + function () { + var iframeRT, + reportWindow, + pathSrc; + + PMDesigner.reporttable = function (event) { + reportWindow = new PMUI.ui.Window({ + id: 'reportTableWindow', + title: "Report Tables".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT + }); + + pathSrc = window.parent.location; + + iframeRT = new PMIframe({ + id: 'reporTableIframe', + src: window.location.href.split("/")[0] + "//" + pathSrc.host + "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/pmTables?PRO_UID=" + PMDesigner.project.id + "&flagProcessmap=1", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 36, + scrolling: 'no', + frameborder: '0' + }); + + reportWindow.addItem(iframeRT); + reportWindow.open(); + reportWindow.setBodyPadding(0); + }; + + PMDesigner.reporttable.create = function () { + pathSrc = window.parent.location; + reportWindow.clearItems(); + iframeRT = new PMIframe({ + id: 'reporTableIframe', + src: window.location.href.split("/")[0] + "//" + pathSrc.host + "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/pmTables/edit?PRO_UID=" + PMDesigner.project.id + "&tableType=report&flagProcessmap=1", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 36, + scrolling: 'no', + frameborder: '0' + }); + reportWindow.addItem(iframeRT); + reportWindow.open(); + reportWindow.setBodyPadding(0); + } + + }() +); +(function () { + $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); + var btnCopyImport, openFormCustom, formEditTriggerCustom; + var triggerOriginDataForUpdate = {}; + PMDesigner.trigger = function (event) { + var listTriggers, + clickedClose = true, + message_ErrorWindow, + flagChanges, + isDirtyFormTrigger, + gridListTrigger, + getListTrigger, + addNumberTriggerWizard, + newTriggerOptions, + allTreesItems, + buttonNew, + buttonCopy, + buttonWizard, + openListTriggers, + openFormWizard, + openFormWizardEditMode, + openFormCopy, + openFormEditCode, + openNewTriggerOptions, + listProjects, + getListProjects, + triggerSelectedData, + formCopyTrigger, + codMirr, + formEditTriggerWizard, + sepInputs, + labelInputs, + paramPanel, + sepOutputs, + labelOutputs, + returnPanel, + parameterItems, + returnItems, + treeNewTrigger, + accordionNewTrigger, + updateCustom, + checkIfValuesAreEqual, + buttonSave, + copyButton, + applyButton, + btnEditSourceCode, + buttonCancel, + editCode, + formEditCode, + triggerWindow, + formcustom; + + message_ErrorWindow = new PMUI.ui.MessageWindow({ + id: "errorMessage", + width: 490, + windowMessageType: 'error', + title: "Triggers".translate(), + message: "This is an error message.".translate(), + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + message_ErrorWindow.close(); + }, + buttonType: "success" + } + ] + }); + + isDirtyFormTrigger = function () { + $("input,select,textarea").blur(); + $("div.pmui-window-body.pmui-background").css('overflow', ''); + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + var flag = false; + + var finalData = { + tri_uid: getData2PMUI(formEditTriggerCustom.html).uid, + tri_title: getData2PMUI(formEditTriggerCustom.html).title, + tri_description: getData2PMUI(formEditTriggerCustom.html).description, + tri_webbot: getData2PMUI(formEditTriggerCustom.html).code + }; + + if (formcustom.isVisible() == true) { + flag = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + } else if (formwizard.isVisible() == true) { + flag = formEditTriggerWizard.isDirty(); + } else if (formcopy.isVisible() == true) { + flag = formCopyTrigger.isDirty(); + if (!flag) { + $('.ctrlSpaceMessage').remove(); + } + } else if (formeditcode.isVisible() == true) { + flag = formeditcode.isDirty(); + var flagFormCustom = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + if (!flag && formeditcode.getItems()[0].controls[0].value != "" || flagFormCustom) { + flag = true; + } + } + + if (flag == true) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, { + text: "Yes".translate(), + handler: function () { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + $('.ctrlSpaceMessage').remove(); + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } + message_window.close(); + if (clickedClose) { + triggerWindow.close(); + } + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } else if (accordionnewtrigger.isVisible() == true) { + openListTriggers(); + } + if (clickedClose) { + triggerWindow.close(); + } + } + }; + //GRID List Case Scheduler + gridListTrigger = new PMUI.grid.GridPanel({ + id: "listTriggers", + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'listTriggersButtonShow', + title: '', + dataType: 'button', + searchable: false, + buttonLabel: 'Show ID'.translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + id: 'copyuid', + onButtonClick: function (row, grid) { + var dataRow = row.getData(); + messageWindow = new PMUI.ui.MessageWindow({ + id: 'dynaformMessageWindowUID', + windowMessageType: 'info', + width: 490, + title: "Triggers".translate(), + message: dataRow.tri_uid, + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + messageWindow.close(); + }, + buttonType: "success" + } + ] + }); + messageWindow.setTitle("ID".translate()); + messageWindow.open(); + messageWindow.showFooter(); + $(messageWindow.dom.icon).removeClass(); + } + }, + { + title: 'Title'.translate(), + id: "title", + dataType: 'string', + width: "407px", + visible: true, + columnData: "tri_title", + searcheable: true, + sortable: true, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + id: "type", + dataType: 'string', + width: "225px", + visible: true, + alignmentCell: 'left', + columnData: function (data) { + if (typeof(data.tri_param) == "object" && typeof(data.tri_param.params) == "object") { + var wizardData = data.tri_param.params; + + return wizardData.LIBRARY_NAME; + } else { + return "Custom"; + } + }, + searcheable: true, + sortable: true + }, + { + id: "editButton", + title: '', + dataType: 'button', + messageTooltip: "Edit".translate(), + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + triggerOriginDataForUpdate = {}; + var data = row.getData(); + triggerOriginDataForUpdate = data; + var fields; + if (data.tri_param == "") { + + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 160); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.tri_uid); + fields.getItems()[1].setValue(data.tri_title); + fields.getItems()[2].setValue(data.tri_description); + formEditTriggerCustom.getItems()[1].setValue(data.tri_webbot); + + codeMirrorControl.setValue(data.tri_webbot); + codeMirrorControl.refresh(); + } else { + openFormWizardEditMode(); + + var wizardData = data.tri_param.params; + + var lib = wizardData.LIBRARY_CLASS; + lib = lib.split('.'); + lib = lib[1]; + fields = formEditTriggerWizard.getFields(); + fields[0].setValue(data.tri_uid); + fields[1].setValue(lib); + fields[2].setValue(wizardData.PMFUNTION_NAME); + fields[3].setValue(wizardData.LIBRARY_NAME + " (" + wizardData.PMFUNTION_LABEL + ")"); + fields[4].setValue(data.tri_title); + fields[5].setValue(data.tri_description); + fields[6].setValue(data.tri_webbot); + + var inputItems = []; + var outputItems = []; + + restClient = new PMRestClient({ + endpoint: "trigger-wizard/" + lib + "/" + wizardData.PMFUNTION_NAME, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (response.fn_params.input != undefined) { + for (j = 0; j < response.fn_params.input.length; j++) { + var nameInput = response.fn_params.input[j].name; + + var inp = new CriteriaField({ + id: nameInput, + pmType: "text", + name: nameInput, + label: response.fn_params.input[j].label, + value: wizardData[nameInput].toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.input[j].description, + required: response.fn_params.input[j].name === "unpauseDate" ? true : response.fn_params.input[j].required + }); + + inputItems.push(inp); + } + } + if (response.fn_params.output != undefined) { + for (k = 0; k < response.fn_params.output.length; k++) { + var nameOutput = response.fn_params.output[k].name; + + var out = new CriteriaField({ + id: nameOutput, + pmType: "text", + name: nameOutput, + label: response.fn_params.output[k].label, + value: wizardData.TRI_ANSWER.toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.output[k].description, + required: response.fn_params.output[k].required + }); + + outputItems.push(out); + } + } + triggerWindow.setTitle("Edit".translate() + " " + wizardData.LIBRARY_NAME); + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + } + }, + { + id: "deleteButton", + title: '', + dataType: 'button', + messageTooltip: "Delete".translate(), + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var questionWindow, dataRow = row.getData(); + + questionWindow = new PMUI.ui.MessageWindow({ + id: "questionDeleteWindow", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: "Do you want to delete this Trigger?".translate(), + footerItems: [ + { + id: 'questionDeleteWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + questionWindow.close(); + }, + buttonType: "error" + }, { + id: 'questionDeleteWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + questionWindow.close(); + restClient = new PMRestClient({ + endpoint: "trigger/" + dataRow.tri_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger deleted successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }, + buttonType: "success" + }, + ] + }); + + questionWindow.open(); + questionWindow.dom.titleContainer.style.height = "17px"; + questionWindow.showFooter(); + } + } + ], + dataItems: listTriggers, + onRowClick: function (row, data) { + + } + }); + + getListTrigger = function () { + var restClient = new PMRestClient({ + endpoint: 'triggers', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listTriggers = response; + gridListTrigger.setDataItems(listTriggers); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + + addNumberTriggerWizard = function (value, position) { + coutTriggers = document.createElement("span"); + coutTriggers.textContent = value; + headerAccordion = triggerWindow.getItems()[5].getItems()[position].header.html; + headerAccordion.appendChild(coutTriggers); + coutTriggers.style.float = "right"; + coutTriggers.style.color = "white"; + coutTriggers.style.fontSize = "13px"; + coutTriggers.style.marginRight = "6px"; + coutTriggers.style.marginTop = "3px"; + }; + + newTriggerOptions = function () { + + var acItemCustom = accordionNewTrigger.getItems()[0]; + var acItemCopy = accordionNewTrigger.getItems()[1]; + acItemCustom.setIconClosed('pmcustomtrigger'); + acItemCustom.setIconExpanded('pmcustomtrigger'); + acItemCopy.setIconClosed('pmcopytrigger'); + acItemCopy.setIconExpanded('pmcopytrigger'); + + var itemCustom = jQuery("#custom > .pmui-accordion-item-header > span")[1]; + itemCustom.style.width = "0px"; + var itemCopy = jQuery("#copy > .pmui-accordion-item-header > span")[1]; + itemCopy.style.width = "0px"; + + var numOfItems = accordionNewTrigger.getItems(); + + var lengthLibFunctions = []; + if (numOfItems.length <= 2) { + restClient = new PMRestClient({ + endpoint: "trigger-wizards", + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (i = 0; i < response.length; i++) { + var functTree = response[i].lib_functions; + lengthLibFunctions[i] = functTree.length; + var newTreeItems = []; + for (h = 0; h < functTree.length; h++) { + newTreeItems.push({ + label: functTree[h].fn_label, + id: functTree[h].fn_name, + onClick: function () { + for (s = 0; s < response.length; s++) { + for (p = 0; p < response[s].lib_functions.length; p++) { + if (response[s].lib_functions[p].fn_name == this.id) { + var fn = response[s].lib_functions[p].fn_params; + var fnLabel = response[s].lib_functions[p].fn_label; + var fnName = response[s].lib_functions[p].fn_name; + var libName = response[s].lib_name; + var libTitle = response[s].lib_title; + p = response[s].lib_functions.length; + s = response.length - 1; + } + } + } + var inputItems = []; + if (fn.input != undefined) { + for (j = 0; j < fn.input.length; j++) { + var val = ""; + if (fn.input[j].type == "array") { + val = "array('')"; + } + var inp = new CriteriaField({ + id: fn.input[j].name, + pmType: "text", + name: fn.input[j].name, + label: fn.input[j].label, + controlsWidth: 400, + labelWidth: '27%', + value: val, + helper: fn.input[j].description, + required: fn.input[j].name === "unpauseDate" ? true : fn.input[j].required + }); + + inputItems.push(inp); + } + } + + var outputItems = []; + if (fn.output != undefined) { + for (k = 0; k < fn.output.length; k++) { + var out = new CriteriaField({ + id: fn.output[k].name, + pmType: "text", + name: fn.output[k].name, + label: fn.output[k].label, + controlsWidth: 400, + labelWidth: '27%', + helper: fn.output[k].description, + required: fn.output[k].required + }); + + outputItems.push(out); + } + } + formEditTriggerWizard.reset(); + formEditTriggerWizard.setTitle(fnLabel + ' (' + fnName + ')'); + formEditTriggerWizard.getItems()[0].getItems()[1].setValue(libName); + formEditTriggerWizard.getItems()[0].getItems()[2].setValue(fnName); + formEditTriggerWizard.getItems()[0].getItems()[3].setValue(libTitle + ' (' + fnLabel + ')'); + + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + openFormWizard(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + triggerWindow.setTitle("Create".translate() + " " + libTitle); + } + }); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + allTreesItems[i] = newTreeItems; + + var arrayTriggerWizards = [ + "pmFunctions", + "pmSugar", + "pmTalend", + "pmTrAlfresco", + "pmTrSharepoint", + "pmZimbra" + ]; + + if (arrayTriggerWizards.indexOf(response[i].lib_name) == -1) { + $("head").append(""); + } + + //Accordion + var newAccordionItem = []; + newAccordionItem = { + iconClass: response[i].lib_name, + id: response[i].lib_name, + title: response[i].lib_title, + height: 'auto' + }; + accordionNewTrigger.addItem(newAccordionItem); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + + openNewTriggerOptions(); + var accordion = triggerWindow.getItems()[5].getItems(); + accordion[0].setVisible(false); + accordion[1].setVisible(false); + for (i = 0; i < accordion.length; i++) { + accordion[i].header.html.style.backgroundColor = "#FFFFFF"; + if (i > 1) { + addNumberTriggerWizard(lengthLibFunctions[i - 2], (i)); + } + } + }; + + allTreesItems = []; + getListTrigger(); + + //Button NEW Trigger + buttonNew = new PMUI.ui.Button({ + id: 'newTriggerButton', + text: "Create".translate(), + height: "36px", + width: 100, + handler: function (event) { + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + codeMirrorControl.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button COPY Trigger + buttonCopy = new PMUI.ui.Button({ + id: 'copyTriggerButton', + text: "Copy".translate(), + height: "36px", + width: 100, + handler: function (event) { + getListProjects(); + openFormCopy(); + formCopyTrigger.getFields()[1].clearOptions(); + $("#Code .CodeMirror.cm-s-default.CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + cmControlCopyTrigger.setValue(""); + if (cmControlCopyTrigger !== undefined) { + cmControlCopyTrigger.setSize(650, 140); + } + cmControlCopyTrigger.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button WIZARD Trigger + buttonWizard = new PMUI.ui.Button({ + id: 'wizardTriggerButton', + text: "Wizard".translate(), + height: "36px", + width: 100, + handler: function (event) { + newTriggerOptions(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + openListTriggers = function () { + triggerWindow.getItems()[0].setVisible(true); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Triggers".translate()); + triggerWindow.hideFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + openFormCustom = function (typeTitle) { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(true); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + + triggerWindow.setTitle(typeTitle + " Custom Trigger".translate()); + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerCustom.setFocus(); + + $('.CodeMirror.cm-s-default')[0].style.border = "1px solid #c0c0c0"; + if (formEditTriggerCustom.getItems()[0].getItems()[1].visible == false) { + var fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[1].setVisible(true); + fields.getItems()[2].setVisible(true); + formEditTriggerCustom.footer.getItems()[1].setVisible(true); + } + formEditTriggerCustom.getFields()[4].dom.labelTextContainer.style.marginLeft = "10px"; + formEditTriggerCustom.setAlignmentButtons('left'); + + $("#code").after($ctrlSpaceMessage.css({ + "margin": "5px 0 0 0", + "text-align": "center", + "width": "655px", + "padding": "" + })); + }; + + openFormWizard = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + openFormWizardEditMode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(true); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + + openFormCopy = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(true); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Copy Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(true); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formCopyTrigger.setFocus(); + + $(".pmui-field").css("float", "left"); + $('#Code .pmui.pmui-pmcodemirrorcontrol').append($ctrlSpaceMessage.css({ + "margin-top": "10px", + "text-align": "", + "width": "655px", + "padding": "" + })); + }; + + openFormEditCode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(true); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Editor".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(true); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).after($ctrlSpaceMessage.css({ + "padding": "5px 0 0 10px", + "text-align": "" + })); + + }; + + openNewTriggerOptions = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(true); + triggerWindow.setTitle("Create Predefined Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + //obtaning the list of process to show it on the copy/import of a trigger dropdown + listProjects = []; + getListProjects = function () { + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listProjects = []; + formCopyTrigger.getFields()[0].clearOptions(); + listProjects[0] = { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }; + for (i = 0; i < response.length; i++) { + listProjects.push({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } + formCopyTrigger.getFields()[0].setOptions(listProjects); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of projects.".translate() + }); + restClient.setBaseEndPoint('projects'); + restClient.executeRestClient(); + }; + + //form Copy/Import Trigger + triggerSelectedData; + formCopyTrigger = new PMUI.form.Form({ + id: "formCopyTriggers", + border: true, + width: '890px', + height: 'auto', + title: "", + visibleHeader: false, + items: [ + { + pmType: 'dropdown', + id: "processField", + label: 'Process'.translate(), + name: 'prj_uid', + required: true, + controlsWidth: 300, + value: "", + options: listProjects, + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidProj = newValue, myForm = this.form; + + //obtaning the Trigger list of the process SELECTED + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + triggerSelectedData = response; + var listTriggersCopy = []; + listTriggersCopy[0] = { + label: "- Select a trigger -".translate(), + value: "", + disabled: true, + selected: true + }; + + for (i = 0; i < response.length; i++) { + listTriggersCopy.push({ + label: response[i].tri_title, + value: response[i].tri_uid + }); + } + formFields[1].setOptions(listTriggersCopy); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of triggers.".translate() + }); + restClient.setBaseEndPoint("project/" + uidProj + "/triggers"); + restClient.executeRestClient(); + } + }, + { + pmType: 'dropdown', + id: "triggerField", + label: 'Trigger'.translate(), + name: 'tri_uid', + required: true, + controlsWidth: 300, + value: "", + options: [], + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidTri = newValue; + + for (i = 0; i < triggerSelectedData.length; i++) { + if (triggerSelectedData[i].tri_uid == uidTri) { + formFields[2].setValue(triggerSelectedData[i].tri_title); + formFields[3].setValue(triggerSelectedData[i].tri_description); + formFields[4].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + } + } + } + }, + { + pmType: "text", + id: "triTitle", + label: "Title of the new trigger".translate(), + placeholder: "Insert the title of the new trigger".translate(), + name: "tri_title", + required: true, + valueType: 'string', + controlsWidth: 300, + style: { + cssProperties: { + 'float': 'left' + } + } + }, + { + pmType: "textarea", + id: "triDescription", + rows: 80, + name: 'tri_description', + label: "Description of the new trigger".translate(), + valueType: 'string', + controlsWidth: 652, + style: { + cssClasses: ['mafe-textarea-resize'], + cssProperties: {'float': 'left'} + } + } + ] + }); + codMirr = new PMCodeMirrorField(); + codMirr.setLabel("Code".translate()); + codMirr.setID("Code"); + codMirr.setName('tri_webbot'); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + formCopyTrigger.addItem(codMirr); + + //Form to Edit the trigger with the WIZARD (we used a Form because we need buttons to save the changes) + formEditTriggerWizard = new PMUI.form.Form({ + id: "formEditTriggerWizard", + border: true, + visibleHeader: false, + name: "formwizard", + width: 926, + title: "New Trigger".translate(), + items: [ + { + id: "panelDetailsWizard", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: 'auto', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + visible: false, + valueType: 'string' + }, + { + id: "libName", + pmType: "text", + label: "", + value: "", + name: "libName", + visible: false, + valueType: 'string' + }, + { + id: "fnName", + pmType: "text", + label: "", + value: "", + name: "fnName", + visible: false, + valueType: 'string' + }, + { + id: "type", + pmType: "text", + label: "Type".translate(), + value: "WIZARD", + controlsWidth: 450, + labelWidth: '27%', + readOnly: true, + name: "type", + valueType: 'string' + }, + { + id: "titleDetailsWiz", + pmType: "text", + label: "Title".translate(), + value: "", + controlsWidth: 450, + labelWidth: '27%', + name: "titleDetails", + valueType: 'string', + required: true + }, + { + id: "descriptionDetailsWiz", + pmType: "textarea", + label: "Description".translate(), + value: "", + rows: 90, + width: '300px', + controlsWidth: 450, + labelWidth: '27%', + name: "descriptionDetails", + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "webbot", + pmType: "text", + label: "Webbot".translate(), + value: "", + name: "webbot", + controlsWidth: 300, + labelWidth: '27%', + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + //adding a separator Inputs line + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepInputs); + + //adding a label Inputs + labelInputs = new PMLabelField({ + text: "PARAMETERS".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + formEditTriggerWizard.addItem(labelInputs); + + //adding the Inputs Items (PARAMETERS) Panel + paramPanel = new PMUI.form.FormPanel({ + id: "panelParametersWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "__PARAMETERS__".translate(), + items: [] + }); + formEditTriggerWizard.addItem(paramPanel); + + //adding a separator Outputs line + sepOutputs = new PMSeparatorLineField({ + controlHeight: 1, + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepOutputs); + + //adding a label Outputs + labelOutputs = new PMLabelField({ + text: "RETURN VALUE".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + + formEditTriggerWizard.addItem(labelOutputs); + + //adding the Output Items (Returns) Panel + returnPanel = new PMUI.form.FormPanel({ + id: "panelReturnValWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "RETURN VALUE".translate(), + items: [] + }); + formEditTriggerWizard.addItem(returnPanel); + + + //treePanel New Trigger PMF + treeNewTrigger = new PMUI.panel.TreePanel({ + id: "treeNewTrigger", + width: 'auto', + height: 'auto', + style: { + cssClasses: ['pmtrigger'], + cssProperties: { + 'margin-top': '5px', + 'margin-bottom': '4px' + } + }, + items: [] + }); + + //Acordion Panel New Triggers Options + accordionNewTrigger = new PMUI.panel.AccordionPanel({ + id: "accordionNewTrigger", + width: 885, + height: 'auto', + borderWidth: "0px", + hiddenTitle: true, + style: { + cssProperties: { + 'margin-left': '30px' + } + }, + items: [ + { + iconClass: "", + id: 'custom', + title: "Custom Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + }, + { + iconClass: "", + id: 'copy', + title: "Copy Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + } + ], + listeners: { + select: function (obj, event) { + + if (obj.id == "custom") { + openFormCustom("Create".translate()); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 150); //CodeMirror Size + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + + } else if (obj.id == "copy") { + + getListProjects(); + openFormCopy(); + $($('#Code .CodeMirror.cm-s-default.CodeMirror-wrap')[1]).css({'border': '1px solid #c0c0c0'}); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + if (cmControlCopyTrigger != undefined) { + cmControlCopyTrigger.setSize(650, 140); //CodeMirror in formCopyTrigger Size + } + } else { + if (treeNewTrigger.getItems() == "" || treeNewTrigger.id != obj.id) { + var acItems = accordionNewTrigger.getItems(); + var accordionActualItem = accordionNewTrigger.getItem(obj.id); + + for (i = 0; i < acItems.length; i++) { + if (acItems[i].id == accordionActualItem.id) { + var positionActualAcItem = i - 2; + } + } + + treeNewTrigger.setItems(allTreesItems[positionActualAcItem]); + treeNewTrigger.setID(obj.id); + + accordionActualItem.setBody(treeNewTrigger); + treeNewTrigger.defineEvents(); + applyStyleTreePanel(treeNewTrigger, false); + } + } + } + } + }); + + updateCustom = function (dataToSend, triggerUid) { + var restClient = new PMRestClient({ + endpoint: "trigger/" + triggerUid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message; + var arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }; + + checkIfValuesAreEqual = function (initialData, finalData) { + if (typeof(initialData['tri_uid']) == "undefined" && finalData['tri_uid'] == '') { + if (finalData['tri_description'] != '' || finalData['tri_title'] != '' || finalData['tri_webbot'] != '') { + return false; + } + } + for (var key1 in initialData) { + for (var key2 in finalData) { + if (typeof(initialData[key1]) != "undefined" && + typeof(finalData[key2]) != "undefined" && + key1 == key2 && + initialData[key1] != finalData[key2] + ) { + return false; + } + } + } + return true; + } + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + buttonSave = new PMUI.ui.Button({ + id: 'saveTriggerButton', + text: "Save".translate(), + handler: function (event) { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1], + formwizard = triggerWindow.getItems()[2], + formTriggerData, + restClient, + dataToSend, + formTriggerData, + inputFields, + message_window, + outputV, + outputFields, + inputV, + dataToSend, + flagEdit; + if (formcustom.isVisible() == true) { + valuesCustom=formcustom.getItems()[0]; + if (!formEditTriggerCustom.isValid( )) { + flagEdit = formEditTriggerCustom.visible; + } else { + flagEdit = formEditTriggerCustom.isValid(); + } + if (flagEdit) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerCustom.html); + } else { + formTriggerData = formEditTriggerCustom.getData(); + } + if (formTriggerData.title.trim() === "") { + return false; + } + dataToSend = { + tri_title: formTriggerData.title, + tri_description: formTriggerData.description, + tri_webbot: formTriggerData.code, + tri_param: "" + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + formEditTriggerCustom.getItems()[0].getItems()[0].setValue(response.tri_uid); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message, + arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + if (formTriggerData.wizzard != "") { + if (formEditTriggerCustom.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "wizzardToCustomTriggerWin", + windowMessageType: 'warning', + title: 'Triggers'.translate(), + width: 490, + message: 'Do you want to save the changes? This Trigger will be saved like a custom Trigger.'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + openFormWizardEditMode(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.reset(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + updateCustom(dataToSend, formTriggerData.uid); + }, + buttonType: "success" + } + ] + + }); + message_window.open(); + message_window.showFooter(); + } else { + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + } + } else { + updateCustom(dataToSend, formTriggerData.uid); + } + } + } + } else if (formwizard.isVisible() == true) { + if (formEditTriggerWizard.isValid() || ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1))) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerWizard.html); + } else { + formTriggerData = formEditTriggerWizard.getData(); + } + + inputV = {}; + inputFields = formEditTriggerWizard.getItems()[3]; + for (i = 0; i < inputFields.getItems().length; i++) { + inputV[inputFields.getItems()[i].name] = formTriggerData[inputFields.getItems()[i].name]; + } + + outputV = {}; + outputFields = formEditTriggerWizard.getItems()[6]; + for (j = 0; j < outputFields.getItems().length; j++) { + outputV[outputFields.getItems()[j].name] = formTriggerData[outputFields.getItems()[j].name]; + } + + dataToSend = { + tri_title: formTriggerData.titleDetails, + tri_description: formTriggerData.descriptionDetails, + tri_type: "SCRIPT", + tri_params: { + input: inputV, + output: outputV + } + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName, + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + formEditTriggerWizard.getFields()[0].setValue(response.tri_uid); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName + '/' + formTriggerData.uid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + } + }, + buttonType: 'success' + }); + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + copyButton = new PMUI.ui.Button({ + id: 'copyAndSaveButton', + text: "Copy Trigger".translate(), + buttonType: 'success', + handler: function (event) { + var data, + dataToSend, + restClient; + if (formCopyTrigger.isValid()) { + formCopyTrigger.setDirty(false); + + data = formCopyTrigger.getData(); + dataToSend = { + tri_title: getData2PMUI(formCopyTrigger.html).tri_title.trim(), + tri_description: data.tri_description, + tri_webbot: data.tri_webbot, + tri_param: "" + }; + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + getListTrigger(); + formCopyTrigger.reset(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + }); + + //Buttons Apply for the Code Editor + applyButton = new PMUI.ui.Button({ + id: 'applyButton', + text: "Apply".translate(), + buttonType: 'success', + handler: function (event) { + + $("div.pmui-window-body.pmui-background").css('overflow', ''); + if (formEditCode.isValid()) { + var typeTitle = "Edit".translate(); + if (triggerWindow.getItems()[1].getData().uid == "") { + typeTitle = "Create".translate(); + } + openFormCustom(typeTitle); + formEditCode.setDirty(false); + + var editCode = formEditCode.getItems()[0].controls[0].cm; + editCodeValue = editCode.getValue(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorCustom != undefined) { + codeMirrorCustom.setSize(580, 150); //CodeMirror Size + } + codeMirrorCustom.setValue(editCodeValue); + formEditTriggerCustom.getItems()[1].setValue(editCodeValue); + + editCode.setValue(""); + editCodeValue = ""; + + formEditCode.getItems()[0].setValue(""); + } + } + }); + + //Button Edit Source Code (this is showed just when the Trigger Wizzard is opened in edition mode) + btnEditSourceCode = new PMUI.ui.Button({ + id: 'btnEditSourceCode', + text: "Edit Source Code".translate(), + buttonType: 'success', + handler: function (event) { + + var data = formEditTriggerWizard.getData(); + var fields; + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(650, 280); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.uid); + fields.getItems()[1].setValue(data.titleDetails); + fields.getItems()[2].setValue(data.descriptionDetails); + fields.getItems()[3].setValue(data.webbot); + fields.getItems()[3].setVisible(false); + formEditTriggerCustom.getItems()[1].setValue(data.webbot); + + codeMirrorControl.setValue(data.webbot); + + formEditTriggerCustom.getItems()[1].setHeight(300); + fields.getItems()[1].setVisible(false); + fields.getItems()[2].setVisible(false); + formEditTriggerCustom.footer.getItems()[1].setVisible(false); + formEditTriggerCustom.footer.getItems()[0].style.addProperties({'margin-right': "10px"}); + formEditTriggerCustom.footer.style.addProperties({width: '880px'}); + codeMirrorControl.refresh(); + } + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelTriggerButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + isDirtyFormTrigger(); + } + }); + + //Form to Edit the Custom trigger (we used a Form because we need buttons to save the changes) + formEditTriggerCustom = new PMUI.form.Form({ + id: "formEditTriggerCustom", + border: true, + visibleHeader: false, + width: '900px', + height: "365px", + name: "formcustom", + title: "Custom Trigger".translate(), + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + readOnly: true, + visible: false, + valueType: 'string' + }, + { + id: "title", + pmType: "text", + label: "Title".translate(), + value: "", + required: true, + name: "title", + valueType: 'string' + }, + { + id: "description", + pmType: "textarea", + rows: 70, + name: 'description', + label: "Description".translate(), + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "wizzard", + pmType: "text", + label: "Wizzard".translate(), + value: "", + name: "wizzard", + readOnly: true, + visible: false, + valueType: 'string' + } + ] + } + ], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditTriggerCustom.getItems()[1].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '208px', + "background": "rgb(30, 145, 209)", + "border": "0px solid rgb(30, 145, 209)" + } + } + }, { + text: "Open Editor".translate(), + id: "openEditorButton", + handler: function () { + openFormEditCode(); + formEditCode.showFooter(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + var value = codeMirrorCustom.getValue(); + + var codeMirrorCopy = formEditCode.getItems()[0].controls[0].cm; + + if (codeMirrorCopy != undefined) { + codeMirrorCopy.setSize(810, 315); //CodeMirror Size + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({'border': '1px solid #c0c0c0'}); + + } + + formEditCode.getItems()[0].setHeight(325); + + codeMirrorCopy.setValue(value); + formEditCode.getItems()[0].setValue(value); + formEditCode.setDirty(false); + + $('#codeEditor .pmui-field-label').hide(); + $('#formEditCode').children().last().css({ + 'margin-top': '-352px', + 'border': '0px', + 'margin-right': '-15px' + }).find('a').css('padding', '10px 5px'); + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({ + 'margin-left': '10px', + 'width': '850px', + 'height': '360px' + }); + $('#triggerWindow .pmui-window-body').css('overflow', 'hidden'); + codeMirrorCopy.refresh(); + }, + style: { + cssProperties: { + "margin-right": 2 + } + } + } + ] + }); + cd = new PMCodeMirrorField({ + labelWidth: '23.8%' + }); + cd.setLabel("Code".translate()); + formEditTriggerCustom.addItem(cd); + formEditTriggerCustom.getItems()[1].setName('code'); + formEditTriggerCustom.getItems()[1].setID('code'); + + formEditCode = new PMUI.form.Form({ + id: "formEditCode", + border: true, + visibleHeader: false, + width: '925px', + name: "formeditcode", + title: "Editor".translate(), + items: [], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditCode.getItems()[0].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '229px', + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + } + } + } + ] + }); + editCode = new PMCodeMirrorField({ + labelWidth: '9%' + }); + editCode.setLabel("Code".translate()); + formEditCode.addItem(editCode); + formEditCode.getItems()[0].setName('codeEditor'); + formEditCode.getItems()[0].setID('codeEditor'); + + //Trigger Window + triggerWindow = new PMUI.ui.Window({ + id: "triggerWindow", + title: "Triggers".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave, + btnEditSourceCode, + applyButton, + copyButton + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + isDirtyFormTrigger(); + } + }); + + + triggerWindow.addItem(gridListTrigger); + triggerWindow.addItem(formEditTriggerCustom); + triggerWindow.addItem(formEditTriggerWizard); + triggerWindow.addItem(formCopyTrigger); + triggerWindow.addItem(formEditCode); + triggerWindow.addItem(accordionNewTrigger); + + if (typeof listTriggers !== "undefined") { + triggerWindow.open(); + codMirr.dom.labelTextContainer.style.width = "23.8%"; + codMirr.html.style.padding = "10px"; + formEditTriggerCustom.panel.html.style.padding = "10px 10px"; + $('#listTriggers .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + applyStyleWindowForm(triggerWindow); + triggerWindow.hideFooter(); + openListTriggers(); + + gridListTrigger.dom.toolbar.appendChild(buttonNew.getHTML()); + buttonNew.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonCopy.getHTML()); + buttonCopy.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonWizard.getHTML()); + buttonWizard.defineEvents(); + + triggerWindow.defineEvents(); + gridListTrigger.sort('tri_title', 'asc'); + formEditTriggerCustom.panel.style.addProperties({'overflow': 'hidden'}); + + formcustom = triggerWindow.getItems()[1]; + valuesCustom=formcustom.getItems()[0]; + } + }; + + PMDesigner.trigger.create = function () { + var codeMirrorControl, cmControlCopyTrigger; + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + codeMirrorControl.refresh(); + } + codeMirrorControl.refresh(); + formEditTriggerCustom.getItems()[1].setHeight(170); + formEditTriggerCustom.reset(); + }; +}()); +/** + * new stepTask module + */ +var stepsTask = function (activity) { + this.mainWindow = null; + this.secondaryWindow = null; + this.stepsAssignTree = null; + this.mainContainer = null; + this.labelsPanel = null; + this.stepsMainContainer = null; + this.stepsAssignAccordion = null; + this.confirmWindow = null; + this.elementAccordionOpen = null; + this.groupType = null; + this.groupLabel = null; + this.stepsType = null; + this.stepsAssigned = null; + stepsTask.prototype.initialize.call(this, activity); +}; +/** + * initialization method steps settings, constants are created. + * components are created + * the data is loaded + * styles are customized + * It extends behaviors and events + */ +stepsTask.prototype.initialize = function () { + this.groupType = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL']; + this.groupLabel = ['Dynaform (s)'.translate(), 'Input Document (s)'.translate(), 'OutPut Document (s)'.translate(), 'External (s)'.translate()]; + this.stepsType = { + "DYNAFORM": "Dynaform".translate(), + "INPUT_DOCUMENT": "Input Document".translate(), + "OUTPUT_DOCUMENT": "Output Document".translate(), + "EXTERNAL": "External".translate() + }; + this.stepsAssigned = new PMUI.util.ArrayList(); + this.elementAccordionOpen = new PMUI.util.ArrayList(); + this.createWidgets(); + this.mainWindow.addItem(this.mainContainer); + this.mainWindow.open(); + this.loadInitialData(); + this.customStyles(); + this.elementsAccordionOpenFixed(); + this.addEventSortableInAccordionElements(); + this.addEventSortableInTreePanelElements(); +}; +/** + * the components are created PMUI UI + * - confirmWindow + * - mainWindow + * - labelsPanel + * - stepsAssignTree + * - stepsAssignAccordion + * - stepsMainContainer + * - mainContainer + * - secondaryWindow + */ +stepsTask.prototype.createWidgets = function () { + var that = this; + this.confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: '', + message: '', + footerItems: [ + { + id: 'confirmWindow-footer-no', + text: 'No'.translate(), + visible: true, + buttonType: "error" + }, { + id: 'confirmWindow-footer-yes', + text: 'Yes'.translate(), + visible: true, + buttonType: "success" + } + ], + visibleFooter: true + }); + this.mainWindow = new PMUI.ui.Window({ + id: "stepsForTask", + title: "Steps for task".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH + }); + this.labelsPanel = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + proportion: 0.08, + layout: "hbox", + items: [ + new PMUI.field.TextAnnotationField({ + text: 'Available Elements'.translate(), + text_Align: 'center', + proportion: 1.4 + }), + new PMUI.field.TextAnnotationField({ + text: 'Assigned Elements (Drop here)'.translate(), + text_Align: 'center', + proportion: 1.3 + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Expand all".translate(), + id: "expand-button", + proportion: 0.6, + handler: function () { + var items, i, item, buttonAfected; + items = that.stepsAssignAccordion.getItems(); + buttonAfected = that.labelsPanel.getItem("collapse-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + that.elementAccordionOpen.clear(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + item.expand(); + that.elementAccordionOpen.insert(item); + } + } + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Collapse all".translate(), + id: "collapse-button", + proportion: 0.7, + disabled: true, + handler: function () { + var items, i, item, buttonAfected; + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + items = that.stepsAssignAccordion.getItems(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + that.elementAccordionOpen.remove(item); + item.collapse(); + } + } + }) + ] + }); + this.stepsAssignTree = new PMUI.panel.TreePanel({ + id: 'stepsAssignTree', + proportion: 0.5, + height: 475, + filterable: true, + autoBind: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nodeDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true, + collapsed: false, + itemsDataBind: 'items', + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + behavior: 'drag' + }, + style: { + cssProperties: { + margin: '0px 0px 0px 0px', + float: 'left', + overflow: 'auto' + }, + cssClasses: ['mafe-border-panel'] + } + }); + this.stepsAssignAccordion = new PMUI.panel.AccordionPanel({ + id: 'stepsAssignAccordion', + multipleSelection: true, + hiddenTitle: true, + proportion: 1.5, + style: { + cssProperties: { + margin: '0px 0px 0px 0px' + }, + cssClasses: ['mafe-border-panel'] + }, + listeners: { + select: function (accordionItem, event) { + var buttonExpand, buttonCollapse, itemsAccod; + itemsAccod = that.stepsAssignAccordion.items; + if (accordionItem.collapsed) { + if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { + that.elementAccordionOpen.remove(accordionItem); + } + } else { + if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { + that.elementAccordionOpen.insert(accordionItem); + } + } + buttonCollapse = that.labelsPanel.getItem("collapse-button"); + buttonExpand = that.labelsPanel.getItem("expand-button"); + if (that.elementAccordionOpen.getSize() === 0) { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(true); + } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { + buttonExpand.setDisabled(true); + buttonCollapse.setDisabled(false); + } else { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(false); + } + } + } + }); + this.stepsMainContainer = new PMUI.core.Panel({ + id: "stepsMainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'hbox', + height: 475, + items: [ + this.stepsAssignTree, + this.stepsAssignAccordion + ] + }); + this.mainContainer = new PMUI.core.Panel({ + id: "mainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'vbox', + items: [ + this.labelsPanel, + this.stepsMainContainer + ] + }); + this.secondaryWindow = new PMUI.ui.Window({ + visibleFooter: true, + title: 'Trigger'.translate(), + footerAlign: 'right', + footerItems: [ + { + text: "@@", + id: "secondaryWindow-criteria", + handler: function () { + }, + style: { + cssProperties: { + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + }, + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-cancel', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + }, + handler: function () { + } + }, { + id: 'secondaryWindow-save', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + }, + handler: function () { + } + } + ] + }); +}; +/** + * This method loads the initial data module steps,for the components: + * - stepsAssignTree + * - stepsAssignAccordion + */ +stepsTask.prototype.loadInitialData = function () { + this.loadTreePanelData(this.getTreePanelData()); + this.loadAccordionItems(this.getAccordionData()); +}; +/** + * This method loads the options to stepsAssignAccordion + * @param {Array} response An array where each element can be a {Element} object or a JSON object + */ +stepsTask.prototype.loadAccordionItems = function (response) { + var firstResp = [], + secondResp = [], + i, + item, + assigmentConfig, + firstRes = 0, + secondRes = 1; + if (jQuery.isArray(response) && response.length) { + if (typeof response[firstRes] === "object") { + firstResp = response[firstRes].response ? response[firstRes].response : []; + } + if (typeof response[secondRes] === "object") { + secondResp = response[secondRes].response ? response[secondRes].response : []; + } + } + if (firstResp.length) { + for (i = 0; i < firstResp.length; i += 1) { + item = this.createAccordionItem(firstResp[i], true, true); + this.stepsAssignAccordion.addItem(item); + item.dataItem = firstResp[i]; + this.customAccordionItemButtons(item.html, firstResp[i], item); + } + } + assigmentConfig = { + step_type_obj: "Assignment".translate(), + triggers: secondResp, + st_type: "ASSIGNMENT", + obj_title: "Assignment".translate(), + step_uid_obj: "Assignment" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + assigmentConfig = { + step_type_obj: "Routing".translate(), + triggers: secondResp, + obj_title: "Routing".translate(), + st_type: 'ROUTING', + step_uid_obj: "Routing" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + this.stepsAssignAccordion.defineEvents(); +}; +/** + * This method creates an element for stepsAssignAccordion + * @param {data} It is an object with the settings to create the element + * @returns {PMUI.item.AccordionItem} + */ +stepsTask.prototype.createAccordionItem = function (data) { + var that = this, + gridBefore, + gridAfter, + beforeTitle, + afterTitle, + i, + textLabel; + if (this.stepsType[data.step_type_obj]) { + textLabel = this.stepsType[data.step_type_obj]; + } else { + textLabel = data.step_type_obj; + } + beforeTitle = new PMUI.field.TextAnnotationField({ + text: 'Before'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left' + }); + afterTitle = new PMUI.field.TextAnnotationField({ + text: 'After'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left', + visible: data.st_type === "ASSIGNMENT" ? false : true + }); + + gridBefore = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + st_type: 'BEFORE', + step_uid: data.step_uid, + visibleFooter: false, + width: '96%', + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: "st_position", + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridBefore.st_type = 'BEFORE'; + } else if (data.st_type === "ROUTING") { + gridBefore.st_type = "BEFORE_ROUTING"; + } else { + gridBefore.st_type = "BEFORE_ASSIGNMENT"; + } + gridBefore.step_uid = data.step_uid; + gridBefore.clearItems(); + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridBefore.st_type === data.triggers[i].st_type) { + gridBefore.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + gridAfter = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + visibleFooter: false, + width: '96%', + visible: data.st_type === "ASSIGNMENT" ? false : true, + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: 'st_position', + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridAfter.st_type = 'AFTER'; + } else if (data.st_type == "ROUTING") { + gridAfter.st_type = "AFTER_ROUTING"; + } else { + gridAfter.st_type = "AFTER_ASSIGNMENT"; + } + gridAfter.step_uid = data.step_uid; + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridAfter.st_type === data.triggers[i].st_type) { + gridAfter.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + var accordionItem = new PMUI.item.AccordionItem({ + id: 'id' + data.step_uid_obj, + dataStep: data, + closeable: true, + body: new PMUI.core.Panel({ + layout: 'vbox', + items: [ + beforeTitle, + gridBefore, + afterTitle, + gridAfter + ] + }) + }); + if (this.stepsType[data.step_type_obj]) { + accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + this.stepsType[data.step_type_obj] + ')'); + this.stepsAssigned.insert(accordionItem); + } else { + accordionItem.setTitle((this.stepsAssignAccordion.items.getSize() + 1) + ". " + data.obj_title); + } + return accordionItem; +}; +/** + * styles that can not be handled with the library are customized PMUI + * @chainable + */ +stepsTask.prototype.customStyles = function () { + this.mainWindow.body.style.overflow = "hidden"; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get + * dynaforms, output document, input Document and external, Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getStepAvailables = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + if (jQuery.isArray(response)) { + resp = response[0] ? response[0].response : []; + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get all Availables + * triggres and dynaforms Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getTreePanelData = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' + }, { + url: 'triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +} +/** + * this method loads the data to stepsAssignTree + * @param response, the answer is an array containing all the elements + * that will be loaded into the step stepsAssignTree + * @chainable + */ +stepsTask.prototype.loadTreePanelData = function (response) { + var that = this, + data, + i, + j, + type, + label, + items, + labelTrigger, + dataTree = [], + treeNode; + data = response[1].response; + labelTrigger = 'Trigger (s)'.translate(); + if (data.length === 0) { + dataTree.push({ + obj_title: labelTrigger, + items: [this.notItemConfig()] + }); + } else { + items = []; + for (i = 0; i < data.length; i += 1) { + items.push({ + obj_title: data[i]['tri_title'], + obj_type: data[i]['tri_type'], + obj_uid: data[i]['tri_uid'] + }); + } + dataTree.push({ + obj_title: labelTrigger, + items: items, + id: "TRIGGER" + }); + } + data = response[0].response; + type = this.groupType; + label = this.groupLabel; + items = []; + for (i = 0; i < type.length; i += 1) { + items = []; + for (j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [this.notItemConfig()], + behavior: '', + id: type[i] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items, + behavior: 'drag', + id: type[i] + }); + } + } + this.stepsAssignTree.clearItems(); + for (i = 0; i < dataTree.length; i += 1) { + this.stepsAssignTree.addDataItem(dataTree[i]); + treeNode = this.stepsAssignTree.getItem(i); + treeNode.setID(dataTree[i].id); + this.updateIndexPosition(treeNode); + } + return this; +}; +/** + * run the endpoint 'activity/{activity_id}/steps' and 'activity/{activity_id}/step/triggers' + * to get all triggres and dynaforms assigned + * @returns {Array} + */ +stepsTask.prototype.getAccordionData = function () { + var resp = [], + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + PMDesigner.act_uid + '/steps', + method: 'GET' + }, { + url: 'activity/' + PMDesigner.act_uid + '/step/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }); + restClient.executeRestClient(); + return resp; +}; +/** + * checks whether a trigger is already assigned in a grid + * @param grid, is instanceof PMUI.grid.Grid, in conducting the search + * @param tri_uid, search parameter in the rows of the grid + * @returns {boolean} + */ +stepsTask.prototype.isTriggerAssigned = function (grid, tri_uid) { + var data, i, exist = false; + data = grid.getData(); + if (grid && jQuery.isArray(data)) { + for (i = 0; i < data.length; i += 1) { + if (data[i].tri_uid === tri_uid) { + exist = true; + break; + } + } + } + return exist; +}; +/** + * retorna el tipo de de step, para la ejecucion de "endpoint" + * @param st_type, this a step type, the accepted parameters are: + * - BEFORE_ASSIGNMENT + * - BEFORE_ROUTING + * - AFTER_ROUTING + * - BEFORE + * - AFTER + * @returns {string} + */ +stepsTask.prototype.getStepType = function (st_type) { + var value; + switch (st_type) { + case 'BEFORE_ASSIGNMENT': + value = 'before-assignment'; + break; + case 'BEFORE_ROUTING': + value = 'before-routing'; + break; + case 'AFTER_ROUTING': + value = 'after-routing'; + break; + case 'BEFORE': + value = 'before'; + break; + case 'AFTER': + value = 'after'; + break; + default: + value = ''; + break; + } + return value; +}; +/** + * This method is executed when editing a "trigger" in a row of the grid. + * secondary window opens with the current configuration of the trigger + * @param trigger, is the return value when is update 'trigger' action in the enpoint + * @param triggerID, is the id of the trigger to update + * @chainable + */ +stepsTask.prototype.editTrigger = function (trigger, triggerID) { + var codeMirror, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + codeMirror = new PMCodeMirror({ + id: "codeMirror" + }); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + codeMirror.setValue(trigger); + this.secondaryWindow.setWidth(DEFAULT_WINDOW_WIDTH); + this.secondaryWindow.setHeight(DEFAULT_WINDOW_HEIGHT); + this.secondaryWindow.setTitle("Trigger".translate()); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + triggerID, + typeRequest: 'update', + data: { + tri_param: '', + tri_webbot: codeMirror.getValue() + }, + messageError: 'There are problems updating the trigger, please try again.'.translate(), + messageSuccess: 'Trigger updated correctly'.translate(), + flashContainer: that.mainWindow, + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(true); + criteriaButton.setHandler(function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var cursorPos, + codemirror; + codemirror = codeMirror.cm; + cursorPos = codemirror.getCursor(); + codemirror.replaceSelection(variable); + codemirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }); + } + this.secondaryWindow.open(); + this.secondaryWindow.addItem(codeMirror); + codeMirror.cm.setSize(this.secondaryWindow.getWidth(), 380); + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + $(".pmui-window-body").css("overflow", "hidden"); + codeMirror.cm.refresh(); +}; +/** + * edit the selected trigger condition + * @param stepID, It is the id of the step to upgrade + * @param triggerID, is the id of the trigger to update + * @param stepType, It is the kind of step to update + * @param row, PMUI.grid.GridPanelRow, is the row affected + */ +stepsTask.prototype.editCondition = function (stepID, triggerID, stepType, row) { + var saveButton, + cancelButton, + criteriaButton, + form, + dataRow, + that = this; + dataRow = row.getData(); + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(500); + this.secondaryWindow.setHeight(350); + this.secondaryWindow.setTitle('Condition Trigger'.translate()); + this.secondaryWindow.setTitle("Trigger".translate()); + form = new PMUI.form.Form({ + id: 'idFormEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + new CriteriaField({ + id: 'st_condition', + pmType: 'textarea', + name: 'st_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea', + value: dataRow.st_condition + }) + ] + }); + this.secondaryWindow.addItem(form); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var data, + restClient; + data = form.getData(); + data.st_type = stepType; + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + ((typeof(stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, + typeRequest: 'update', + data: data, + messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + functionSuccess: function (xhr, response) { + dataRow.st_condition = data.st_condition; + row.setData(dataRow); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + that.secondaryWindow.close(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(false); + criteriaButton.handler = null; + } + this.secondaryWindow.open(); +}; +/** + * eliminates the elements of the secondary window + * @chainable + */ +stepsTask.prototype.resetSecondaryWindow = function () { + var i, items; + if (this.secondaryWindow && this.secondaryWindow.items.getSize() > 0) { + items = this.secondaryWindow.items; + for (i = 0; i < items.getSize(); i += 1) { + this.secondaryWindow.removeItem(items.get(i)); + } + } +}; +/** + * It establishes a PMUI.util.ArrayList that stores the + * elements of "stepsAssignAccordion" that are open + * @chainable + */ +stepsTask.prototype.elementsAccordionOpenFixed = function () { + var i, + accordionItems; + if (this.stepsAssignAccordion) { + accordionItems = this.stepsAssignAccordion.getItems(); + if ($.isArray(accordionItems)) { + for (i = 0; i < accordionItems.length; i += 1) { + if (!accordionItems[i].collapsed) { + this.elementAccordionOpen.insert(accordionItems[i]); + } + } + } + } +}; +/** + * It is an extension to add the "sortable" event "stepAssignAccordion". + * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. + * @chainable + */ +stepsTask.prototype.addEventSortableInAccordionElements = function () { + var tagContainer, + newIndex, + index, + treeNodeObject, + treeNodeData, + that = this; + if (this.stepsAssignAccordion && this.stepsAssignAccordion.html) { + tagContainer = this.stepsAssignAccordion.body; + $(tagContainer).sortable({ + items: '>div:not(#idAssignment,#idRouting)', + placeholder: 'steps-placeholder', + receive: function (event, ui) { + var item = ui ? ui.item : null; + if (item && item instanceof jQuery && item.length) { + treeNodeObject = PMUI.getPMUIObject(item.get(0)); + treeNodeData = treeNodeObject.getData(); + } + }, + stop: function (event, ui) { + var itemClone = ui ? ui.item : null, + accordionItems, + accordionItem, + dataEdited, + restClientMultipart, + restClient; + var newIndex = ui.item.index(); + accordionItems = that.stepsAssignAccordion.getItems(); + if (itemClone && itemClone instanceof jQuery && itemClone.length) { + if (treeNodeObject) { + itemClone.remove(); + if (newIndex + 1 > accordionItems.length) { + newIndex = that.stepsAssigned.getSize(); + } + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step', + typeRequest: 'post', + data: { + step_type_obj: treeNodeData.obj_type, + step_uid_obj: treeNodeData.obj_uid, + step_condition: '', + step_position: newIndex + 1, + step_mode: 'EDIT' + }, + functionSuccess: function (xhr, response) { + var item, buttonAfected, treeNode; + that.stepsAssignTree.removeItem(treeNodeObject); + treeNode = that.stepsAssignTree.items.find("id", response.step_type_obj); + if (treeNode.items.getSize() === 0) { + treeNode.addDataItem(that.notItemConfig()); + } + response.obj_description = ''; + response.obj_title = treeNodeData.obj_title; + response.triggers = []; + item = that.createAccordionItem(response, true, true); + item.dataItem = response; + if (that.stepsAssignAccordion.items.getSize() === 2) { + that.stepsAssignAccordion.addItem(item, 0); + } else { + that.stepsAssignAccordion.addItem(item, newIndex); + } + that.stepsAssignAccordion.defineEvents(); + that.customAccordionItemButtons(item.html, response, item); + that.updateItemIndexToAccordion(); + that.addEventSortableInAccordionElements(); + that.addEventSortableInTreePanelElements(); + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while assigning the step, please try again later.'.translate(), + messageSuccess: 'Step assigned successfully.'.translate(), + flashContainer: that.stepsAssignAccordion.getParent() + }); + restClient.executeRestClient(); + } else { + accordionItem = PMUI.getPMUIObject(ui.item.get(0)); + index = that.stepsAssignAccordion.items.indexOf(accordionItem); + if (newIndex !== index) { + that.stepsAssignAccordion.items.remove(accordionItem); + that.stepsAssignAccordion.items.insertAt(accordionItem, newIndex); + dataEdited = { + step_position: newIndex + 1, + step_uid: accordionItem.dataItem.step_uid, + step_type_obj: accordionItem.dataItem.step_type_obj, + step_uid_obj: accordionItem.dataItem.step_uid_obj + }; + restClientMultipart = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + accordionItem.dataItem.step_uid, + typeRequest: 'update', + data: dataEdited, + functionSuccess: function (xhr, response) { + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while editing the step, please try again later.'.translate(), + messageSuccess: 'Step editing successfully.'.translate(), + flashContainer: this.mainWindow + }); + restClientMultipart.executeRestClient(); + } + } + } + }, + start: function (e, ui) { + newIndex = ui.item.index(); + } + }); + } +}; +/** + * It is an extension to add the "sortable" event "stepsAssignTree". + * when choosing a node treePanel and you want to add to the accordion or the grid + * @chainable + */ +stepsTask.prototype.addEventSortableInTreePanelElements = function () { + var items = this.stepsAssignTree.getItems(), + connect, + i, + sw, + that = this, + nodeItems; + for (i = 0; i < items.length; i += 1) { + nodeItems = items[i].getItems(); + if (nodeItems.length && nodeItems[0].getData().obj_type) { + sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; + connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; + $(items[i].html).find('ul').find('>li').draggable({ + appendTo: document.body, + revert: "invalid", + helper: "clone", + cursor: "move", + zIndex: 1000, + connectToSortable: connect, + start: function (e) { + var i, nodeTag, node, nodeData, accordionItems, item; + nodeTag = e.target; + node = PMUI.getPMUIObject(nodeTag); + nodeData = node.getData(); + accordionItems = that.stepsAssignAccordion.getItems(); + $(that.stepsAssignAccordion.body).hide(); + if (nodeData.obj_type !== "SCRIPT") { + for (i = 0; i < accordionItems.length; i += 1) { + item = accordionItems[i]; + item.collapse(); + } + } + $(that.stepsAssignAccordion.body).show(); + }, + stop: function () { + var i = 0, max; + if (that.elementAccordionOpen) { + max = that.elementAccordionOpen.getSize(); + for (i = 0; i < max; i += 1) { + that.elementAccordionOpen.get(i).expand(); + } + } + } + }); + } else { + $(nodeItems[0].html).draggable("disable"); + } + } +}; +/** + * add custom buttons on the head of an element of stepsAssignAccordion + * are three buttons + * properties + * edit + * remove + * @param html, is the html of the header accordion item + * @param step, the data of the step selected + */ +stepsTask.prototype.customAccordionItemButtons = function (html, step, accordionItem) { + var propertiesStep, + editStep, + removeStep, + $html, + containerButtons, + that = this, + title; + if (html) { + $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); + title = step.obj_title + ' (' + step.step_type_obj + ')'; + $html.find(".pmui-accordion-item-title").get(0).title = title; + containerButtons = $('
'); + containerButtons.addClass("propertiesTask-accordionItem"); + propertiesStep = $('' + 'Properties'.translate() + ''); + propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + editStep = $('' + 'Edit'.translate() + ''); + editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + removeStep = $('' + 'Remove'.translate() + ''); + removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); + + propertiesStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.propertiesStepShow(step); + return false; + }); + + editStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.editStepShow(step, accordionItem); + return false; + }); + + removeStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.removeStepShow(step); + return false; + }); + containerButtons.append(propertiesStep); + containerButtons.append(editStep); + containerButtons.append(removeStep); + $html.append(containerButtons); + } +}; +/** + * opens the properties of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ +stepsTask.prototype.propertiesStepShow = function (step) { + var form, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(520); + this.secondaryWindow.setHeight(370); + this.secondaryWindow.setTitle('Step Properties'.translate()); + form = new PMUI.form.Form({ + id: 'stepsEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + { + id: 'step_mode', + pmType: 'radio', + label: 'Mode'.translate(), + value: '', + visible: step.step_type_obj === "DYNAFORM" ? true : false, + name: 'step_mode', + options: [ + { + id: 'modeEdit', + label: 'Edit'.translate(), + value: 'EDIT', + selected: true + }, { + id: 'modeView', + label: 'View'.translate(), + value: 'VIEW' + } + ] + }, + new CriteriaField({ + id: 'step_condition', + pmType: 'textarea', + name: 'step_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea' + }) + ] + }); + this.secondaryWindow.addItem(form); + + var restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + form.getField('step_mode').setValue(response.step_mode); + form.getField('step_condition').setValue(response.step_condition); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient; + if (form.isValid()) { + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'update', + data: form.getData(), + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems update the Step Trigger, please try again.'.translate() + }); + restClient.executeRestClient(); + } + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.handler = null; + criteriaButton.setVisible(false); + } + this.secondaryWindow.open(); +}; +/** + * opens the step of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ +stepsTask.prototype.editStepShow = function (step, accordioItem) { + var inputDocument, + that = this; + switch (step.step_type_obj) { + case 'DYNAFORM': + var restProxy = new PMRestClient({ + endpoint: 'dynaform/' + step.step_uid_obj, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var old = PMUI.activeCanvas, + formDesigner; + PMUI.activeCanvas = false; + formDesigner = PMDesigner.dynaformDesigner(response); + formDesigner.onHide = function () { + var assignedDynaform, + i, + data, + title; + assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); + if (jQuery.isArray(assignedDynaform)) { + for (i = 0; i < assignedDynaform.length; i += 1) { + data = assignedDynaform[i]; + if (typeof data === "object") { + if (data.step_uid === step.step_uid) { + title = data.step_position + ". " + data.obj_title; + title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; + accordioItem.setTitle(title); + accordioItem.dataItem = data; + } + } + } + } + PMUI.activeCanvas = old; + }; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + break; + case 'OUTPUT_DOCUMENT': + PMDesigner.output(); + PMDesigner.output.showTiny(step.step_uid_obj); + break; + case 'INPUT_DOCUMENT': + inputDocument = new InputDocument({ + onUpdateInputDocumentHandler: function (data, inputDoc) { + var position, title; + position = accordioItem.dataItem.step_position; + title = position + ". " + data.inp_doc_title; + title = title + ' (' + that.stepsType["INPUT_DOCUMENT"] + ')'; + accordioItem.dataItem.obj_title = data.inp_doc_title; + accordioItem.setTitle(title); + inputDoc.winMainInputDocument.close(); + } + }); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); + break; + } +}; +/** + * the window opens for confirmation of the removal step + * @param step, the current step to remove + * @chainable + */ +stepsTask.prototype.removeStepShow = function (step) { + var title, + yesButton, + noButton, + that = this, + restClient; + if (this.stepsType[step.step_type_obj] !== undefined) { + title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); + this.confirmWindow.setTitle(title); + } else { + this.confirmWindow.setTitle("Step " + step.step_type_obj.capitalize()); + } + this.confirmWindow.setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.removingStepTask(step, response); + that.confirmWindow.close(); + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), + messageSuccess: 'Step removed successfully'.translate(), + flashContainer: that.mainWindow.getParent() + }); + restClient.executeRestClient(); + }); + } + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); + }); + } + this.confirmWindow.open(); +}; +/** + * eliminates the step of step Assign Accordion + * @param step, the current step to remove + * @param response, data from the endpoint + */ +stepsTask.prototype.removingStepTask = function (step, response) { + var stepObject, + stepAvailable, + treeNodeObject, + stepAvailables, + i, + itemsTreeNode = [], + items = []; + stepObject = this.stepsAssignAccordion.getItem("id" + step.step_uid_obj); + this.elementAccordionOpen.remove(stepObject); + this.stepsAssigned.remove(stepObject); + this.stepsAssignAccordion.removeItem(stepObject); + if (stepObject) { + stepAvailable = this.getStepAvailables(); + stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); + for (i = 0; i < stepAvailables.length; i += 1) { + items.push({ + obj_title: stepAvailables[i]['obj_title'], + obj_type: stepAvailables[i]['obj_type'], + obj_uid: stepAvailables[i]['obj_uid'] + }); + } + treeNodeObject = this.stepsAssignTree.getItem(step.step_type_obj); + itemsTreeNode = treeNodeObject.getItems(); + for (i = 0; i < itemsTreeNode.length; i += 1) { + treeNodeObject.removeItem(itemsTreeNode[i]); + } + treeNodeObject.clearItems(); + treeNodeObject.setDataItems(items); + this.updateIndexPosition(treeNodeObject); + this.addEventSortableInTreePanelElements(); + this.addEventSortableInAccordionElements(); + } +}; +/** + * get the steps is not assigned by a criterion + * @param criteria, It is the filter criteria search + * @param stepAvailable, all steps Unassigned + * @returns {Array}, filtered items + */ +stepsTask.prototype.getAvailablesStepsByCriteria = function (criteria, stepAvailable) { + var items = [], + i; + if (jQuery.isArray(stepAvailable)) { + for (i = 0; i < stepAvailable.length; i += 1) { + if (stepAvailable[i].obj_type === criteria) { + items.push(stepAvailable[i]); + } + } + } + return items; +}; +/** + * This method is executed when an element stepsAssignTree, is assigned in a grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @returns {stepsTask} + */ +stepsTask.prototype.receiveTreeNodeItem = function (receiveData, grid, index) { + var restClient, that = this, message; + if (that.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow + }); + message.show(); + return; + } + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + typeRequest: 'post', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: '', + st_position: index + 1 + }, + functionSuccess: function (xhr, response) { + grid.addDataItem({ + st_condition: '', + st_position: index + 1, + st_type: grid.st_type, + tri_description: '', + tri_title: receiveData.obj_title, + tri_uid: receiveData.obj_uid, + obj_title: receiveData.obj_title, + obj_uid: receiveData.obj_uid + }, index); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method is executed when a row is drop in another grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @param draggableItem + * @returns {*} + */ +stepsTask.prototype.receiveRowItem = function (receiveData, grid, index, draggableItem) { + var receiveParent = draggableItem.getParent(), + message, + restClient, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow + }); + index = receiveParent.items.indexOf(draggableItem); + receiveParent.items.remove(draggableItem); + receiveParent.addItem(draggableItem, index); + message.show(); + return false; + } + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + method: 'POST', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + } + }, { + url: receiveParent.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + receiveData.obj_uid + '/' + that.getStepType(receiveParent.st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + receiveParent.step_uid + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), + method: 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + var data; + data = receiveData; + if (data.hasOwnProperty("st_type")) { + data.st_type = grid.st_type; + grid.addDataItem(receiveData, index); + } + receiveParent.removeItem(draggableItem); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: [ + 'An unexpected error while assigning the trigger, please try again later.'.translate() + ], + messageSuccess: [ + 'Trigger assigned successfully.'.translate() + ] + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method is executed when a row is sorted in the grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the new index position row + * @returns {stepsTask} + */ +stepsTask.prototype.sortableRowHandler = function (receiveData, grid, index) { + var that = this, + restClient; + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + "/step/trigger/" + receiveData.tri_uid : + 'activity/' + PMDesigner.act_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, + typeRequest: 'update', + data: { + st_type: receiveData.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger assigned successfully.'.translate() + }); + restClient.executeRestClient(); + return this; +}; +/** + * This method eliminates the list of triggers trigger an assigned step + * @param row, the row affected or selected + * @param grid, It is affected or grid to remove selected row + */ +stepsTask.prototype.removeTrigger = function (row, grid) { + var message = 'Do you want to remove the trigger "', + messageData = row.getData().tri_title ? row.getData().tri_title : "", + yesButton, + noButton, + that = this, + restClient; + message = message + messageData + '"?'; + this.confirmWindow.setMessage(message.translate()); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type), + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + that.confirmWindow.close(); + that.updateIndexToGrid(grid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger removed successfully'.translate() + }); + restClient.executeRestClient(); + }); + } + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); + }); + } + this.confirmWindow.open(); +}; +/** + * updates indexes of elements selected grid + * @param grid, It is affected or grid to remove selected row + * @returns {stepsTask} + */ +stepsTask.prototype.updateIndexToGrid = function (grid) { + var cell, rows, i, row; + if (grid) { + rows = grid.getItems(); + if (jQuery.isArray(rows)) { + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + cell = row.cells.find("columnData"); + if (cell) { + cell.setContent(i + 1); + } + } + } + } + return this; +}; +/** + * get the steps assigned by a search criterion + * @param criteria, search filter, after running the endpoint getAccordionData method + * @returns {Array}, response with criteria + */ +stepsTask.prototype.getStepsAssignedByCriteria = function (criteria) { + var allAssigned, + i, + elements, + j, + resp, + response = []; + allAssigned = this.getAccordionData(); + if (jQuery.isArray(allAssigned)) { + for (i = 0; i < allAssigned.length; i += 1) { + resp = allAssigned[i]; + if (typeof resp === "object") { + elements = resp.response ? resp.response : []; + for (j = 0; j < elements.length; j += 1) { + data = elements[j]; + if (typeof data === "object") { + if (data.step_type_obj && data.step_type_obj === criteria) { + response.push(data); + } + } + } + } + } + } + return response; +}; +/** + * updates indexes of elements assigned + * @returns {stepsTask} + */ +stepsTask.prototype.updateItemIndexToAccordion = function () { + var title, + i, + item, + dataItem, + items = this.stepsAssignAccordion.items, + position, + max; + max = items.getSize(); + for (i = 0; i < max; i += 1) { + item = items.get(i); + position = items.indexOf(item); + dataItem = item.dataItem; + title = (position + 1) + ". " + dataItem.obj_title; + if (this.stepsType[dataItem.step_type_obj]){ + title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; + } + item.dataItem.step_position = i + 1; + item.setTitle(title); + } + return this; +}; +/** + * add tooltip in treeNode elements + * @returns {stepsTask} + */ +stepsTask.prototype.updateIndexPosition = function (treeNode) { + var items, i, item, $item, text, data; + if (treeNode && treeNode.html) { + items = treeNode.getItems(); + if (jQuery.isArray(items)) { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + if (item.html) { + $item = $(item.html); + data = item.getData(); + text = $item.find("a").get(0); + text.title = data.obj_title; + } + } + } + } + return this; +}; +/** + * return the not items config. + * @returns {{obj_title: *, obj_uid: string, id: string}} + */ +stepsTask.prototype.notItemConfig = function () { + var config = { + obj_title: 'N/A'.translate(), + obj_uid: '', + id: "notItem" + }; + return config; +}; +( + function () { + var processPermissionsSetForm; + PMDesigner.processPermissions = function (event) { + var PROCESS_PERMISSIONS_OPTION = "", + PROCESS_PERMISSIONS_UID = "", + arrayCboGroup = [], + arrayCboUser = [], + winGrdpnlProcessPermissions, + grdpnlProcessPermissions, + frmProcessPermissions, + processPermissionsData, + btnCreate, btnSave, btnCancel, + loadDataFromServerToFields, + disableAllItems, + listProcessPermissions, + isDirty2, + isDirtyFormProcessPermission, + refreshGridPanelInMainWindow, + processPermissionsGetRestProxy, + processPermissionsPostRestProxy, + processPermissionGetRestProxy, + processPermissionsPutRestProxy, + cboTargetCboOriginTaskSetOptionsRestProxy, + cboDynaFormSetOptionsRestProxy, + cboInputDocumentSetOptionsRestProxy, + cboOutputDocumentSetOptionsRestProxy, + processPermissionsSetFormByType, + processPermissionsDeleteRestProxy, + cboStatusCase, + cboTargetTask, + cboGroupOrUser, + cboOriginTask, + optionsType, + cboType, + cboDynaForm, + cboInputDocument, + cboOutputDocument, + cboPermission, + cboParticipationRequired, + processPermissionsDataIni = {}, + notification, + notificationText = "Fields marked with an asterisk (%%ASTERISK%%) are required.".translate() + .replace(/%%ASTERISK%%/g, '*'); + + loadDataFromServerToFields = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/dynaforms', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/input-documents', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/output-documents', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var i; + data = response[0].response; + cboTargetTask.clearOptions(); + cboOriginTask.clearOptions(); + cboTargetTask.addOption({value: '', label: 'All Tasks'.translate()}); + cboOriginTask.addOption({value: '', label: 'All Tasks'.translate()}); + for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { + cboTargetTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + cboOriginTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + } + //project/dynaforms + data = response[1].response; + cboDynaForm.clearOptions(); + cboDynaForm.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); + } + //project/input-documents + data = response[2].response; + cboInputDocument.clearOptions(); + cboInputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); + } + //project/output-documents + data = response[3].response; + cboOutputDocument.clearOptions(); + cboOutputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + + disableAllItems = function () { + winGrdpnlProcessPermissions.getItems()[0].setVisible(false); + winGrdpnlProcessPermissions.getItems()[1].setVisible(false); + winGrdpnlProcessPermissions.hideFooter(); + }; + + isDirty2 = function () { + var user, + dynaForm, + inputDocument, + outputDocument, + flagInsert = (typeof(processPermissionsData.op_case_status) === "undefined") ? true : false; + + if (flagInsert) { + processPermissionsData = processPermissionsDataIni; + } + + if (cboStatusCase.getValue() != processPermissionsData.op_case_status) { + return true; + } + + if (cboTargetTask.getValue() != processPermissionsData.tas_uid) { + return true; + } + + user = (cboGroupOrUser.get("value") !== null && cboGroupOrUser.get("value")) ? cboGroupOrUser.get("value") : ""; + + if (user != processPermissionsData.usr_uid) { + return true; + } + + if (cboOriginTask.getValue() != processPermissionsData.op_task_source) { + return true; + } + + if (cboParticipationRequired.getValue() != processPermissionsData.op_participate) { + return true; + } + + if (cboType.getValue() != processPermissionsData.op_obj_type) { + return true; + } + + switch (cboType.getValue()) { + case "DYNAFORM": + dynaForm = (cboDynaForm.getValue() !== "") ? cboDynaForm.getValue() : "0"; + + if (dynaForm != processPermissionsData.op_obj_uid) { + return true; + } + + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + case "ATTACHMENT": + if (cboPermission.getValue() !== processPermissionsData.op_action) { + return true; + } + break; + case "INPUT": + inputDocument = (cboInputDocument.getValue() !== "") ? cboInputDocument.getValue() : "0"; + + if (inputDocument != processPermissionsData.op_obj_uid) { + return true; + } + + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + + break; + case "OUTPUT": + outputDocument = (cboOutputDocument.getValue() !== "") ? cboOutputDocument.getValue() : "0"; + + if (outputDocument != processPermissionsData.op_obj_uid) { + return true; + } + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "ANY": + case "MSGS_HISTORY": + if (cboPermission.getValue() != processPermissionsData.op_action) { + return true; + } + break; + } + + return false; + }; + + isDirtyFormProcessPermission = function () { + $("input,select,textarea").blur(); + if (frmProcessPermissions.isVisible()) { + var result = frmProcessPermissions.isDirty(), message_window; + + if (isDirty2()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Permissions".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + cboGroupOrUser.html.find("input").val(""); + cboGroupOrUser.value = ""; + if (clickedClose) { + winGrdpnlProcessPermissions.close(); + } else { + refreshGridPanelInMainWindow(false); + } + + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if (cboGroupOrUser.html.find("input").val()) { + cboGroupOrUser.html.find("input").val(""); + } + cboGroupOrUser.containerList.hide(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + refreshGridPanelInMainWindow(false); + if (clickedClose) { + winGrdpnlProcessPermissions.close(); + } + } + } else { + winGrdpnlProcessPermissions.close(); + } + }; + refreshGridPanelInMainWindow = function (load) { + disableAllItems(); + PROCESS_PERMISSIONS_OPTION = ""; + PROCESS_PERMISSIONS_UID = ""; + winGrdpnlProcessPermissions.getItems()[0].setVisible(true); + winGrdpnlProcessPermissions.setTitle("Permissions".translate()); + load = load != null ? load : true; + if (load) { + processPermissionsGetRestProxy(grdpnlProcessPermissions); + } + }; + + processPermissionsGetRestProxy = function (grdpnl) { + var restProxy = new PMRestClient({ + endpoint: "process-permissions", + typeRequest: "get", + functionSuccess: function (xhr, response) { + listProcessPermissions = response; + grdpnl.setDataItems(listProcessPermissions); + grdpnl.sort('group_user', 'asc'); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); + }; + + processPermissionsPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "process-permission", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission saved successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + processPermissionGetRestProxy = function (processPermissionsUid) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response; + processPermissionsSetForm("PUT", data); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + processPermissionsPutRestProxy = function (processPermissionsUid, data) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission edited successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + cboTargetCboOriginTaskSetOptionsRestProxy = function (cboTargetTask, cboOriginTask) { + cboTargetTask.clearOptions(); + cboOriginTask.clearOptions(); + var restProxy = new PMRestClient({ + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboTargetTask.addOption({value: "", label: "All Tasks".translate()}); + cboOriginTask.addOption({value: "", label: "All Tasks".translate()}); + for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { + cboTargetTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + cboOriginTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); + }; + + cboDynaFormSetOptionsRestProxy = function (cboDynaForm) { + cboDynaForm.clearOptions(); + var restProxy = new PMRestClient({ + endpoint: "dynaforms", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboDynaForm.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + cboInputDocumentSetOptionsRestProxy = function (cboInputDocument) { + cboInputDocument.clearOptions(); + var restProxy = new PMRestClient({ + endpoint: "input-documents", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboInputDocument.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + cboOutputDocumentSetOptionsRestProxy = function (cboOutputDocument) { + var restProxy; + cboOutputDocument.clearOptions(); + restProxy = new PMRestClient({ + endpoint: "output-documents", + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, i; + cboOutputDocument.addOption({value: "", label: "All".translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + processPermissionsSetFormByType = function (type) { + cboPermission.removeOption("DELETE"); + cboPermission.removeOption("RESEND"); + + cboPermission.reset(); + cboOriginTask.setVisible(true); + cboParticipationRequired.setVisible(true); + cboStatusCase.setVisible(true); + cboDynaForm.setVisible(false); + cboInputDocument.setVisible(false); + cboOutputDocument.setVisible(false); + cboPermission.setVisible(false); + + switch (type) { + case "DYNAFORM": + cboDynaForm.setVisible(true); + cboPermission.setVisible(true); + break; + case "ATTACHMENT": + cboPermission.setVisible(true); + break; + case "INPUT": + cboPermission.addOption({value: "DELETE", label: "Delete".translate()}); + + cboInputDocument.setVisible(true); + cboPermission.setVisible(true); + break; + case "OUTPUT": + cboPermission.addOption({value: "DELETE", label: "Delete".translate()}); + + cboOutputDocument.setVisible(true); + cboPermission.setVisible(true); + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "MSGS_HISTORY": + cboPermission.addOption({value: "RESEND", label: "Resend".translate()}); + + cboPermission.setVisible(true); + break; + case "ANY": + cboPermission.setVisible(true); + break; + case "REASSIGN_MY_CASES": + cboOriginTask.setVisible(false); + cboParticipationRequired.setVisible(false); + cboStatusCase.setVisible(false); + break; + } + }; + + processPermissionsDeleteRestProxy = function (processPermissionsUid) { + var restProxy = new PMRestClient({ + endpoint: "process-permission/" + processPermissionsUid, + typeRequest: "remove", + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Permission deleted successfully'.translate(), + flashContainer: grdpnlProcessPermissions + }); + restProxy.executeRestClient(); + }; + + processPermissionsSetForm = function (option, data) { + cboGroupOrUser.hideMessageRequired(); + processPermissionsData = data; + PROCESS_PERMISSIONS_OPTION = option; + PROCESS_PERMISSIONS_UID = (typeof(processPermissionsData.op_uid) !== "undefined") ? processPermissionsData.op_uid : ""; + + disableAllItems(); + winGrdpnlProcessPermissions.showFooter(); + winGrdpnlProcessPermissions.getItems()[1].setVisible(true); + + loadDataFromServerToFields(); + + switch (option) { + case "POST": + winGrdpnlProcessPermissions.setTitle("Create permission".translate()); + frmProcessPermissions.reset(); + processPermissionsSetFormByType(cboType.getValue()); + + break; + case "PUT": + winGrdpnlProcessPermissions.setTitle("Edit permission".translate()); + cboStatusCase.setValue(processPermissionsData.op_case_status); + cboTargetTask.setValue(processPermissionsData.tas_uid); + + var endpoint; + if (processPermissionsData.op_user_relation == 1) { + endpoint = "users/" + processPermissionsData.usr_uid; + } + if (processPermissionsData.op_user_relation == 2) { + endpoint = "groups/" + processPermissionsData.usr_uid; + } + + if (endpoint) { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (response.hasOwnProperty("usr_uid")) { + cboGroupOrUser.set("value", response["usr_uid"]); + cboGroupOrUser.data = response; + cboGroupOrUser.html.find("input").val(response["usr_firstname"] + " " + response["usr_lastname"] + " " + "(" + response["usr_username"] + ")"); + } + if (response.hasOwnProperty("grp_uid")) { + cboGroupOrUser.set("value", response["grp_uid"]); + cboGroupOrUser.data = response; + cboGroupOrUser.html.find("input").val(response["grp_title"]); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint(endpoint); + restClient.executeRestClient(); + } + + cboParticipationRequired.setValue(processPermissionsData.op_participate); + cboType.setValue(processPermissionsData.op_obj_type); + cboOriginTask.setValue(processPermissionsData.op_task_source); + processPermissionsSetFormByType(processPermissionsData.op_obj_type); + switch (processPermissionsData.op_obj_type) { + case "ANY": + cboPermission.setValue(processPermissionsData.op_action); + break; + case "DYNAFORM": + cboDynaForm.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "ATTACHMENT": + cboPermission.setValue(processPermissionsData.op_action); + break; + case "INPUT": + cboInputDocument.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "OUTPUT": + cboOutputDocument.setValue(processPermissionsData.op_obj_uid); + cboPermission.setValue(processPermissionsData.op_action); + break; + case "CASES_NOTES": + case "SUMMARY_FORM": + break; + case "MSGS_HISTORY": + cboPermission.setValue(processPermissionsData.op_action); + break; + } + break; + } + frmProcessPermissions.setFocus(); + }; + + cboStatusCase = new PMUI.field.DropDownListField({ + id: "cboStatusCase", + name: "cboStatusCase", + controlsWidth: "120px", + label: "Case Status".translate(), + value: "ALL", + options: [ + { + value: "ALL", + label: "All".translate() + }, + { + value: "DRAFT", + label: "DRAFT".translate() + }, + { + value: "TO_DO", + label: "TO DO".translate() + }, + { + value: "PAUSED", + label: "PAUSED".translate() + }, + { + value: "COMPLETED", + label: "COMPLETED".translate() + } + ] + }); + + cboTargetTask = new PMUI.field.DropDownListField({ + id: "cboTargetTask", + name: "cboTargetTask", + controlsWidth: "300px", + label: "Target Task".translate(), + options: null + }); + cboGroupOrUser = new SuggestField({ + label: "Group or User".translate(), + id: "cboGroupOrUser", + name: "cboGroupOrUser", + placeholder: "suggest users and groups", + width: 500, + required: true, + separatingText: ["Groups", "Users"], + dynamicLoad: { + data: [ + { + key: "grp_uid", + label: ["grp_title"] + }, + { + key: "usr_uid", + label: ["usr_firstname", "usr_lastname", "(", "usr_username", ")"] + } + ], + keys: { + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endpoints: [ + { + method: "GET", + url: 'groups' + }, { + method: "GET", + url: 'users' + } + ] + } + } + }); + + cboOriginTask = new PMUI.field.DropDownListField({ + id: "cboOriginTask", + name: "cboOriginTask", + controlsWidth: "300px", + label: "Origin Task".translate(), + options: null + }); + + cboParticipationRequired = new PMUI.field.DropDownListField({ + id: "cboParticipationRequired", + name: "cboParticipationRequired", + controlsWidth: "70px", + label: "Participation required?".translate(), + value: "0", + options: [ + { + value: "0", + label: "No".translate() + }, + { + value: "1", + label: "Yes".translate() + } + ] + }); + notification = new PMUI.field.TextAnnotationField({ + id: "requiredMessage", + name: "Message", + textType: PMUI.field.TextAnnotationField.TEXT_TYPES.HTML, + text: notificationText, + text_Align: "center" + }); + optionsType = [ + { + value: "ANY", + label: "All".translate() + }, + { + value: "DYNAFORM", + label: "Dynaform".translate() + }, + { + value: "ATTACHMENT", + label: "Attachment".translate() + }, + { + value: "INPUT", + label: "Input Document".translate() + }, + { + value: "OUTPUT", + label: "Output Document".translate() + }, + { + value: "CASES_NOTES", + label: "Cases Notes".translate() + }, + { + value: "MSGS_HISTORY", + label: "Messages History".translate() + }, + { + value: "REASSIGN_MY_CASES", + label: "Reassign my cases".translate() + } + ]; + + if (enterprise == "1") { + optionsType.push({value: "SUMMARY_FORM", label: "Summary Form".translate()}); + } + // sorting the optionsType + optionsType.sort(function(a, b) { + return (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0); + }); + + cboType = new PMUI.field.DropDownListField({ + id: "cboType", + name: "cboType", + controlsWidth: "180px", + label: "Type".translate(), + value: "ANY", + options: optionsType, + onChange: function (newValue, prevValue) { + processPermissionsSetFormByType(cboType.getValue()); + } + }); + + cboDynaForm = new PMUI.field.DropDownListField({ + id: "cboDynaForm", + name: "cboDynaForm", + controlsWidth: "300px", + label: "DynaForm".translate(), + options: [], + visible: false + }); + + cboInputDocument = new PMUI.field.DropDownListField({ + id: "cboInputDocument", + name: "cboInputDocument", + controlsWidth: "300px", + label: "Input Document".translate(), + options: [], + visible: false + }); + + cboOutputDocument = new PMUI.field.DropDownListField({ + id: "cboOutputDocument", + name: "cboOutputDocument", + controlsWidth: "300px", + label: "Output Document".translate(), + options: [], + visible: false + }); + + cboPermission = new PMUI.field.DropDownListField({ + id: "cboPermission", + name: "cboPermission", + controlsWidth: "100px", + label: "Permission".translate(), + value: "VIEW", + options: [ + { + value: "VIEW", + label: "View".translate() + }, + { + value: "BLOCK", + label: "Block".translate() + } + ], + visible: true + }); + + frmProcessPermissions = new PMUI.form.Form({ + id: "frmProcessPermissions", + + title: "", + width: "890px", + items: [ + cboType, + cboStatusCase, + cboTargetTask, + cboOriginTask, + cboParticipationRequired, + cboDynaForm, + cboInputDocument, + cboOutputDocument, + cboPermission + ] + }); + + btnCreate = new PMUI.ui.Button({ + id: "btnCreate", + text: "Create".translate(), + height: "36px", + width: 100, + style: { + cssClasses: [ + "mafe-button-create" + ] + }, + + handler: function () { + frmProcessPermissions.reset(); + processPermissionsDataIni = {}; + + processPermissionsDataIni.op_case_status = "ALL"; + processPermissionsDataIni.tas_uid = ""; + processPermissionsDataIni.usr_uid = ""; + processPermissionsDataIni.op_task_source = ""; + processPermissionsDataIni.op_participate = "0"; + processPermissionsDataIni.op_obj_type = "ANY"; + processPermissionsDataIni.op_obj_uid = ""; + processPermissionsDataIni.op_action = "VIEW"; + + processPermissionsSetForm("POST", {}); + } + }); + + grdpnlProcessPermissions = new PMUI.grid.GridPanel({ + id: "grdpnlProcessPermissions", + filterPlaceholder: "Search ...".translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + width: "96%", + tableContainerHeight: 374, + //height: DEFAULT_WINDOW_HEIGHT - 60, + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterable: true, + columns: [ + { + columnData: "group_user", + title: "Group or User".translate(), + alignmentCell: 'left', + width: "190px", + sortable: true + }, + { + columnData: "op_obj_type", + title: "Type".translate(), + alignmentCell: 'left', + width: "100px", + sortable: true + }, + { + columnData: "participated", + title: "Participation".translate(), + alignmentCell: 'left', + width: "115px", + sortable: true + }, + { + columnData: "object", + title: "Object".translate(), + alignmentCell: 'left', + width: "158px", + sortable: true + }, + { + columnData: "op_action", + title: "Permission".translate(), + alignmentCell: 'left', + width: "100px", + sortable: true + }, + { + columnData: "op_case_status", + title: "Status".translate(), + alignmentCell: 'left', + width: "70px", + sortable: true + }, + { + id: 'grdpnlProcessPermissionsButtonEdit', + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: "70px", + buttonStyle: { + cssClasses: [ + "mafe-button-edit" + ] + }, + + onButtonClick: function (row, grid) { + var data; + frmProcessPermissions.reset(); + data = row.getData(); + processPermissionGetRestProxy(data.op_uid); + } + }, + { + id: 'grdpnlProcessPermissionsButtonDelete', + dataType: "button", + title: "", + buttonLabel: "Delete".translate(), + width: "80px", + buttonStyle: { + cssClasses: [ + "mafe-button-delete" + ] + }, + + onButtonClick: function (row, grid) { + var data = row.getData(), msgWarning; + msgWarning = new PMUI.ui.MessageWindow({ + id: "msgWarning", + windowMessageType: 'warning', + width: 490, + title: "Permissions".translate(), + message: "Do you want to delete this permission?".translate(), + footerItems: [ + { + id: 'msgWarningButtonNo', + text: "No".translate(), + handler: function () { + msgWarning.close(); + }, + buttonType: "error" + }, + { + id: 'msgWarningButtonYes', + text: "Yes".translate(), + handler: function () { + processPermissionsDeleteRestProxy(data.op_uid); + msgWarning.close(); + }, + buttonType: "success" + } + ] + }); + + msgWarning.open(); + msgWarning.dom.titleContainer.style.height = '17px'; + msgWarning.showFooter(); + } + } + ], + dataItems: null + }); + + winGrdpnlProcessPermissions = new PMUI.ui.Window({ + id: "winGrdpnlProcessPermissions", + title: "Permissions".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + buttonPanelPosition: "bottom", + footerAlign: "right", + onBeforeClose: function () { + clickedClose = true; + isDirtyFormProcessPermission(); + }, + footerItems: [ + { + id: "btnCancel", + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + clickedClose = false; + isDirtyFormProcessPermission(); + } + }, + { + id: "btnSave", + text: "Save".translate(), + buttonType: "success", + handler: function () { + var cboGroupOrUserValue = "", groupOrUser, data; + + if (frmProcessPermissions.isValid() && cboGroupOrUser.isValid()) { + if (cboGroupOrUser.data) { + if (cboGroupOrUser.data.hasOwnProperty("usr_uid")) { + cboGroupOrUserValue = "1|" + cboGroupOrUser.get("value"); + } + if (cboGroupOrUser.data.hasOwnProperty("grp_uid")) { + cboGroupOrUserValue = "2|" + cboGroupOrUser.get("value"); + } + } else { + cboGroupOrUserValue = ""; + } + groupOrUser = cboGroupOrUserValue.split("|"); + + data = { + op_case_status: cboStatusCase.getValue(), + tas_uid: cboTargetTask.getValue() === '0' ? '' : cboTargetTask.getValue(), + op_user_relation: groupOrUser[0], + usr_uid: groupOrUser[1], + op_task_source: cboOriginTask.getValue() === '0' ? '' : cboOriginTask.getValue(), + op_participate: cboParticipationRequired.getValue() + }; + + switch (cboType.getValue()) { + case "DYNAFORM": + data["op_obj_type"] = cboType.getValue(); + data["dynaforms"] = cboDynaForm.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "INPUT": + data["op_obj_type"] = cboType.getValue(); + data["inputs"] = cboInputDocument.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "OUTPUT": + data["op_obj_type"] = cboType.getValue(); + data["outputs"] = cboOutputDocument.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "CASES_NOTES": + data["op_obj_type"] = cboType.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + case "REASSIGN_MY_CASES": + data = {}; + data["op_user_relation"] = groupOrUser[0]; + data["usr_uid"] = groupOrUser[1]; + data["tas_uid"] = cboTargetTask.getValue() === '0' ? '' : cboTargetTask.getValue(); + data["op_obj_type"] = cboType.getValue(); + break; + default: + data["op_obj_type"] = cboType.getValue(); + data["op_action"] = cboPermission.getValue(); + break; + } + switch (PROCESS_PERMISSIONS_OPTION) { + case "POST": + processPermissionsPostRestProxy(data); + break; + case "PUT": + processPermissionsPutRestProxy(PROCESS_PERMISSIONS_UID, data); + break; + } + } else { + cboGroupOrUser.showMessageRequired(); + frmProcessPermissions.addItem(notification) + } + + cboGroupOrUser.html.find("input").val(""); + cboGroupOrUser.value = ""; + } + } + ] + }); + + winGrdpnlProcessPermissions.addItem(grdpnlProcessPermissions); + winGrdpnlProcessPermissions.addItem(frmProcessPermissions); + + refreshGridPanelInMainWindow(); + if (typeof listProcessPermissions !== "undefined") { + winGrdpnlProcessPermissions.open(); + $(cboGroupOrUser.createHTML()).insertBefore(cboType.html); + + + cboGroupOrUser.html.find("input").val(""); + jQuery(grdpnlProcessPermissions.html).css({ + margin: "2px" + }); + winGrdpnlProcessPermissions.body.style.height = "auto"; + $('#grdpnlProcessPermissions .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + winGrdpnlProcessPermissions.defineEvents(); + applyStyleWindowForm(winGrdpnlProcessPermissions); + + grdpnlProcessPermissions.dom.toolbar.appendChild(btnCreate.getHTML()); + btnCreate.defineEvents(); + disableAllItems(); + refreshGridPanelInMainWindow(); + } + }; + + PMDesigner.processPermissions.create = function () { + PMDesigner.processPermissions(); + + frmProcessPermissions.reset(); + processPermissionsDataIni = {}; + + processPermissionsDataIni.op_case_status = "ALL"; + processPermissionsDataIni.tas_uid = ""; + processPermissionsDataIni.usr_uid = ""; + processPermissionsDataIni.op_task_source = ""; + processPermissionsDataIni.op_participate = "0"; + processPermissionsDataIni.op_obj_type = "ANY"; + processPermissionsDataIni.op_obj_uid = ""; + processPermissionsDataIni.op_action = "VIEW"; + + processPermissionsSetForm("POST", {}); + }; + }() +); + +(function () { + var winHtmlShow, loadValuesStartMessage; + + PMDesigner.startMessage = function (element) { + var winGrdpnlStartMessage, + btnNew, + cboUser, + cboDynaForm, + btnGenerateStartMessagePage, + frmDataStartMessage, + frmHtml, + winFrmDataStartMessage, + restProxy, + disableAllItems, + winFrmStartMessageShow, + updateStartMessage, + loadDataDynaform, + loadDataUsers, + loadDataForm, + listUsers = [], + cboMethod, + listDynaforms = [], + dataForm = [], + enableGenerateWebEntry, + btnSaveStartMessagePage, + btnStartMessageCancel, + btnClose, + startMessage = element; + + disableAllItems = function () { + winGrdpnlStartMessage.getItems()[0].setVisible(false); + winGrdpnlStartMessage.getItems()[1].setVisible(false); + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(false); + winGrdpnlStartMessage.hideFooter(); + }; + + winFrmStartMessageShow = function () { + disableAllItems(); + frmDataStartMessage.reset(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.getItems()[0].setVisible(true); + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + loadDataUsers(); + loadDataDynaform(); + loadDataForm(); + frmDataStartMessage.setFocus(); + }; + + winHtmlShow = function (msgHtml) { + if (typeof msgHtml == 'undefined') { + msgHtml = dataForm.we_data; + if (dataForm.we_method == "WS") { + window.open(msgHtml); + winGrdpnlStartMessage.close(); + return false; + } + } + disableAllItems(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.getItems()[1].setVisible(true); + winGrdpnlStartMessage.getItems()[1].setWidth(925); + winGrdpnlStartMessage.getItems()[1].setHeight(440); + winGrdpnlStartMessage.getItems()[1].hideHeader(); + frmHtml.getFields()[0].setHeight(396); + frmHtml.getItems()[0].setValue(msgHtml); + frmHtml.panel.style.addProperties({'box-sizing': 'initial'}); + frmHtml.style.addProperties({marginLeft: '16px'}); + frmHtml.setFocus(); + return true; + }; + + loadValuesStartMessage = function (flag) { + var viewFlagForm, + restClient, + response; + listUsers = []; + listDynaforms = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startMessage.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: "activity/" + startMessage.ports.get(0).connection.flo_element_dest + "/steps", + method: 'GET' + }, { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + listDynaforms = response[1].response; + dataForm = response[2].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + if (flag) { + viewFlagForm = false; + if (typeof dataForm == 'object' && dataForm.we_data != null) { + viewFlagForm = true; + } + response = [listUsers.length, listDynaforms.length, viewFlagForm]; + return response; + } + return true; + }; + + updateStartMessage = function (data) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: "web-entry/" + startMessage.evn_uid, + method: 'PUT', + data: data + }, + { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataForm = response[1].response; + if (data.we_method == "HTML") { + winHtmlShow(response.we_data); + } + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ["There are problems updating the Web Entry, please try again.".translate()], + messageSuccess: ['Web Entry updated successfully'.translate()], + flashContainer: frmDataStartMessage + }); + restClient.executeRestClient(); + }; + + loadDataDynaform = function () { + var i; + cboDynaForm.clearOptions(); + for (i = 0; i <= listDynaforms.length - 1; i++) { + if (listDynaforms[i].step_type_obj == "DYNAFORM") { + cboDynaForm.addOption({ + value: listDynaforms[i].step_uid_obj, + label: listDynaforms[i].obj_title + }); + } + } + }; + + loadDataUsers = function () { + var i; + cboUser.clearOptions(); + for (i = 0; i <= listUsers.length - 1; i++) { + cboUser.addOption({ + value: listUsers[i].aas_uid, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + cboUser.setValue(dataForm.usr_uid); + cboDynaForm.setValue(dataForm.dyn_uid); + cboMethod.setValue(dataForm.we_method); + }; + + enableGenerateWebEntry = function () { + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + btnClose.setVisible(false); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(true); + }; + cboUser = new PMUI.field.DropDownListField({ + id: "cboUser", + name: "cboUser", + label: "User".translate(), + required: true, + options: null, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboDynaForm = new PMUI.field.DropDownListField({ + id: "cboDynaForm", + name: "cboDynaForm", + label: "Initial Dynaform".translate(), + options: null, + required: true, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboMethod = new PMUI.field.DropDownListField({ + id: "cboMethod", + name: "cboMethod", + label: "Method".translate(), + value: "WS", + options: [ + { + value: "WS", + label: "PHP pages with Web Services".translate() + }, + { + value: "HTML", + label: "Single HTML".translate() + } + ], + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + btnGenerateStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Generate Web Entry Page".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + btnSaveStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Save".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + + frmDataStartMessage = new PMUI.form.Form({ + id: "frmDataStartMessage", + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + items: [ + cboUser, + cboDynaForm, + cboMethod + ], + visibleHeader: false + }); + + btnClose = new PMUI.ui.Button({ + id: "btnClose", + text: "Close".translate(), + handler: function () { + winGrdpnlStartMessage.close(); + }, + buttonType: 'success', + height: 31 + }); + + btnStartMessageCancel = new PMUI.ui.Button({ + id: "btnStartMessageCancel", + text: "Cancel".translate(), + handler: function () { + var message_window; + if (frmDataStartMessage.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + id: "cancelMessageStartTimer", + title: "Start Message Event".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + bodyHeight: 'auto', + width: 490, + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + winGrdpnlStartMessage.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + frmDataStartMessage.reset(); + winGrdpnlStartMessage.close(); + } + } + }); + + frmHtml = new PMUI.form.Form({ + id: "frmHtml", + title: "", + width: DEFAULT_WINDOW_WIDTH - 43, + items: [ + { + id: "txtHtml", + name: "txtHtml", + pmType: "textarea", + valueType: "string", + rows: 400, + value: '', + controlsWidth: DEFAULT_WINDOW_WIDTH - 50, + labelVisible: false, + style: {cssClasses: ['mafe-textarea-resize']} + } + ] + }); + + winGrdpnlStartMessage = new PMUI.ui.Window({ + id: "winGrdpnlStartMessage", + title: "Start Message Event".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: "top", + buttons: [btnSaveStartMessagePage, {pmType: 'label', text: 'or'}, btnStartMessageCancel, btnClose] + }); + + winGrdpnlStartMessage.addItem(frmDataStartMessage); + + openForm = function () { + winGrdpnlStartMessage.open(); + winGrdpnlStartMessage.defineEvents(); + applyStyleWindowForm(winGrdpnlStartMessage); + winGrdpnlStartMessage.footer.html.style.textAlign = 'right'; + winFrmStartMessageShow(); + } + }; + + PMDesigner.startMessage.openForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.viewForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.validate = function (starMessageEvent) { + if (starMessageEvent.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 4000, 5); + return [false, false]; + } + PMDesigner.startMessage(starMessageEvent); + response = loadValuesStartMessage(true); + if (response[0] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 4000); + return [false, false]; + } + if (response[1] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned Dynaforms'.translate(), document.body, 'info', 4000); + return [false, false]; + } + return [true, response[2]]; + } +}()); + +(function () { + var windowPropSub; + + PMDesigner.propertiesSubProcess = function (activity) { + var typeVariables = ['@@', '@#', '@=', '@&'], + restClient, + isDirtyFormSubProcess, + getSubProcess, + formVarTexOriginOut, + updateSubProcess, + formVarTexOriginIn, + loadDropProcess, + formVarTexTargetOut, + formVarTexTargetIn, + windowPropertiesSub, + formProperties, + sepInputs, + gridVariablesOut, + gridVariablesIn, + formVariablesPanelOut, + formVariablesPanelIn, + validateVariable, + formVarButtonAddOut, + formVarButtonAddIn, + labelVariablesOut, + labelVariablesIn, + loadDataServer, + loadActivity, + isDirty = false; + + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i += 1) { + if (response[i].prj_uid != PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + isDirtyFormSubProcess = function () { + var message_window; + if (formProperties.isDirty() || isDirty) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: "cancelSaveSubprocPropertiesWin", + title: "Sub-process Properties".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + windowPropertiesSub.close(); + } + }; + getSubProcess = function () { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var yout, + oout, + jout, + itemsOut, + i, + xin, + yin, + oin, + jin, + dout, + din, + itemsIn, + xout; + formProperties.getField('out_doc_title').setValue(response.spr_name); + formProperties.getField('out_doc_process').setValue(response.spr_pro); + formProperties.getField('out_doc_type').setValue(response.spr_synchronous); + + if (response.spr_variables_out != false) { + xout = JSON.stringify(response.spr_variables_out); + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + + itemsOut = []; + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); + } + gridVariablesOut.setDataItems(itemsOut); + + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + } + + if (response.spr_variables_in != false && response.spr_variables_in != undefined) { + xin = JSON.stringify(response.spr_variables_in); + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + + itemsIn = []; + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } + gridVariablesIn.setDataItems(itemsIn); + } + + if (response.spr_synchronous == "1") { + gridVariablesIn.setVisible(true); + formVariablesPanelIn.setVisible(true); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + updateSubProcess = function (data) { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + var name = formProperties.getData().out_doc_title; + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + formVarTexOriginOut = new CriteriaField({ + id: 'idformVarTexOriginOut', + pmType: "text", + name: 'nmformVarTexOriginOut', + placeholder: 'Origin'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + formVarTexOriginIn = new CriteriaField({ + id: 'idformVarTexOriginIn', + pmType: "text", + name: 'nmformVarTexOriginIn', + placeholder: 'Select Origin Process'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + formVarTexTargetOut = new CriteriaField({ + id: 'idformVarTexTargetOut', + pmType: "text", + name: 'nmformVarTexTargetOut', + placeholder: 'Select Target Process'.translate(), + labelVisible: false, + controlsWidth: 150, + required: true + }); + + formVarTexTargetIn = new CriteriaField({ + id: 'idformVarTexTargetIn', + pmType: "text", + name: 'nmformVarTexTargetIn', + placeholder: 'Target'.translate(), + labelVisible: false, + controlsWidth: 150 + }); + + windowPropertiesSub = new PMUI.ui.Window({ + id: 'propSubWindow', + title: "Sub-process Properties".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + bodyHeight: '465px', + bodyWidth: '900px', + onBeforeClose: function () { + isDirtyFormSubProcess(); + }, + buttons: [ + { + id: 'propSubButtonClose', + text: "Close".translate(), + buttonType: 'error', + handler: function () { + isDirtyFormSubProcess(); + } + }, + { + id: 'propSubButtonSave', + text: "Save".translate(), + buttonType: 'success', + handler: function () { + if (!formProperties.isValid()) { + return; + } + var propertiesData = formProperties.getData(); + var variablesOutData = gridVariablesOut.getData(); + var variablesOut = {}; + if (variablesOutData.length > "0") { + for (i = 0; i < variablesOutData.length; i += 1) { + variablesOut[variablesOutData[i].origin] = variablesOutData[i].target; + } + } + var variablesIn = {}; + if (propertiesData.out_doc_type == "1") { + var variablesInData = gridVariablesIn.getData(); + if (variablesInData.length > "0") { + for (j = 0; j < variablesInData.length; j += 1) { + variablesIn[variablesInData[j].origin] = variablesInData[j].target; + } + } + } + + var dataToSend = { + spr_pro: propertiesData.out_doc_process, + spr_tas: propertiesData.spr_tas, + spr_name: propertiesData.out_doc_title, + spr_synchronous: propertiesData.out_doc_type, + spr_variables_out: variablesOut, + spr_variables_in: variablesIn + }; + + updateSubProcess(dataToSend); + } + } + ], + buttonPanelPosition: 'bottom', + buttonsPosition: 'right' + }); + + formProperties = new PMUI.form.Form({ + id: 'propSubForm', + title: "", + fieldset: true, + visibleHeader: false, + width: 926, + height: 'auto', + items: [ + { + id: 'propSubFormTitle', + pmType: "text", + name: 'out_doc_title', + label: "Sub-Process name".translate(), + required: true, + controlsWidth: 300 + }, + { + id: 'propSubFormProcess', + pmType: "dropdown", + name: 'out_doc_process', + label: "Process".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + if (a.trim().length !== 0) { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + formVarTexTargetOut.controls[0].setPlaceholder("Target"); + formVarTexOriginIn.controls[0].setPlaceholder("Origin"); + } else { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } + formVarTexTargetOut.setProcess(a); + formVarTexOriginIn.setProcess(a); + loadActivity(a); + } + }, + { + id: 'propSubFormActivity', + pmType: "dropdown", + name: 'spr_tas', + label: "Starting activity".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select starting activity -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + } + }, + { + id: 'propSubFormType', + pmType: "dropdown", + name: 'out_doc_type', + label: "Type".translate(), + controlsWidth: 150, + required: true, + options: [ + { + label: "Asynchronous".translate(), + value: "0" + }, + { + label: "Synchronous".translate(), + value: "1" + } + ], + value: "0", + onChange: function (a, b) { + isDirty = true; + } + } + ], + onChange: function (newValue, prevValue) { + switch (newValue.value) { + case "1" : + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + break; + case "0": + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + windowPropertiesSub.getItems()[4].setVisible(false); + break; + default : + break; + } + } + }); + + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + + formProperties.addItem(sepInputs); + + gridVariablesOut = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesOut', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + style: { + cssClasses: ["mafe-gridPanel"] + }, + columns: [ + { + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesOutButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + } + + } + ] + }); + + gridVariablesIn = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesIn', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + columns: [ + { + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesInButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + } + } + ] + }); + + formVariablesPanelOut = new PMUI.core.Panel({ + id: "formVariablesPanelOut", + layout: "hbox", + fieldset: true, + width: DEFAULT_WINDOW_WIDTH - 70 + }); + + formVariablesPanelIn = new PMUI.core.Panel({ + id: "formVariablesPanelIn", + layout: "hbox", + fieldset: true, + legend: "Variables In".translate(), + width: DEFAULT_WINDOW_WIDTH - 70 + }); + + validateVariable = function (field) { + var value; + field.controls[0].style.removeClasses(['error']) + value = field.getValue(); + if (value == '') { + PMDesigner.msgWinWarning('Please insert variable before adding to the list.'.translate()); + field.controls[0].style.addClasses(['error']) + return false; + } + if (typeVariables.indexOf(String(value.substring(0, 2))) != -1) { + return true; + } + PMDesigner.msgWinWarning("The value introduced doesn\'t have the correct format with a vallid prefix (@@, @#, @=, @&)".translate()); + field.controls[0].style.addClasses(['error']) + return false; + }; + + formVarButtonAddOut = new PMUI.ui.Button({ + id: 'formVarButtonAddOut', + text: 'Add'.translate(), + width: 60, + visible: false, + buttonType: "success", + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px" + } + }, + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginOut) && validateVariable(formVarTexTargetOut)) { + a = formVarTexOriginOut.getValue(); + b = formVarTexTargetOut.getValue(); + gridVariablesOut.addDataItem({origin: a, target: b}); + formVarTexOriginOut.setValue(""); + formVarTexTargetOut.setValue(""); + isDirty = true; + + gridOut = document.getElementById("propSubGridVariablesOut").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); + + formVarButtonAddIn = new PMUI.ui.Button({ + id: 'formVarButtonAddIn', + text: 'Add'.translate(), + width: 60, + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px", + } + }, + buttonType: 'success', + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginIn) && validateVariable(formVarTexTargetIn)) { + a = formVarTexOriginIn.getValue(); + b = formVarTexTargetIn.getValue(); + gridVariablesIn.addDataItem({origin: a, target: b}); + formVarTexOriginIn.setValue(""); + formVarTexTargetIn.setValue(""); + isDirty = true; + + gridOut = document.getElementById("propSubGridVariablesIn").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); + + labelVariablesOut = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables Out'.translate() + }); + + labelVariablesIn = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables In'.translate() + }); + + loadDropProcess = function () { + formProperties.getField('out_doc_process').clearOptions(); + formProperties.getField('out_doc_process').addOption({ + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }); + }; + loadDataServer = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'projects', + method: 'GET' + }, + { + url: 'project/' + PMDesigner.project.id + '/subprocess/' + activity.act_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var dt, + itemsOut, + yout, + oout, + jout, + dout, + xin, + yin, + oin, + jin, + din, + itemsIn, + xout; + + //projects + dt = response[0].response; + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].prj_uid !== PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: dt[i].prj_name, + value: dt[i].prj_uid + }); + } + } + //subprocess + dt = response[1].response; + formProperties.getField('out_doc_title').setValue(dt.spr_name); + formProperties.getField('out_doc_process').setValue(dt.spr_pro === '0' ? '' : dt.spr_pro); + formProperties.getField('out_doc_type').setValue(dt.spr_synchronous); + + if (dt.spr_variables_out !== false) { //Asynchronous + xout = JSON.stringify(dt.spr_variables_out); + itemsOut = []; + if (xout != "[]") { + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); + } + } + gridVariablesOut.setDataItems(itemsOut); + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + } + + if (dt.spr_variables_in !== false && dt.spr_variables_in !== undefined) { //Synchronous + xin = JSON.stringify(dt.spr_variables_in); + itemsIn = []; + if (xin != "[]") { + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } + } + gridVariablesIn.setDataItems(itemsIn); + } + + if (dt.spr_synchronous === "1") { + gridVariablesIn.setVisible(true); + formVariablesPanelIn.setVisible(true); + } + if (formProperties.getField('out_doc_process').getValue() !== '') { + loadActivity(formProperties.getField('out_doc_process').getValue()); + } + formProperties.getField('spr_tas').setValue(dt.spr_tas === '0' ? '' : dt.spr_tas); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadActivity = function (value) { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + value + '/starting-tasks', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var dropdown, + i, + dt = response[0].response; + dt = dt.sort(function (a, b) { + return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); + }); + dropdown = formProperties.getField('spr_tas'); + dropdown.clearOptions(); + dropdown.addOption({ + value: '', + label: '- Select starting activity -'.translate() + }); + for (i = 0; i < dt.length; i += 1) { + dropdown.addOption({ + value: dt[i].act_uid, + label: dt[i].act_name + }); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + + formVariablesPanelOut.addItem(formVarTexOriginOut); + formVariablesPanelOut.addItem(formVarTexTargetOut); + formVariablesPanelOut.addItem(formVarButtonAddOut); + + formVariablesPanelIn.addItem(formVarTexOriginIn); + formVariablesPanelIn.addItem(formVarTexTargetIn); + formVariablesPanelIn.addItem(formVarButtonAddIn); + + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + + windowPropertiesSub.addItem(formProperties); + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables Out'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '-15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' + } + }, + display: 'block' + })); + windowPropertiesSub.addItem(formVariablesPanelOut); + windowPropertiesSub.addItem(gridVariablesOut); + + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables In'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' + } + }, + display: 'block', + visible: false + })); + + windowPropertiesSub.addItem(formVariablesPanelIn); + windowPropertiesSub.addItem(gridVariablesIn); + + loadDropProcess(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + loadDataServer(); + + if (formProperties.getItems()[1].getValue() != "0") { + formVarTexTargetOut.setProcess(formProperties.getItems()[1].getValue()); + formVarTexOriginIn.setProcess(formProperties.getItems()[1].getValue()); + } + windowPropertiesSub.open(); + if (formProperties.getField('out_doc_process').getValue().trim().length === 0) { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } else { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + } + windowPropertiesSub.showFooter(); + applyStyleWindowForm(windowPropertiesSub); + formVariablesPanelIn.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelIn.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.style.addProperties({marginLeft: '45px'}); + gridVariablesOut.style.addProperties({marginLeft: '45px'}); + if (formVariablesPanelIn.visible == true) { + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + } + + formVariablesPanelOut.style.addProperties({width: '870px'}); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + windowPropertiesSub.defineEvents(); + gridVariablesOut.html.children[0].style.display = "none"; + gridVariablesIn.html.children[0].style.display = "none"; + formProperties.getField('out_doc_title').setFocus(); + formVarButtonAddOut.setWidth(80); + formVarButtonAddOut.setVisible(true); + + }; +}()); +if (typeof(consolidated) == 'undefined') { + consolidated = '0'; +} +PMDesigner.activityProperties = function (activity) { + switch (activity.getActivityType()) { + case "SUB_PROCESS": + PMDesigner.propertiesSubProcess(activity); + break; + case "TASK": + if (activity.getTaskType() === "SCRIPTTASK") { + PMDesigner.scriptTaskProperties(activity); + } else { + PMDesigner.taskProperties(activity); + } + break; + } +}; + +PMDesigner.taskProperties = function (activity) { + var formDefinitions, + featuresForms = [], + propertiesTabs, + formCaseLabels, + dataProperties, + formTimingControl, + configurationForms, + customGrid, + formNotifications, + buttonFieldCancel, + buttonFieldAdd, + abeForm, + MobilePanel, + enableTaskMobile, + routeCaseMobile, + abeMainPanel, + abeAddOption, + abeTemplates, + abeDynaforms, + abeReceiverAccount, + abeEmailAcount, + abeFields, + warningChanges, + windowProperties, + processDataProperties, + i, + editRow = null, + arrayTrue = '["TRUE"]', + arrayFalse = '["FALSE"]', + stringTrue = "TRUE", + stringFalse = "FALSE", + defaultServerlabel = "Mail (PHP)".translate(); + + configurationForms = [ + { + id: 'windowPropertiesTabPanelDefinitions', + icon: '', + title: 'Definitions'.translate(), + panel: formDefinitions = new PMUI.form.Form({ + id: 'formDefinitions', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formDefinitionsUID', + pmType: 'text', + name: 'UID', + valueType: 'string', + label: 'UID'.translate(), + controlsWidth: 300 + }, { + id: 'formDefinitionsTitle', + pmType: 'text', + name: 'tas_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300 + }, { + id: 'formDefinitionsDescription', + pmType: 'textarea', + name: 'tas_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: 300, + style: {cssClasses: ['mafe-textarea-resize']} + }, new CriteriaField({ + id: 'formDefinitionsVariable', + pmType: 'text', + name: 'tas_priority_variable', + valueType: 'string', + label: 'Variable for Case priority'.translate(), + controlsWidth: 300 + }), { + id: 'formDefinitionsRouting', + pmType: 'dropdown', + name: 'tas_derivation_screen_tpl', + valueType: 'string', + label: 'Routing Screen Template'.translate(), + controlsWidth: 150, + style: { + cssProperties: { + float: "left" + } + } + } + ] + }) + }, + { + id: 'windowPropertiesTabPanelCaseLabels', + icon: '', + title: 'Case Labels'.translate(), + panel: formCaseLabels = new PMUI.form.Form({ + id: 'formCaseLabels', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [new CriteriaField({ + id: 'formCaseLabelsTitle', + pmType: 'text', + name: 'tas_def_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + controlsWidth: DEFAULT_WINDOW_WIDTH - 527 + }), new CriteriaField({ + id: 'formCaseLabelsDescription', + pmType: 'textarea', + name: 'tas_def_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: DEFAULT_WINDOW_WIDTH - 527, + renderType: 'textarea' + }) + ] + }) + }, + { + id: 'windowPropertiesTabPanelTimingControl', + icon: '', + title: 'Timing Control'.translate(), + panel: formTimingControl = new PMUI.form.Form({ + id: 'formTimingControl', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formTimingControlFly', + pmType: 'checkbox', + name: 'tas_transfer_fly', + labelVisible: false, + options: [ + { + id: 'formTimingControlOption', + label: 'Allow users to change the task duration in runtime'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeTimingControl(this.controls[0].selected); + } + }, { + id: 'formTimingMainPanel', + pmType: 'panel', + items: [ + { + id: 'formTimingControlTask', + pmType: 'text', + name: 'tas_duration', + valueType: 'string', + label: 'Task duration'.translate(), + required: true, + maxLength: 3, + controlsWidth: 200, + validators: [ + { + pmType: "regexp", + criteria: /^\d*$/, + errorMessage: "Please enter a positive integer value".translate() + } + ] + }, + { + id: 'formTimingControlAverage', + pmType: 'text', + name: 'tas_average', + valueType: 'string', + label: 'Average'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlSdv', + pmType: 'text', + name: 'tas_sdv', + valueType: 'string', + label: 'SDV'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlTime', + pmType: 'dropdown', + name: 'tas_timeunit', + label: 'Time unit'.translate(), + controlsWidth: 100, + options: [{ + id: 'formTimingControlTime1', + label: 'Hours'.translate(), + value: 'HOURS' + }, { + id: 'formTimingControlTime2', + label: 'Days'.translate(), + value: 'DAYS' + }, { + id: 'formTimingControlTime3', + label: 'Minutes'.translate(), + value: 'MINUTES' + } + ] + }, { + id: 'formTimingControlCount', + pmType: 'dropdown', + name: 'tas_type_day', + label: 'Count days by'.translate(), + controlsWidth: 150, + options: [{ + id: 'formTimingControlCount1', + label: 'Work Days'.translate(), + value: 1 + }, { + id: 'formTimingControlCount2', + label: 'Calendar Days'.translate(), + value: 2 + } + ] + }, { + id: 'formTimingControlCalendar', + pmType: 'dropdown', + name: 'tas_calendar', + label: 'Calendar'.translate(), + options: [], + controlsWidth: 150 + } + ] + } + ] + }) + }, + { + id: 'windowPropertiesTabPanelNotifications', + icon: '', + title: 'Notifications'.translate(), + panel: formNotifications = new PMUI.form.Form({ + id: 'formNotifications', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formNotificationsTasSend', + pmType: 'checkbox', + name: 'tas_send_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasSend1', + label: 'After routing notify the next assigned user(s)'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeFormNotifications(this.controls[0].selected, 'text'); + } + }, { + id: 'formNotificationsMainPanel', + pmType: 'panel', + items: [ + { + id: 'tas_email_server_uid', + name: 'tas_email_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_not_email_from_format', + name: 'tas_not_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'formNotificationsSubject', + pmType: 'text', + name: 'tas_def_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), { + id: 'formNotificationsContent', + pmType: 'dropdown', + name: 'tas_def_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsContent1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsContent2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentType(value); + } + }, new CriteriaField({ + id: 'formNotificationsMessage', + pmType: 'textarea', + name: 'tas_def_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), { + id: 'formNotificationsTemplate', + pmType: 'dropdown', + name: 'tas_def_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" + } + ] + }, + { + id: 'formNotificationsTasReceive', + pmType: 'checkbox', + name: 'tas_receive_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasReceive', + label: 'Notify the assigned user to this task'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeFormNotificationsReceive(this.controls[0].selected, 'text'); + } + }, + { + id: 'formNotificationsReceivePanel', + pmType: 'panel', + items: [ + { + id: 'tas_receive_server_uid', + name: 'tas_receive_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_receive_email_from_format', + name: 'tas_receive_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'tas_receive_subject_message', + pmType: 'text', + name: 'tas_receive_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), + { + id: 'tas_receive_message_type', + pmType: 'dropdown', + name: 'tas_receive_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsReceive1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsReceive2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentTypeReceive(value); + } + }, + new CriteriaField({ + id: 'tas_receive_message', + pmType: 'textarea', + name: 'tas_receive_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), + { + id: 'tas_receive_message_template', + pmType: 'dropdown', + name: 'tas_receive_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" + } + + ] + } + ] + }) + } + ]; + if (consolidated == '1') { + configurationForms.push({ + id: 'windowPropertiesTabPanelConsolidated', + icon: '', + title: 'Consolidated Case '.translate(), + panel: formConsolidated = new PMUI.form.Form({ + id: 'formConsolidated', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formConsolidatedEnable', + pmType: 'checkbox', + name: 'consolidated_enable', + labelVisible: false, + options: [{ + label: 'Enable consolidate for this task.'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeConsolidated(this.controls[0].selected); + } + }, { + id: 'formConsolidatedMainPanel', + pmType: 'panel', + items: [ + { + id: 'formConsolidatedReportTable', + pmType: 'text', + name: 'consolidated_report_table', + visible: false, + valueType: 'string', + controlsWidth: 300 + }, { + id: 'formConsolidatedDynaform', + pmType: 'dropdown', + name: 'consolidated_dynaform', + label: 'Dynaform Template'.translate(), + options: [], + required: true, + controlsWidth: 300 + }, { + id: 'formConsolidatedTable', + pmType: 'text', + name: 'consolidated_table', + valueType: 'string', + label: 'Table Name'.translate(), + placeholder: 'Insert a table name'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + }, + validators: [{ + pmType: "regexp", + criteria: /^[a-zA-Z0-9_]+$/, + errorMessage: "The table name can not contain spaces".translate() + }] + }, { + id: 'formConsolidatedTitle', + pmType: 'text', + name: 'consolidated_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + } + } + ] + } + ] + }) + }); + } + + + warningChanges = new PMUI.ui.MessageWindow({ + id: 'warningChanges', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Activity Properties'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningChangesButtonNo', + text: "No".translate(), + handler: function () { + warningChanges.close(); + }, + buttonType: "error" + }, + { + id: 'warningChangesButtonYes', + text: "Yes".translate(), + handler: function () { + windowProperties.close(); + warningChanges.close(); + }, + buttonType: "success" + } + ] + }); + windowProperties = new PMUI.ui.Window({ + id: 'windowProperties', + title: 'Activity Properties'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + onOpen: function () { + loadServerData(); + }, + items: [ + propertiesTabs = new PMUI.panel.TabPanel({ + id: 'windowPropertiesTabPanel', + height: 435, + width: DEFAULT_WINDOW_WIDTH - 50, + style: { + cssProperties: { + 'margin-left': '10px' + } + }, + items: configurationForms.concat(featuresForms), + itemsPosition: { + position: 'left' + }, + onTabClick: function (tab) { + setFocusTab(tab); + } + }), + customGrid + ], + onBeforeClose: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonPanelPosition: 'bottom', + buttonsPosition: 'right', + buttons: [ + { + id: 'windowPropertiesButtonCancel', + text: 'Cancel'.translate(), + handler: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonType: "error" + }, + { + id: 'windowPropertiesButtonSave', + text: 'Save'.translate(), + handler: function () { + saveData(); + }, + buttonType: 'success' + } + ] + }); + + function changeConsolidated(value) { + var panel = formConsolidated.getItem('formConsolidatedMainPanel'); + formConsolidated.getField('consolidated_enable').setValue(value ? '["1"]' : '[]'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + + function changeTimingControl(value) { + var mainPanel = formTimingControl.getItem('formTimingMainPanel'); + formTimingControl.getField('tas_transfer_fly').setValue(value ? '["1"]' : '[]'); + if (mainPanel) { + if (value) { + mainPanel.disable(); + + } else { + mainPanel.enable(); + } + mainPanel.setVisible(!value); + } + if (window.enterprise !== "1") { + formTimingControl.getField('tas_average').setVisible(false); + formTimingControl.getField('tas_sdv').setVisible(false); + } + } + + function changeFormNotifications(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsMainPanel'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + if (value) { + formNotifications.getField('tas_def_message_type').setValue(valueTwo); + visibleContentType(valueTwo); + } + formNotifications.getField('tas_send_last_email').setValue(value ? '["1"]' : '[]'); + formNotifications.getField('tas_def_subject_message').setFocus(); + } + + /** + * Notification receive change handler, according to user selection + * @param value + * @param valueTwo + */ + function changeFormNotificationsReceive(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsReceivePanel'); + + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } + } + + if (value) { + formNotifications.getField('tas_receive_message_type').setValue(valueTwo); + visibleContentTypeReceive(valueTwo); + } + formNotifications.getField('tas_receive_last_email').setValue(value ? '["1"]' : '[]'); + formNotifications.getField('tas_receive_subject_message').setFocus(); + } + + /** + * Get value parsed + * @param valueCheckBox '["TRUE"]'/'["FALSE"]' + * @returns {string} "TRUE"/"FALSE" + */ + function getValueCheckBox(valueCheckBox) { + var optionSelected = JSON.parse(valueCheckBox), + valChecked; + valChecked = (Array.isArray(optionSelected) && optionSelected.length === 1) ? optionSelected[0] : stringFalse; + return valChecked; + } + + function loadFormData(response) { + dataProperties = response.properties; + formDefinitions.getField('UID').setReadOnly(true); + formDefinitions.getField('UID').setValue(activity.id); + formDefinitions.getField('tas_title').setValue(dataProperties.tas_title); + formDefinitions.getField('tas_title').setFocus(); + formDefinitions.getField('tas_description').setValue(dataProperties.tas_description); + formDefinitions.getField('tas_priority_variable').setValue(dataProperties.tas_priority_variable); + formDefinitions.getField('tas_derivation_screen_tpl').setValue(dataProperties.tas_derivation_screen_tpl); + + formCaseLabels.getField('tas_def_title').setValue(dataProperties.tas_def_title); + formCaseLabels.getField('tas_def_description').setValue(dataProperties.tas_def_description); + + if (dataProperties.tas_transfer_fly === 'FALSE') { + changeTimingControl(false); + } else { + changeTimingControl(true); + } + formTimingControl.getField('tas_duration').setValue(dataProperties.tas_duration); + formTimingControl.getField('tas_timeunit').setValue(dataProperties.tas_timeunit); + formTimingControl.getField('tas_type_day').setValue(dataProperties.tas_type_day); + formTimingControl.getField('tas_calendar').setValue(dataProperties.tas_calendar); + + if (window.enterprise === "1") { + formTimingControl.getField('tas_average').setValue(dataProperties.tas_average); + formTimingControl.getField('tas_sdv').setValue(dataProperties.tas_sdv); + } + + changeFormNotifications(dataProperties.tas_send_last_email === 'TRUE', dataProperties.tas_def_message_type); + changeFormNotificationsReceive(dataProperties.tas_receive_last_email === 'TRUE', dataProperties.tas_receive_message_type); + formNotifications.getField('tas_def_subject_message').setValue(dataProperties.tas_def_subject_message); + formNotifications.getField('tas_def_message_type').setValue(dataProperties.tas_def_message_type); + formNotifications.getField('tas_def_message').setValue(dataProperties.tas_def_message); + formNotifications.getField('tas_email_server_uid').setValue(dataProperties.tas_email_server_uid); + formNotifications.getField('tas_def_message_template').setValue(dataProperties.tas_def_message_template); + formNotifications.getField('tas_not_email_from_format').setValue(dataProperties.tas_not_email_from_format); + // receive + formNotifications.getField('tas_receive_subject_message').setValue(dataProperties.tas_receive_subject_message); + formNotifications.getField('tas_receive_message_type').setValue(dataProperties.tas_receive_message_type); + formNotifications.getField('tas_receive_message').setValue(dataProperties.tas_receive_message); + formNotifications.getField('tas_receive_server_uid').setValue(dataProperties.tas_receive_server_uid); + formNotifications.getField('tas_receive_message_template').setValue(dataProperties.tas_receive_message_template); + formNotifications.getField('tas_receive_email_from_format').setValue(dataProperties.tas_receive_email_from_format); + } + function loadCalendar(response) { + var field = formTimingControl.getField('tas_calendar'), i; + field.clearOptions(); + field.addOption({ + value: '', + label: '- None -'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].cal_uid, + label: response[i].cal_name + }); + } + } + + /** + * Loads the template from rest service response + * @param response + * @param fieldName + */ + function loadTemplate(response, fieldName) { + var field = formNotifications.getField(fieldName), i, field2; + field.clearOptions(); + field.addOption({ + value: 'alert_message.html', + label: '-- Default --'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].prf_filename, + label: response[i].prf_filename + }); + } + field2 = formDefinitions.getField('tas_derivation_screen_tpl'); + field2.clearOptions(); + field2.addOption({ + value: '', + label: '-- Default --'.translate() + }); + for (i = 0; i < response.length; i += 1) { + if (response[i].prf_filename !== 'alert_message.html') { + field2.addOption({ + value: response[i].prf_filename, + label: response[i].prf_filename + }); + } + } + }; + /** + * Load Email account server dropdown options + * @param response + */ + function loadEmailAccount(response, fieldName) { + var field = formNotifications.getField(fieldName) || null, + i; + if (response instanceof Array && field) { + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + }; + + function loadABETemplateField(templates) { + var templateField = abeForm.getField('ABE_TEMPLATE'), i; + for (i in templates) { + if (templateField !== null) { + templateField.addOption({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + abeTemplates.options.push({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + }; + /** + * Loads the email accounts settings + * @param response + */ + function loadABEmailAccount(response) { + var accountField = abeForm.getField('ABE_EMAIL_SERVER_UID') || null, + i; + + if (response instanceof Array) { + for (i = 0; i < response.length; i += 1) { + if (accountField !== null) { + accountField.addOption({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + abeEmailAcount.options.push({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + + }; + + /** + * Loads the IMAP email accounts settings + * @param response + */ + function loadABImapEmailAccount(response) { + var accountField = abeForm.getField('ABE_RECEIVER_EMAIL_SERVER_UID') || null, + i; + + if (response instanceof Array) { + for (i = 0; i < response.length; i += 1) { + if (response[i].mess_engine === "IMAP") { + if (accountField !== null) { + accountField.addOption({ + value: response[i].mess_uid, + label: response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + abeReceiverAccount.options.push({ + value: response[i].mess_uid, + label: response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + } + + }; + + function loadABEDynaformField(dynaforms) { + var dynaformField = abeForm.getField('DYN_UID'), i; + for (i in dynaforms) { + if (dynaformField !== null) { + dynaformField.addOption({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME + }); + } + abeDynaforms.options.push({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME + }); + } + } + + function loadServerData() { + var restClient, i; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: { + "formconfig": { + "url": 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + "method": 'GET' + }, + "calendar": { + "url": 'calendar', + "method": 'GET' + }, + "templates": { + "url": 'project/' + PMDesigner.project.id + '/file-manager?path=templates', + "method": 'GET' + }, + "emailserver": { + "url": 'project/' + PMDesigner.project.id + '/email-event/accounts/emailServer', + "method": 'GET' + } + } + }, + functionSuccess: function (xhr, response) { + loadTemplate(response["templates"].response, 'tas_def_message_template'); + loadTemplate(response["templates"].response, 'tas_receive_message_template'); + loadCalendar(response["calendar"].response); + loadFormData(response["formconfig"].response); + loadEmailAccount(response["emailserver"].response, 'tas_email_server_uid'); + loadEmailAccount(response["emailserver"].response, 'tas_receive_server_uid'); + + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + if (consolidated == '1') { + $.extend(restClient.data.calls, { + "steps": { + 'url': 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/steps', + 'method': 'GET' + }, + "consolidate": { + "url": 'consolidated/' + activity.id, + "method": 'GET' + } + }); + } + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + } + + function visibleContentType(value) { + formNotifications.getField('tas_def_message_template').disable(); + formNotifications.getField('tas_def_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_def_message').enable(); + formNotifications.getField('tas_def_message').setVisible(true); + formNotifications.getField('tas_def_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_def_message_template').enable(); + formNotifications.getField('tas_def_message').setVisible(false); + formNotifications.getField('tas_def_message_template').setVisible(true); + } + }; + /** + * content type handler, enable or disable templates or message field + * @param value + */ + function visibleContentTypeReceive(value) { + formNotifications.getField('tas_receive_message_template').disable(); + formNotifications.getField('tas_receive_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_receive_message').enable(); + formNotifications.getField('tas_receive_message').setVisible(true); + formNotifications.getField('tas_receive_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_receive_message_template').enable(); + formNotifications.getField('tas_receive_message').setVisible(false); + formNotifications.getField('tas_receive_message_template').setVisible(true); + } + }; + function saveData() { + var tabPanel = windowProperties.getItem('windowPropertiesTabPanel'), + tabItems = tabPanel.getItems(), + valid = true, + panel, + tas_transfer_fly, + tas_send_last_email, + tas_receive_last_email, + dataCaseLabels, + dataDefinitions, + dataTimingControl, + dataNotification, + consolidated_enable, + message, + i; + + for (i = 0; i < tabItems.length; i += 1) { + panel = tabItems[i].getPanel(); + if (panel instanceof PMUI.form.Form) { + valid = valid && panel.isValid(); + } else { + if (panel.getID() === "ActionsByEmailPanel") { + if (!abeForm.isValid()) { + valid = false; + } + } + } + if (!valid) { + tabItems[i].select(); + return; + } + } + + tas_transfer_fly = formTimingControl.getField('tas_transfer_fly').getValue() === '["1"]'; + tas_send_last_email = formNotifications.getField('tas_send_last_email').getValue() === '["1"]'; + tas_receive_last_email = formNotifications.getField('tas_receive_last_email').getValue() === '["1"]'; + + if (tas_transfer_fly !== false) { + var a = formTimingControl.getField('tas_transfer_fly').getValue(); + formTimingControl.reset(); + formTimingControl.getField('tas_transfer_fly').setValue(a); + formTimingControl.getField('tas_duration').setValue('1'); + formTimingControl.getField('tas_timeunit').setValue('DAYS'); + formTimingControl.getField('tas_type_day').setValue(''); + formTimingControl.getField('tas_calendar').setValue(''); + } + + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataDefinitions = getData2PMUI(formDefinitions.html); + dataCaseLabels = getData2PMUI(formCaseLabels.html); + dataTimingControl = getData2PMUI(formTimingControl.html); + dataNotification = getData2PMUI(formNotifications.html); + if (!dataCaseLabels) { + dataCaseLabels = {}; + } + if (!dataTimingControl) { + dataTimingControl = {}; + } + if (!dataNotification) { + dataNotification = {}; + } + } else { + dataDefinitions = formDefinitions.getData(); + dataCaseLabels = formCaseLabels.getData(); + dataTimingControl = formTimingControl.getData(); + dataNotification = formNotifications.getData(); + } + + if (dataDefinitions['tas_title']) { + dataProperties.tas_title = dataDefinitions['tas_title']; + } + if (dataDefinitions['tas_description']) { + dataProperties.tas_description = dataDefinitions['tas_description']; + } + if (dataDefinitions['tas_priority_variable'] || typeof dataDefinitions['tas_priority_variable'] == "string") { + dataProperties.tas_priority_variable = dataDefinitions['tas_priority_variable']; + } + if (dataDefinitions['tas_derivation_screen_tpl'] || dataDefinitions['tas_derivation_screen_tpl'] == "") { + dataProperties.tas_derivation_screen_tpl = dataDefinitions['tas_derivation_screen_tpl']; + } + dataProperties.tas_def_title = dataCaseLabels['tas_def_title']; + dataProperties.tas_def_description = dataCaseLabels['tas_def_description']; + dataProperties.tas_transfer_fly = tas_transfer_fly ? 'TRUE' : 'FALSE'; + if (dataTimingControl['tas_duration']) { + dataProperties.tas_duration = dataTimingControl['tas_duration']; + } + if (dataTimingControl['tas_timeunit']) { + dataProperties.tas_timeunit = dataTimingControl['tas_timeunit']; + } + if (dataTimingControl['tas_type_day']) { + dataProperties.tas_type_day = dataTimingControl['tas_type_day']; + } + if (dataTimingControl['tas_calendar']) { + dataProperties.tas_calendar = dataTimingControl['tas_calendar']; + } + dataProperties.tas_send_last_email = tas_send_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_not_email_from_format']) { + dataProperties.tas_not_email_from_format = dataNotification['tas_not_email_from_format']; + } + if (dataNotification['tas_def_subject_message']) { + dataProperties.tas_def_subject_message = dataNotification['tas_def_subject_message']; + } + if (dataNotification['tas_def_message_type']) { + dataProperties.tas_def_message_type = dataNotification['tas_def_message_type']; + } + if (dataNotification['tas_def_message']) { + dataProperties.tas_def_message = dataNotification['tas_def_message']; + } + if (dataNotification['tas_def_message_template']) { + dataProperties.tas_def_message_template = dataNotification['tas_def_message_template']; + } + if (dataNotification['tas_email_server_uid'] !== 'undefined' && dataNotification['tas_email_server_uid'] !== null) { + dataProperties.tas_email_server_uid = dataNotification['tas_email_server_uid']; + } + + dataProperties.tas_receive_last_email = tas_receive_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_receive_email_from_format']) { + dataProperties.tas_receive_email_from_format = dataNotification['tas_receive_email_from_format']; + } + if (dataNotification['tas_receive_server_uid'] !== 'undefined' && dataNotification['tas_receive_server_uid'] !== null) { + dataProperties.tas_receive_server_uid = dataNotification['tas_receive_server_uid']; + } + if (dataNotification['tas_receive_subject_message']) { + dataProperties.tas_receive_subject_message = dataNotification['tas_receive_subject_message']; + } + if (dataNotification['tas_receive_message_type']) { + dataProperties.tas_receive_message_type = dataNotification['tas_receive_message_type']; + } + if (dataNotification['tas_receive_message']) { + dataProperties.tas_receive_message = dataNotification['tas_receive_message']; + } + if (dataNotification['tas_receive_message_template']) { + dataProperties.tas_receive_message_template = dataNotification['tas_receive_message_template']; + } + + if (consolidated == '1') { + consolidated_enable = false; + if (formConsolidated.getField('consolidated_enable').getValue() == '["1"]') { + consolidated_enable = true; + if (!formConsolidated.isValid()) { + return; + } + } + dataProperties.consolidate_data = { + "consolidated_enable": consolidated_enable, + "consolidated_dynaform": formConsolidated.getField('consolidated_dynaform').getValue(), + "consolidated_table": formConsolidated.getField('consolidated_table').getValue(), + "consolidated_title": formConsolidated.getField('consolidated_title').getValue(), + "consolidated_report_table": formConsolidated.getField('consolidated_report_table').getValue() + }; + } + + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: '', + data: { + definition: {}, + properties: dataProperties + }, + functionSuccess: function (xhr, response) { + setNameActivity(dataProperties.tas_title); + windowProperties.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Task properties saved successfully'.translate(), + flashContainer: document.body + })).executeRestClient(); + } + + function setFocusTab(tab) { + var style; + $customGrid = $("#customGrid"); + $customGrid.hide().appendTo($("#windowProperties").find(".pmui-window-body:eq(0)")); + + if (tab.getTitle() === 'Definitions'.translate()) { + formDefinitions.getField('tas_title').setFocus(); + } + if (tab.getTitle() === 'Case Labels'.translate()) { + formCaseLabels.getField('tas_def_title').setFocus(); + style = $('#formCaseLabelsDescription .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formCaseLabelsDescription .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Timing Control'.translate()) { + formTimingControl.getField('tas_duration').setFocus(); + } + if (tab.getTitle() === 'Notifications'.translate()) { + formNotifications.getField('tas_def_subject_message').setFocus(); + style = $('#formNotificationsMessage .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formNotificationsMessage .pmui-field-label').attr("style", style); + + style = $('#tas_receive_message .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#tas_receive_message .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Actions by Email'.translate()) { + abeForm.getField("ABE_TYPE").onChange(abeForm.getField("ABE_TYPE").getValue()); + } + } + + function isDirty() { + return formDefinitions.isDirty() || + formCaseLabels.isDirty() || + formTimingControl.isDirty() || + formNotifications.isDirty(); + } + + function setNameActivity(name) { + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + } + + windowProperties.open(); + windowProperties.showFooter(); + + applyStyleWindowForm(windowProperties); + if (consolidated == '1') { + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + function customDOM() { + $customGrid = $("#customGrid"); + $customGrid.show().appendTo($("#customGridPanel").find("fieldset:eq(0)")); + document.getElementById("customGridPanel").style.width = "720px"; + document.getElementById("customGridPanel").style.padding = ""; + document.getElementById("customGridPanel").getElementsByTagName("fieldset")[0].style.width = "100%"; + $(".pmui-gridpanel-footer").css({"text-align": "center", "margin-top": "10px", "width": "120%"}); + $(".pmui-gridpanel-footer").removeClass("pmui-gridpanel-footer"); + } + + function clearAddOptionForm() { + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + editRow = null; + }; + function addAcceptedValue() { + var abeValue = abeAddOption.getField("abe_custom_value_add").getValue(), + abeLabel = abeAddOption.getField("abe_custom_label_add").getValue(), + abeFormat = abeAddOption.getField("abe_custom_format_add").getValue(); + + if (abeAddOption && !abeAddOption.isValid()) { + return; + } + + if (!evaluateTags(abeFormat, 'validate')) { + return; + } + + if (editRow === null) { + customGrid.addItem(new PMUI.grid.GridPanelRow({ + data: { + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat + } + })); + } else { + editRow.setData({ + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat + }); + editRow = null; + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + } + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + } + + function customGridRowEdit(row) { + editRow = row; + row = row.getData(); + if (abeAddOption) { + abeAddOption.getField("abe_custom_value_add").setValue(row.abe_custom_value); + abeAddOption.getField("abe_custom_label_add").setValue(row.abe_custom_label); + abeAddOption.getField("abe_custom_format_add").setValue(row.abe_custom_format); + abeAddOption.getField("buttonFieldCancel").setVisible(true); + abeAddOption.getField("buttonFieldAdd").setValue("Save".translate()); + } + } + + function evaluateTags(html, action) { + var oldHtml; + var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*'; + var pattern = /^[a-zA-Z0-9\s\[\]\.\-_#%;,=:()']*$/; + var tagOrComment = new RegExp( + '<(?:' + // Comment body. + + '!--(?:(?:-*[^->])*--+|-?)' + // Special "raw text" elements whose content should be elided. + + '|script\\b' + tagBody + '>[\\s\\S]*?[\\s\\S]*?', + 'gi'); + + var action = (typeof action === 'undefined') ? 'delete' : 'validate'; + if (action == "validate") { + return pattern.test(html); + } else { + do { + oldHtml = html; + html = html.replace(tagOrComment, ''); + } while (html !== oldHtml); + return html.replace(/ -1) { + arrayObjectAdhocUser.splice(index, 1); + } + }, + onDrop: function (a, row) { + grid = this; + removeAD(row); + gridUserListAD.goToPage(gridUserListAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + assigmentPanelUserListAD = new PMUI.core.Panel({ + id: "assigmentPanelUserListAD", + layout: "vbox", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + }, + width: "60%" + }); + panelTitleUseListAD = new PMUI.core.Panel({ + id: "panelTitleUseListAD", + layout: "hbox" + }); + titleUserListAD = new PMUI.ui.TextLabel({ + id: "titleUserListAD", + textMode: 'plain', + text: 'Assigned users list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelGridUserListAD = new PMUI.core.Panel({ + id: "panelGridUserListAD", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] + } + }); + buttonsUserListAD = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUserListAD", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAs', + label: 'View all'.translate(), + value: 'all', + selected: true + }, { + id: 'buttonUsersAs', + label: 'View users'.translate(), + value: 'user' + }, { + id: 'buttonGroupsAs', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserListAD.typeList = "user"; + break; + case "group": + gridUserListAD.typeList = "group"; + break; + default: + gridUserListAD.typeList = ""; + break; + } + gridUserListAD.goToPage(0); + } + }); + gridUserListAD = new PMUI.grid.GridPanel({ + id: "gridUserListAD", + pageSize: pageSizeAssignmentAD - 1, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = "mafe-grid-panel-empty"; + div.style.height = gridUserListAD.dom.tableContainer.style.height; + div.style.width = gridUserListAD.dom.tableContainer.style.width; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserListAD.dom.tableContainer.style.overflow = "hidden"; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/adhoc-assignee/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].ada_type == "group") { + data[i]["assignee"] = data[i].ada_name; + } else { + data[i]["assignee"] = data[i].ada_name + " " + data[i].ada_lastname + " (" + data[i].ada_username + ")"; + } + } + return data; + }, + columns: [ + { + id: 'gridUserListADButtonLabel', + title: "", + width: "13%", + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem"; + if (row.getData()["ada_type"] === "group") { + var i, + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint("group/" + row.getData()["ada_uid"] + "/users?start=0&limit=11"); + restClient.executeRestClient(); + } + } + }, + { + title: '', + dataType: 'string', + columnData: "assignee", + alignmentCell: "left", + width: "330px" + }, + { + id: 'gridUserListADButtonDelete', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["ada_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUserListAD; + removeAD(row); + grid.goToPage(grid.currentPage); + gridUsersAD.goToPage(gridUsersAD.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (a, row) { + grid = this; + assigneeAD(row); + gridUsersAD.goToPage(gridUsersAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelContainerRules = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH - 55, + height: "auto", + fieldset: true, + items: [ + formAssignmentRules + ] + }); + panelContainerUsers = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobal + ] + }); + panelContainerUsersAdHoc = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobalAD + ] + }); + + tabPanelAssignmentRules = new PMUI.panel.TabPanel({ + id: 'tabPanelAssignmentRules', + width: "100%", + height: "auto", + items: [ + { + id: 'tabUsers', + title: 'Users'.translate(), + panel: panelContainerUsers + }, + { + id: 'tabUsersAdHoc', + title: 'Ad Hoc Users'.translate(), + panel: panelContainerUsersAdHoc + } + ], + onTabClick: function (item) { + quickMessageWindow.close(); + switch (item.id) { + case 'tabRules': + break; + case 'tabUsers': + applyStyles(); + gridUsers.goToPage(0); + gridUserList.goToPage(0); + break; + case 'tabUsersAdHoc': + applyStylesAD(); + gridUsersAD.goToPage(0); + gridUserListAD.goToPage(0); + break; + } + } + }); + windowAssignmentRules = new PMUI.ui.Window({ + id: 'windowAssignmentRules', + title: 'Assignment Rules'.translate() + ': ' + activity.act_name, + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerItems: [ + { + id: 'windowConnectionsButtonCancel', + text: 'Close'.translate(), + handler: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); + } + }, + buttonType: 'error' + }, + { + buttonType: 'success', + id: 'windowPropertiesButtonSave', + text: "Save".translate(), + handler: function () { + saveData(); + } + } + ], + visibleFooter: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); + } + } + }); + + loadTrigger = function (response) { + var field = formAssignmentRules.getField('tas_selfservice_trigger_uid'), i; + field.clearOptions(); + field.addOption({ + value: '', + label: '- Select Trigger -'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].tri_uid, + label: response[i].tri_title + }); + } + }; + loadFormData = function (response) { + dataProperties = response.properties; + formAssignmentRules.getField('tas_assign_type').setValue(dataProperties.tas_assign_type); + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + changeRadioButtons(formAssignmentRules.getField('tas_assign_type').getValue()); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + if (dataProperties.tas_selfservice_timeout === 1) { + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].select(); + } + formAssignmentRules.getField('tas_selfservice_time').setValue(dataProperties.tas_selfservice_time); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(dataProperties.tas_selfservice_time_unit); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(dataProperties.tas_selfservice_trigger_uid); + formAssignmentRules.getField('tas_selfservice_execution').setValue(dataProperties.tas_selfservice_execution); + visibleService(dataProperties.tas_selfservice_timeout === 1); + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadTrigger(response[1].response); + loadFormData(response[0].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadFreeUsers = function (response) { + var i; + gridUsers.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsers.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAssignmentUsers = function (response) { + var i; + gridUserList.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserList.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAdHocFreeUsers = function (response) { + var i; + gridUsersAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsersAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + loadAdHocAssignmentUsers = function (response) { + var i; + gridUserListAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserListAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + updateRules = function () { + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: ' ', + data: { + definition: {}, + properties: dataProperties + }, + messageSuccess: 'Assignment Rules saved successfully'.translate(), + flashContainer: document.body, + functionSuccess: function () { + formAssignmentRules.dirty = false; + windowAssignmentRules.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + }; + allHidden = function () { + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + formAssignmentRules.getField('tas_group_variable').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + formAssignmentRules.getField('tas_selfservice_time').setVisible(false); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(false); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(false); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(false); + }; + changeRadioButtons = function (newVal) { + allHidden(); + tabPanelAssignmentRules.setVisible(true); + switch (newVal) { + case 'EVALUATE': + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (dataProperties.tas_assign_variable === "" || dataProperties.tas_assign_variable === null) { + formAssignmentRules.getField('tas_assign_variable').setValue('@@SYS_NEXT_USER_TO_BE_ASSIGNED'); + } else { + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + } + break; + case 'SELF_SERVICE': + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'SELF_SERVICE_EVALUATE': + formAssignmentRules.getField('tas_group_variable').setVisible(true); + if (dataProperties.tas_group_variable === "@@SYS_GROUP_TO_BE_ASSIGNED" || dataProperties.tas_group_variable === "" || dataProperties.tas_group_variable === null) { + formAssignmentRules.getField('tas_group_variable').setPlaceholder('@@ARRAY_OF_USERS or @@GROUP_UID'); + } else { + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + } + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'REPORT_TO': + break; + case 'MULTIPLE_INSTANCE_VALUE_BASED': + formAssignmentRules.getField('tas_assign_variable').setLabel("Array of users".translate()); + if (formAssignmentRules.getField('tas_assign_variable').getValue() == "@@SYS_NEXT_USER_TO_BE_ASSIGNED" || formAssignmentRules.getField('tas_assign_variable').getValue() == "") { + formAssignmentRules.getField('tas_assign_variable').setValue(''); + formAssignmentRules.getField('tas_assign_variable').setPlaceholder('@@ARRAY_OF_USERS'); + } + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (activity.act_loop_type == "PARALLEL") { + tabPanelAssignmentRules.setVisible(false); + } + break; + default: + break; + } + }; + visibleService = function (value) { + var a = formAssignmentRules.getField('tas_assign_type').getValue(); + if (a === 'SELF_SERVICE' || a === 'SELF_SERVICE_EVALUATE') { + formAssignmentRules.getField('tas_selfservice_time').setVisible(value); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(value); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(value); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(value); + } + }; + hiddenTab = function (value) { + tabPanelAssignmentRules.showTab(2); + }; + saveData = function () { + var a, b, c, d, tas_selfservice_timeout, data; + tas_selfservice_timeout = formAssignmentRules.getField('tas_selfservice_timeout').getValue() === '["1"]'; + if (!tas_selfservice_timeout) { + //validation because getData method do not work in IE + if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { + data = getData2PMUI(formAssignmentRules.html); + b = data["tas_assign_variable"]; + } else { + b = formAssignmentRules.getField('tas_assign_variable').getValue(); + } + a = formAssignmentRules.getField('tas_assign_type').getValue(); + c = formAssignmentRules.getField('tas_group_variable').getValue(); + d = formAssignmentRules.getField('tas_group_variable').getValue(); + formAssignmentRules.getField('tas_assign_type').setValue(a); + formAssignmentRules.getField('tas_assign_variable').setValue(b); + formAssignmentRules.getField('tas_group_variable').setValue(c); + formAssignmentRules.getField('tas_selfservice_timeout').setValue(d); + formAssignmentRules.getField('tas_selfservice_time').setValue(''); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(''); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(''); + formAssignmentRules.getField('tas_selfservice_execution').setValue(''); + } else { + if (!formAssignmentRules.isValid()) { + return; + } + } + dataProperties.tas_assign_type = formAssignmentRules.getField('tas_assign_type').getValue(); + dataProperties.tas_assign_variable = formAssignmentRules.getField('tas_assign_variable').getValue() === '' ? '@@SYS_NEXT_USER_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_assign_variable').getValue(); + dataProperties.tas_group_variable = formAssignmentRules.getField('tas_group_variable').getValue() === '' ? '@@SYS_GROUP_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_group_variable').getValue(); + dataProperties.tas_selfservice_timeout = tas_selfservice_timeout ? 1 : 0; + dataProperties.tas_selfservice_time = formAssignmentRules.getField('tas_selfservice_time').getValue() !== "" ? parseInt(formAssignmentRules.getField('tas_selfservice_time').getValue(), 10) : 0; + dataProperties.tas_selfservice_time_unit = formAssignmentRules.getField('tas_selfservice_time_unit').getValue(); + dataProperties.tas_selfservice_trigger_uid = formAssignmentRules.getField('tas_selfservice_trigger_uid').getValue(); + dataProperties.tas_selfservice_execution = formAssignmentRules.getField('tas_selfservice_execution').getValue(); + updateRules(); + }; + saveOrUpdateUserAndAdHocUsers = function () { + //Assigne and Remove (users) + var i, b; + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); + } + } + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } + } + } + //Assigne and Remove (AdHocUsers) + if (gridUserListAD.getItems().length > 0) { + grid = gridUserListAD; + for (i = 0; i < arrayObjectAdhocUserList.length; i += 1) { + b = arrayObjectAdhocUserList[i]; + if (arrayObjectAdhocUserList2.indexOf(b) == -1) { + assigneeAD(b); + } + } + } + if (gridUsersAD.getItems().length > 0) { + for (i = 0; i < arrayObjectAdhocUser.length; i += 1) { + b = arrayObjectAdhocUser[i]; + if (arrayObjectAdhocUser2.indexOf(b) == -1) { + removeAD(arrayObjectAdhocUser[i]); + } + } + } + }; + applyStyles = function () { + gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + buttonsUsers.defineEvents(); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + buttonsUserList.defineEvents(); + gridUserList.dom.toolbar.style.height = "76px"; + buttonsUsers.dom.labelTextContainer.style.display = "none"; + buttonsUserList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + }; + applyStylesAD = function () { + gridUsersAD.dom.toolbar.appendChild(buttonsUsersAD.getHTML()); + buttonsUsersAD.defineEvents(); + gridUsersAD.dom.toolbar.style.height = "76px"; + + gridUserListAD.dom.toolbar.appendChild(buttonsUserListAD.getHTML()); + buttonsUserListAD.defineEvents(); + gridUserListAD.dom.toolbar.style.height = "76px"; + buttonsUsersAD.dom.labelTextContainer.style.display = "none"; + buttonsUserListAD.dom.labelTextContainer.style.display = "none"; + gridUsersAD.hideHeaders(); + gridUserListAD.hideHeaders(); + assigmentPanelUserListAD.setHeight('100%'); + gridUsersAD.filterControl.html.style.width = "300px"; + gridUserListAD.filterControl.html.style.width = "300px"; + }; + assignee = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/assignee"); + restClient.setData({aas_uid: row.getData()["aas_uid"], aas_type: row.getData()["aas_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + remove = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/assignee/" + row.getData().aas_uid); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + assigneeAD = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee"); + restClient.setData({ada_uid: row.getData()["ada_uid"], ada_type: row.getData()["ada_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + removeAD = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee/" + row.getData()["ada_uid"]); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().ass_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('fullName', 'asc'); + }; + + function onchangeRadio(grid, fieldName) { + var radioButTrat = document.getElementsByName(fieldName), i; + for (i = 0; i < radioButTrat.length; i += 1) { + if (radioButTrat[i].checked == true) { + quickMessageWindow.close(); + groupRows(grid, radioButTrat[i].value); + } + } + } + + function domSettings() { + if (activity.act_loop_type == "PARALLEL") { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().show(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE_VALUE_BASED"); + } else { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE"); + } + } else { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().hide(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("BALANCED"); + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + } + } + }; + + panelTitleUser.addItem(titleUser); + panelGridUser.addItem(gridUsers); + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelGridUser); + assigmentPanelGlobal.addItem(assigmentPanelUser); + panelTitleUserList.addItem(titleUserList); + panelGridUserList.addItem(gridUserList); + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelGridUserList); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + + panelTitleUserAD.addItem(titleUserAD); + panelSearchUserAD.addItem(searchGridUserAD); + panelGridUserAD.addItem(gridUsersAD); + assigmentPanelUserAD.addItem(panelTitleUserAD); + assigmentPanelUserAD.addItem(panelGridUserAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserAD); + panelTitleUseListAD.addItem(titleUserListAD); + panelGridUserListAD.addItem(gridUserListAD); + assigmentPanelUserListAD.addItem(panelTitleUseListAD); + assigmentPanelUserListAD.addItem(panelGridUserListAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserListAD); + + if (formAssignmentRules.dirty == null) { + formAssignmentRules.dirty = false; + } + windowAssignmentRules.addItem(formAssignmentRules); + windowAssignmentRules.addItem(tabPanelAssignmentRules); + windowAssignmentRules.open(); + applyStyleWindowForm(windowAssignmentRules); + windowAssignmentRules.body.style.overflowY = 'auto'; + windowAssignmentRules.body.style.overflowX = 'hidden'; + windowAssignmentRules.defineEvents(); + buttonsUsers.defineEvents(); + tabPanelAssignmentRules.itemClick(0); + loadServerData(); + domSettings(); + //array for Users + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + //array for AdHocUsers + usersgrid = gridUsersAD; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectAdhocUser2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserListAD; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectAdhocUserList2[i] = userslist.getItems()[i]; + } + formAssignmentRules.html.style.marginLeft = '30px'; + formAssignmentRulesSetTimeoutOption; + document.getElementById("formAssignmentRulesSetTimeoutOption").childNodes[0].onchange = function () { + visibleService(this.checked); + }; + $(".pmui-field-control-table").css("border", "0px"); + $(".pmui-field-label").css("padding", "0px"); + $(".mafe-designer-assigment-title").css("margin-top", "25px"); + $("#formTasAssignType").append("
"); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + buttonsUserList, + gridUserList, + applyStyles, + loadServerData, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + quickMessageWindow = new QuickMessageWindow(); + + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Assign Users and Groups as Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true + }); + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: 'There are problems, please try again.'.translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + assigmentPanelUser = new PMUI.core.Panel({ + layout: "vbox", + width: "49%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + } + }); + assigmentPanelUserList = new PMUI.core.Panel({ + layout: "vbox", + width: "50%", + style: { + cssClasses: [ + 'mafe-panel-assignment-smooth' + ] + } + }); + assigmentPanelGlobal = new PMUI.core.Panel({ + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH, + style: { + cssClasses: [ + 'mafe-assigment-panel-global' + ] + } + }); + + panelTitleUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUser = new PMUI.ui.TextLabel({ + id: 'titleUser', + label: ' ', + textMode: 'plain', + text: 'Available Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUser = new PMUI.field.TextField({ + id: 'searchGridUser', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); + buttonsUsers = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUsers', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + selected: true, + value: 'all', + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + ], + listeners: { + select: function (item, event) { + groupRows(gridUsers, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUsers = new PMUI.grid.GridPanel({ + id: 'gridUsers', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: '10%', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + var stringUsers = '', i; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'sup_name', + alignmentCell: 'left', + width: '80%' + }, { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: '19%', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Assign'.translate(); + }, + onButtonClick: function (row, grid) { + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(row); + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); + assignee(row); + } + } + ], + onDropOut: function (item, origin, destiny) { + assignee(item); + }, + onDrop: function (a, row) { + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelTitleUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUserList = new PMUI.ui.TextLabel({ + id: 'titleUserList', + textMode: 'plain', + text: 'Assigned Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + buttonsUserList = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUserList', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + value: 'all', + selected: true, + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + + ], + listeners: { + select: function (item, event) { + groupRows(gridUserList, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUserList = new PMUI.grid.GridPanel({ + id: 'gridUserList', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + filterable: true, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = 'mafe-grid-panel-empty'; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserList.dom.tableContainer.style.overflow = 'hidden'; + }, + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var stringUsers, i; + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + stringUsers = ''; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'sup_name', + width: '80%', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Remove'.translate(); + }, + onButtonClick: function (row, grid) { + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUsers.addItem(row); + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); + remove(row); + } + } + ], + onDropOut: function (item, origin, destiny) { + remove(item); + }, + onDrop: function (a, row) { + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + applyStyles = function () { + gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + buttonsUsers.dom.labelTextContainer.style.display = "none"; + buttonsUserList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/available-process-supervisors', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/process-supervisors', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadUsers(response[0].response); + loadUsersList(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); + } + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); + } + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.data.customKeys.sup_uid, + pu_type: row.data.customKeys.obj_type === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.data.customKeys.pu_uid, + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflow = "hidden"; + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); + + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); + + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(buttonsUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(buttonsUserList); + assigmentPanelUserList.addItem(panelGridUserList); + + assigmentWindow.defineEvents(); + applyStyles(); + + loadServerData(); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + flagEdit = 0, + i, + index = 0, + quickMessageWindow = new QuickMessageWindow(), + arrayObjectUserList = new Array(), + arrayObjectUsers = new Array(), + arrayObjectUserList2 = new Array(), + arrayObjectUsers2 = new Array(), + arrayDynaformInputDocumentID = new Array(), + arrayDynaformInputDocumentObject = new Array(), + arrayObjectRemovedSteps = new Array(), + message_window, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + radioUsersList, + buttonsUserList, + gridUserList, + radioUsers, + applyStylesRadioButtonGroupField, + applyStylesForToolbar, + applyStyles, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + loadGridCaseTacker, + orderDataTree, + titleTreeObjects, + titleGridObjects, + panelLabelObjects, + panelObjects, + treePanelObjects, + updateItem, + usersgrid, + saveItemDyanformInputDocuments, + getValuesAssignmentSteps, + gridPanelObjects, + panelContainerObjects, + userslist, + gridpanelobj, + flashMessage = new PMUI.ui.FlashMessage({ + message: '', + appendTo: document.body, + duration: 1000, + severity: "success" + }); + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + onBeforeClose: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } + }, + footerItems: [ + { + text: "Cancel", + handler: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } + }, + buttonType: 'error' + }, + { + text: 'Save', + handler: function () { + var i, j, idObject, objType, baseEndPointID; + if (flagEdit != 0) { + //save Configuration Supervisors and Steps(Dyanform - Inputs Documents) + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + grid.removeItem(b); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(b); + radioUsersList.setValue(radioUsers.getValue()); + groupRows(gridUserList, radioUsers.getValue()); + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); + } + } + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } + } + } + + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayDynaformInputDocumentID.indexOf(idObject); + if (index <= -1) { + saveItemDyanformInputDocuments(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); + } + } + + for (i = 0; i < arrayObjectRemovedSteps.length; i += 1) { + for (j = 0; j < arrayDynaformInputDocumentObject.length; j += 1) { + index = (arrayObjectRemovedSteps[i] == arrayDynaformInputDocumentObject[j].obj_uid) ? 0 : 1; + if (index == 0) { + objType = arrayDynaformInputDocumentObject[j].obj_type.toLowerCase(); + baseEndPointID = (objType === "dynaform") ? arrayDynaformInputDocumentObject[j].pud_uid : arrayDynaformInputDocumentObject[j].pui_uid; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + '/' + baseEndPointID, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } + } + } + assigmentWindow.close(); + } + else { + assigmentWindow.close(); + } + }, + buttonType: "success" + } + ], + visibleFooter: true, + buttonPanelPosition: "bottom", + footerAlign: "right" + }); + + message_window = new PMUI.ui.MessageWindow({ + id: "messageWindowCancel", + width: 490, + title: "Supervisors".translate(), + windowMessageType: "warning", + bodyHeight: "auto", + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: "messageWindowNo", + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: "messageWindowYes", + text: "Yes".translate(), + handler: function () { + message_window.close(); + assigmentWindow.close(); + }, + buttonType: "success" + } + ] + }); + + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: 'There are problems, please try again.'.translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + assigmentPanelUser = new PMUI.core.Panel({ + layout: "vbox", + width: "49%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] + } + }); + assigmentPanelUserList = new PMUI.core.Panel({ + layout: "vbox", + width: "50%", + style: { + cssClasses: [ + 'mafe-panel-assignment-smooth' + ] + } + }); + assigmentPanelGlobal = new PMUI.core.Panel({ + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH, + style: { + cssClasses: [ + 'mafe-assigment-panel-global' + ] + } + }); + + panelTitleUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUser = new PMUI.ui.TextLabel({ + id: 'titleUser', + label: ' ', + textMode: 'plain', + text: 'Available Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUser = new PMUI.field.TextField({ + id: 'searchGridUser', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); + buttonsUsers = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUsers', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + selected: true, + value: 'all', + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + ], + listeners: { + select: function (item, event) { + groupRows(gridUsers, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUsers = new PMUI.grid.GridPanel({ + id: 'gridUsers', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/available-process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].obj_type == "group") { + data[i].available = data[i].grp_name; + } else { + data[i].available = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + } + } + return data; + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: '10%', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["obj_type"] === 'group') { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'available', + alignmentCell: 'left', + width: '330px' + }, { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: '19%', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit-assign' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["obj_type"] === 'user' ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + assignee(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (a, row) { + grid = this; + remove(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelTitleUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUserList = new PMUI.ui.TextLabel({ + id: 'titleUserList', + textMode: 'plain', + text: 'Assigned supervisors list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + radioUsersList = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsersList', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + label: "View all".translate(), + value: "all" + }, + { + label: "View users".translate(), + value: "user" + }, + { + label: "View groups".translate(), + value: "group" + } + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserList.typeList = "user".translate(); + break; + case "group": + gridUserList.typeList = "group".translate(); + break; + default: + gridUserList.typeList = ""; + break; + } + gridUserList.goToPage(0); + }, + required: true, + value: "all" + }); + buttonsUserList = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUserList', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + value: 'all', + selected: true, + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] + } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] + } + } + + ], + listeners: { + select: function (item, event) { + groupRows(gridUserList, item.value); + } + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUserList = new PMUI.grid.GridPanel({ + id: 'gridUserList', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + filterable: true, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = 'mafe-grid-panel-empty'; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserList.dom.tableContainer.style.overflow = 'hidden'; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].pu_type == "GROUP_SUPERVISOR") { + data[i].assignee = data[i].grp_name; + } else { + data[i].assignee = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + } + } + return data; + }, + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["pu_type"] === "GROUP_SUPERVISOR") { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'assignee', + width: '330px', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["pu_type"] === "SUPERVISOR" ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + remove(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (grid, row) { + var dataRow = {}; + grid = this; + assignee(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + radioUsers = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsers', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + label: "View all".translate(), + value: "all" + }, + { + label: "View users".translate(), + value: "user" + }, + { + label: "View groups".translate(), + value: "group" + } + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUsers.typeList = "user"; + break; + case "group": + gridUsers.typeList = "group"; + break; + default: + gridUsers.typeList = ""; + break; + } + gridUsers.goToPage(0); + }, + required: true, + value: "all", + style: { + cssProperties: { + 'margin-top': '15px' + } + } + }); + applyStylesRadioButtonGroupField = function () { + $('#idRadioUsers .pmui-field-control-table').css("border", "none"); + $('#idRadioUsers').css("margin-top", "12px"); + radioUsers.defineEvents(); + + $('#idRadioUsersList .pmui-field-control-table').css("border", "none"); + $('#idRadioUsersList').css("margin-top", "12px"); + radioUsersList.defineEvents(); + }; + + applyStylesForToolbar = function () { + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('#assigmentUserWindow')[0].childNodes[1].childNodes[0].childNodes[1].style.backgroundColor = "white"; + $('#gridUserList')[0].style.backgroundColor = "white"; + $('#gridUserList').css("width", "452px"); + $('#gridUsers').css({"width": "452px", "height": "175px"}); + $('.pmui-window-body .pmui-panel:eq(9)').css({ + 'width': '1000px', + 'border-top': '1px solid #cdd2d5', + 'margin-top': '36px', + 'height': '80px' + }); + }; + + applyStyles = function () { + applyStylesRadioButtonGroupField(); + gridUsers.dom.toolbar.appendChild(radioUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(radioUsersList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + radioUsers.dom.labelTextContainer.style.display = "none"; + radioUsersList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderRight = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[1].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.paddingLeft = "10px"; + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': '245px'}); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); + } + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); + } + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } + } + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.getData()["obj_type"] == "group" ? row.getData()["grp_uid"] : row.getData()["usr_uid"], + pu_type: row.getData()["obj_type"] === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.getData()["pu_uid"], + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + //steps Dynaforms and InputDocuments + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ], + cssProperties: { + 'left': 40 + } + } + }); + + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 2, + 'margin-left': 50 + } + }, + layout: "hbox" + }); + + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 30, + fieldset: true, + items: [ + panelLabelObjects + ], + layout: "vbox" + }); + + //Objects + orderDataTree = function (data) { + var items = [], i, + type = ['DYNAFORM', 'INPUT-DOCUMENT'], + label = ['Dynaform', 'Input Document']; + for (i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + if (data[j].obj_type == "DYNAFORM") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['dyn_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + dyn_uid: data[j]['dyn_uid'] + }); + } else { + if (data[j].obj_type == "INPUT-DOCUMENT") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['inp_doc_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + obj_uid: data[j]['obj_uid'], + inp_uid: data[j]['inp_doc_uid'] + }); + } + } + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [{obj_title: 'N/A'.translate(), obj_uid: ''}] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items + }); + } + } + }; + + loadGridCaseTacker = function (data) { + var dataOrder = new Array(), i, j; + for (i = 0; i < data.length; i += 1) { + for (j = 0; j < data.length; j += 1) { + positionIndex = (data[j]['obj_type'] == 'DYNAFORM') ? data[j].pud_position : data[j].pui_position; + if (positionIndex == (i + 1)) { + dataOrder.push(data[j]); + switch (dataOrder[i]['obj_type']) { + case 'DYNAFORM': + label = dataOrder[i]['dyn_title'].translate(); + break; + case 'INPUT-DOCUMENT': + label = dataOrder[i]['input_doc_title'].translate(); + break; + default: + break; + } + dataOrder[i]['obj_title'] = label; + break; + } + } + } + gridPanelObjects.setDataItems(dataOrder); + }; + + getValuesAssignmentSteps = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "process-supervisor/available-assignmentsteps", + "method": 'GET' + }, + { + "url": "process-supervisor/assignmentsteps", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Text to search'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true + } + }); + + //Save Item (Drop) + saveItemDyanformInputDocuments = function (rowStep) { + rowStep = rowStep.getData(); + if (rowStep.obj_type === "DYNAFORM") { + data = { + "dyn_uid": rowStep.obj_uid, + "pud_position": rowStep.obj_position + }; + } else { + data = { + "inp_doc_uid": rowStep.obj_uid, + "pui_position": rowStep.obj_position + }; + } + + restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + rowStep.obj_type.toLowerCase(), + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + return data; + }; + + //Update SORT tree + updateItem = function (rowStep, i) { + var objType, + baseEndPointType, + baseEndPointID; + rowStep = rowStep.getData(); + rowStep.obj_position = i + 1; + objType = rowStep.obj_type.toLowerCase(), + baseEndPointType = (objType === "dynaform") ? 'dynaforms' : 'input-documents'; + baseEndPointID = (objType === "dynaform") ? rowStep.pud_uid : rowStep.pui_uid; + if (objType === "dynaform") { + rowStep.pud_position = rowStep.obj_position; + } else { + rowStep.pui_position = rowStep.obj_position; + } + + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + "/" + baseEndPointID, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + }; + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + style: { + cssClasses: ['itemsSteps'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_type", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + var rowStep, treePanelItems; + flagEdit = 1; + index = arrayDynaformInputDocumentID.indexOf(row.getData().obj_uid); + rowStep = row.getData(); + treePanelItems = treePanelObjects.getItems(); + + if (index > -1) { + arrayObjectRemovedSteps.push(row.getData().obj_uid); + arrayDynaformInputDocumentID.splice(index, 1); + } + function removeRowClass(treeNode) { + var childNodeEl = $(treeNode.html).find('.pmui-gridpanelrow'); + childNodeEl.removeClass('pmui-gridpanelrow'); + } + + function removeEmptyNode(indexNode) { + var parentNode = treePanelItems[indexNode]; + if (parentNode.getItems().length == 1 && + parentNode.getItems()[0].getData()['obj_uid'] == "") { + parentNode.removeItem(0); + } + parentNode.addItem(row); + removeRowClass(parentNode); + } + + if (rowStep.obj_type === "DYNAFORM") { + removeEmptyNode(0); + } else { + removeEmptyNode(1); + } + grid.removeItem(row); + } + } + ], + onDrop: function (grid, item, index) { + var parentItems; + if (item.getData()['obj_uid'] == "") { + return false; + + } + parentItems = item.parent.getItems(); + if (parentItems.length == 1 && item.getData()['obj_uid'] != "") { + item.parent.addDataItem( + {obj_title: 'N/A'.translate(), obj_uid: ''} + ); + item.parent.behaviorObject.draggedObject = item; + } + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + item.setData(rowStep); + index = arrayObjectRemovedSteps.indexOf(item.getData().obj_uid); + + if (index > -1) { + arrayDynaformInputDocumentID.push(item.getData().obj_uid); + arrayObjectRemovedSteps.splice(index, 1); + } + }, + onSort: function (grid, item, index) { + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + } + }); + + //principal Container Steps + panelContainerObjects = new PMUI.core.Panel({ + id: "panelContainerObjects", + width: DEFAULT_WINDOW_WIDTH, + height: 250, + fieldset: true, + items: [treePanelObjects, gridPanelObjects], + layout: "hbox", + style: { + cssProperties: { + 'margin-top': '-40px' + } + } + }); + + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflowX = "hidden"; + + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); + + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); + + assigmentWindow.addItem(panelObjects); + assigmentWindow.addItem(panelContainerObjects); + getValuesAssignmentSteps(); + + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(630); + gridPanelObjects.setHeight(250); + $('#gridPanelObjects').css("margin-right", "32px"); + $('#treePanelObjects').css("margin-left", "10px"); + + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(radioUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(radioUsersList); + assigmentPanelUserList.addItem(panelGridUserList); + gridUsers.dom.tableContainer.style.height = "245px"; + gridUserList.dom.tableContainer.style.height = "245px"; + gridUsers.goToPage(0); + gridUserList.goToPage(0); + assigmentWindow.defineEvents(); + applyStyles(); + treePanelObjects.style.addProperties({overflow: 'auto'}); + + applyStylesForToolbar(); + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + gridpanelobj = gridPanelObjects; + for (i = 0; i < gridpanelobj.getItems().length; i += 1) { + arrayDynaformInputDocumentID[i] = gridpanelobj.getItems()[i].getData().obj_uid; + arrayDynaformInputDocumentObject[i] = gridpanelobj.getItems()[i].getData(); + } + }; +}()); +( + function () { + PMDesigner.propertiesProcess = function () { + var responseProperties = null, + getValuesProperties, + isDirtyFormProcess, + saveProperties, + propertiesWindow, + processUID, + textTitle, + textDescription, + processOwner, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + loadProperties, + proUnitCost, + formEditProcess, + loadDynaforms, + loadCalendar, + loadTemplate, + loadTriggers, + loadTypeProcess, + loadCategory, + notification, + notificationText = "Fields marked with an asterisk (%%ASTERISK%%) are required.".translate() + .replace(/%%ASTERISK%%/g, '*'), + clickedClose; + + getValuesProperties = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "project/" + PMDesigner.project.id + "/dynaforms", + "method": 'GET' + }, + { + "url": "calendars", + "method": 'GET' + }, + { + "url": "project/categories", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/file-manager?path=templates", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/triggers", + "method": 'GET' + }, + { + "url": "project/" + PMDesigner.project.id + "/process", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadDynaforms(response[0].response); + loadCalendar(response[1].response); + loadCategory(response[2].response); + loadTemplate(response[3].response); + loadTriggers(response[4].response); + loadTypeProcess(response[5].response); + loadProperties(response[5].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + isDirtyFormProcess = function () { + var message_window + if (formEditProcess.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Edit process".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + propertiesWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + propertiesWindow.close(); + } + }; + saveProperties = function (data) { + var restClient = new PMRestClient({ + typeRequest: 'update', + data: data, + messageSuccess: "Properties saved successfully".translate(), + functionSuccess: function (xhr, response) { + propertiesWindow.close(); + + PMDesigner.project.setProjectName(data.pro_title); + PMDesigner.project.setDescription(data.pro_description); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + PMDesigner.project.dirty = false; + } + }); + restClient.setEndpoint("process"); + restClient.executeRestClient(); + }; + + propertiesWindow = new PMUI.ui.Window({ + id: "propertiesProcessWindow", + title: "Edit process".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: "auto", + modal: true, + buttonPanelPosition: "bottom", + footerAlign: "right", + onBeforeClose: function () { + clickClose = true; + isDirtyFormProcess(); + }, + buttons: [ + { + id: 'outputWindowDocButtonCancel', + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + clickedClose = false; + isDirtyFormProcess(); + } + }, + { + id: 'outputWindowDocButtonSave', + text: "Save".translate(), + buttonType: "success", + handler: function () { + var dataForm; + if (formEditProcess.isValid() && processOwner.isValid()) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataForm = getData2PMUI(formEditProcess.html); + } else { + dataForm = formEditProcess.getData(); + dataForm.pro_process_owner = processOwner.get("value"); + } + dataForm.pro_debug = checkDebug.controls[0].selected ? 1 : 0; + dataForm.pro_show_message = checkHideCase.controls[0].selected ? 1 : 0; + dataForm.pro_subprocess = checkSubProcess.controls[0].selected ? 1 : 0; + functionAssignmentUsers = function (xhr, response) { + }; + saveProperties(dataForm); + } else { + if (!(processOwner.isValid()) && formEditProcess.isValid()) { + formEditProcess.addItem(notification); + } else { + formEditProcess.removeItem(notification); + } + } + } + } + ] + }); + + processUID = new PMUI.field.TextField({ + label: "UID".translate(), + id: "process_uid", + name: "pro_uid", + labelWidth: "35%", + controlsWidth: "300px" + }); + + textTitle = new PMUI.field.TextField({ + label: "Title".translate(), + id: 'textTitle', + name: 'pro_title', + labelWidth: "35%", + placeholder: 'a text here'.translate(), + controlsWidth: "300px", + required: true + }); + + textDescription = new PMUI.field.TextAreaField({ + id: 'textDescription', + name: 'pro_description', + label: "Description".translate(), + labelWidth: "35%", + controlsWidth: "500px", + rows: 150, + style: {cssClasses: ['mafe-textarea-resize']} + }); + + processOwner = new SuggestField({ + id: 'processOwner', + name: 'pro_owner', + label: "Process Owner".translate(), + required: true, + width: 500, + placeholder: "suggest users".translate(), + separatingText: ["Users".translate()], + dynamicLoad: { + data: [ + { + key: "usr_uid", + label: ["usr_firstname", "usr_lastname", "(", "usr_username", ")"] + } + ], + keys: { + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endpoints: [ + { + method: "GET", + url: 'users' + } + ] + } + } + }); + + dropCalendar = new PMUI.field.DropDownListField({ + id: "dropCalendar", + name: "pro_calendar", + labelWidth: "35%", + label: "Calendar".translate(), + controlsWidth: "300px", + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropProcessCat = new PMUI.field.DropDownListField({ + id: "dropProcessCat", + name: "pro_category", + controlsWidth: "300px", + labelWidth: "35%", + label: "Process Category".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropDynaform = new PMUI.field.DropDownListField({ + id: "dropDynaform", + name: "pro_summary_dynaform", + controlsWidth: "300px", + labelWidth: "35%", + label: "Dynaform to show a case summary".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + dropRouting = new PMUI.field.DropDownListField({ + id: "dropRouting", + name: "pro_derivation_screen_tpl", + controlsWidth: "300px", + labelWidth: "35%", + label: "Routing Screen Template".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); + + checkDebug = new PMUI.field.CheckBoxGroupField({ + id: 'checkDebug', + labelWidth: "35%", + label: "Debug".translate(), + name: "pro_debug", + value: '1', + controlPositioning: 'vertical', + options: [ + { + id: 'pro_debug', + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + + checkHideCase = new PMUI.field.CheckBoxGroupField({ + id: 'checkHideCase', + labelWidth: "35%", + label: "Hide the case number and the case title in the steps".translate(), + value: '1', + name: "pro_show_message", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + + checkSubProcess = new PMUI.field.CheckBoxGroupField({ + id: 'checkSubProcess', + labelWidth: "35%", + label: "This a sub-process".translate(), + value: '1', + name: "pro_subprocess", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + } + }); + dropCaseCreated = new PMUI.field.DropDownListField({ + id: "dropCaseCreated", + name: "pro_tri_create", + labelWidth: "35%", + label: "Execute a trigger when a case is created".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseDeleted = new PMUI.field.DropDownListField({ + id: "dropCaseDeleted", + name: "pro_tri_deleted", + labelWidth: "35%", + label: "Execute a trigger when a case is deleted".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseCancelled = new PMUI.field.DropDownListField({ + id: "dropCaseCancelled", + name: "pro_tri_canceled", + labelWidth: "35%", + label: "Execute a trigger when a case is cancelled".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCasePaused = new PMUI.field.DropDownListField({ + id: "dropCasePaused", + name: "pro_tri_paused", + labelWidth: "35%", + label: "Execute a trigger when a case is paused".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseUnpaused = new PMUI.field.DropDownListField({ + id: "dropCaseUnpaused", + name: "pro_tri_unpaused", + labelWidth: "35%", + label: "Execute a trigger when a case is unpaused".translate(), + valueType: "string", + controlsWidth: "300px" + }); + + dropCaseReassigned = new PMUI.field.DropDownListField({ + id: "dropCaseReassigned", + name: "pro_tri_reassigned", + labelWidth: "35%", + label: "Execute a trigger when a case is reassigned".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseOpen = new PMUI.field.DropDownListField({ + id: "dropCaseOpen", + name: "pro_tri_open", + label: "Execute a trigger when a case is opened".translate(), + labelWidth: "35%", + valueType: "string", + controlsWidth: "300px", + + onChange: function (newValue, prevValue) { + } + }); + + dropTypeProcess = new PMUI.field.DropDownListField({ + id: "dropTypeProcess", + name: "pro_type_process", + labelWidth: "35%", + label: "Process Design Access: Public / Private (Owner)".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + proCost = new PMUI.field.TextField({ + id: 'proCost', + name: 'pro_cost', + labelWidth: "35%", + value: 0, + placeholder: 'a cost here'.translate(), + label: "Cost".translate(), + valueType: 'integer', + controlsWidth: "300px", + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" + } + } + }); + + proUnitCost = new PMUI.field.TextField({ + id: 'proUnitCost', + name: 'pro_unit_cost', + labelWidth: "35%", + value: '$', + placeholder: 'a unit cost here'.translate(), + controlsWidth: "300px", + label: "Units".translate(), + valueType: 'string', + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" + } + } + }); + + notification = new PMUI.field.TextAnnotationField({ + id: "requiredMessage", + name: "Message", + textType: PMUI.field.TextAnnotationField.TEXT_TYPES.HTML, + text: notificationText, + text_Align: "center" + }); + + formEditProcess = new PMUI.form.Form({ + id: 'formEditProcess', + fieldset: true, + title: "Process Information".translate(), + width: DEFAULT_WINDOW_WIDTH - DEFAULT_WINDOW_WIDTH * 0.10, + items: [ + processUID, + textTitle, + textDescription, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + proUnitCost + ] + }); + + //Load Dynaforms + loadDynaforms = function (response) { + var i; + dropDynaform.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropDynaform.addOption({ + label: response[i].dyn_title, + value: response[i].dyn_uid, + select: false + }); + } + }; + + //Load calendar + loadCalendar = function (response) { + var i; + dropCalendar.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropCalendar.addOption({ + label: response[i].cal_name, + value: response[i].cal_uid, + select: false + }); + } + }; + + //Load category + loadCategory = function (response) { + var i; + dropProcessCat.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropProcessCat.addOption({ + label: response[i].cat_name, + value: response[i].cat_uid, + select: false + }); + } + }; + + //Load Templates + loadTemplate = function (response) { + var i; + dropRouting.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + if (response[i].prf_filename != "alert_message.html") { + dropRouting.addOption({ + label: response[i].prf_filename, + value: response[i].prf_filename, + select: false + }); + } + } + }; + + //Load triggers + loadTriggers = function (response) { + var i; + dropCaseCreated.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseDeleted.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseCancelled.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCasePaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseUnpaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseReassigned.addOption({ + label: "None".translate(), + value: "", + select: false + }); + + dropCaseOpen.addOption({ + label: "None".translate(), + value: "", + select: false + }); + + for (i = 0; i < response.length; i += 1) { + dropCaseCreated.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseDeleted.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseCancelled.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCasePaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseUnpaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseReassigned.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + + dropCaseOpen.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + } + }; + + // Load type of process + loadTypeProcess = function (response) { + dropTypeProcess.addOption({ + label: "Public".translate(), + value: "PUBLIC", + select: false + }); + dropTypeProcess.addOption({ + label: "Private".translate(), + value: "PRIVATE", + select: false + }); + }; + + // Load properties of process + loadProperties = function (response) { + propertiesWindow.addItem(formEditProcess); + propertiesWindow.open(); + $(processOwner.createHTML()).insertBefore(dropCalendar.html); + processOwner.html.find("input").blur(function () { + if (!(processOwner.isValid())) { + processOwner.showMessageRequiredExtended(); + } else { + processOwner.repaint("1px solid #adafb2", "2px", "", "1px solid white"); + } + }); + processOwner.html.find("input").focusin(function () { + if (processOwner.isValid()) { + processOwner.repaint("1px solid #adafb2", "2px", "#000", "-webkit-focus-ring-color auto 1px"); + } + }); + processOwner.containerLabel.css({ width: "35%" }); + processOwner.repaint("1px solid #adafb2", "2px", "", ""); + formEditProcess.getField("pro_type_process").hideColon(); + formEditProcess.reset(); + responseProperties = response; + processUID.setValue(response.pro_uid); + processUID.setReadOnly(true); + textTitle.setValue(response.pro_title); + textDescription.setValue(response.pro_description); + processOwner.set("value", response.pro_create_user); + processOwner.html.find("input").val(response.pro_create_firstname + " " + response.pro_create_lastname + " " + "(" + response.pro_create_username + ")"); + dropDynaform.setValue(response.pro_summary_dynaform); + dropCaseCancelled.setValue(response.pro_tri_canceled); + dropCaseCreated.setValue(response.pro_tri_create); + dropCaseDeleted.setValue(response.pro_tri_deleted); + dropCasePaused.setValue(response.pro_tri_paused); + dropCaseUnpaused.setValue(response.pro_tri_unpaused); + dropCaseReassigned.setValue(response.pro_tri_reassigned); + dropCaseOpen.setValue(response.pro_tri_open); + dropRouting.setValue(response.pro_derivation_screen_tpl); + dropCalendar.setValue(response.pro_calendar); + dropProcessCat.setValue(response.pro_category); + dropTypeProcess.setValue(response.pro_type_process); + checkHideCase.setHeight(57) + if (response.pro_debug == 1) { + checkDebug.getControls()[0].select(); + } + if (response.pro_show_message == 1) { + checkHideCase.getControls()[0].select(); + } + if (response.pro_subprocess == 1) { + checkSubProcess.getControls()[0].select(); + } + proCost.setValue(response.pro_cost); + if (response.pro_unit_cost != null && response.pro_unit_cost != '') { + proUnitCost.setValue(response.pro_unit_cost); + } + }; + + getValuesProperties(); + + propertiesWindow.showFooter(); + propertiesWindow.defineEvents(); + applyStyleWindowForm(propertiesWindow); + formEditProcess.getField('pro_title').setFocus(); + formEditProcess.getField("pro_type_process").html.style.float = "left"; + + dropCaseCancelled.style.addProperties({"float": "left"}); + dropCasePaused.style.addProperties({"float": "left"}); + dropCaseUnpaused.style.addProperties({"float": "left"}); + dropCaseReassigned.style.addProperties({"float": "left"}); + dropCaseOpen.style.addProperties({"float": "left"}); + + $("#dropCaseCancelled,#dropCasePaused,#dropCaseReassigned,#dropTypeProcess,#dropCaseOpen").find("select:eq(0)").css("z-index", 1); + + if (window.enterprise === "1") { + proCost.setVisible(true); + proUnitCost.setVisible(true); + } else { + proCost.setVisible(false); + proUnitCost.setVisible(false); + } + }; + + }() +); +(function () { + PMDesigner.caseTracker = function () { + var caseTrackerForm, + index, + flagEdit = 0, + caseTrackerWindow, + dataCaseTracker, + dataTree, + conditionform, + conditionWindows, + disableAllItems, + formIsDirty, + conditionformIsDirty, + orderDataTree, + saveItem, + updateItem, + treePanelObjects, + loadGridCaseTacker, + editCondition, + gridPanelObjects, + titleTreeObjects, + getValuesCaseTrackerObjects, + updateCaseTrackerPropertiesAndObjects, + loadPropertiesCaseTracker, + titleGridObjects, + panelLabelObjects, + panelContainerObjects, + panelObjects, + applyStylesWindow, + showObjects, + arrayObjectDropAssignedObjects = new Array(), + arrayObjectAvailableObjects = new Array(), + arrayObjectStepsCaseTracker = new Array(); + + disableAllItems = function () { + caseTrackerWindow.getItems()[0].setVisible(false); + caseTrackerWindow.getItems()[1].setVisible(false); + caseTrackerWindow.hideFooter(); + }; + formIsDirty = function () { + if (caseTrackerForm.isDirty() || flagEdit == 1) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + caseTrackerWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + caseTrackerWindow.close(); + } + }; + + conditionformIsDirty = function () { + if (conditionform.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + conditionWindows.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + conditionWindows.close(); + } + + }; + orderDataTree = function (data) { + var items = []; + var type = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL_STEP']; + var label = ['Dynaform', 'Input Document', 'OutPut Document', 'External Step']; + for (var i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items + }); + } + } + }; + + //Properties + loadPropertiesCaseTracker = function () { + dataCaseTracker = []; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + dataCaseTracker = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + updateCaseTrackerPropertiesAndObjects = function (data) { + //save steps Objects Case Tracker + var i, j; + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = (typeof gridPanelObjects.getItems()[i].getData().cto_uid_obj != 'undefined') ? gridPanelObjects.getItems()[i].getData().cto_uid_obj : gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayObjectStepsCaseTracker.indexOf(idObject); + if (index <= -1) { + saveItem(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); + } + } + ; + for (i = 0; i < arrayObjectAvailableObjects.length; i += 1) { + for (j = 0; j < arrayObjectDropAssignedObjects.length; j += 1) { + index = (arrayObjectAvailableObjects[i] == arrayObjectDropAssignedObjects[j].cto_uid_obj) ? 0 : 1; + if (index == 0) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + arrayObjectDropAssignedObjects[j].cto_uid, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } + } + } + + //save Properties Case Tracker + data ['map_type'] = data ['map_type'] == '["1"]' ? "PROCESSMAP" : "NONE"; + data ['routing_history'] = data ['routing_history'] == '["1"]' ? 1 : 0; + data ['message_history'] = data ['message_history'] == '["1"]' ? 1 : 0; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + caseTrackerWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the Case Tracker, please try again.".translate(), + messageSuccess: 'Case Tracker updated successfully'.translate(), + flashContainer: document.body + }); + restClient.executeRestClient(); + }; + + caseTrackerForm = new PMUI.form.Form({ + id: 'caseTrackerForm', + fieldset: true, + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + height: 30, + layout: "hbox", + items: [ + { + pmType: "annotation", + text: "Display :".translate(), + id: "DisplayMessage", + name: "DisplayMessage" + }, + { + id: 'map_type', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Processmap'.translate(), + value: '1' + } + ] + }, + { + id: 'routing_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Routing History'.translate(), + value: '1' + } + ] + }, + { + id: 'message_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + id: 'message_history', + label: 'Messages'.translate(), + value: '1' + } + ] + } + ], + style: { + cssProperties: { + 'margin-bottom': '70px' + } + } + }); + + //objects + loadGridCaseTacker = function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + switch (data[i]['cto_type_obj']) { + case 'DYNAFORM': + label = 'Dynaform'.translate(); + break; + case 'INPUT_DOCUMENT': + label = 'Input Document'.translate(); + break; + case 'OUTPUT_DOCUMENT': + label = 'OutPut Document'.translate(); + break; + case 'EXTERNAL_STEP': + label = 'External Step'.translate(); + break; + default: + label = data[i]['tri_type']; + break; + } + data[i]['obj_label'] = label; + } + gridPanelObjects.setDataItems(data); + }; + + getValuesCaseTrackerObjects = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "case-tracker/available-objects", + "method": 'GET' + }, + { + "url": "case-tracker/objects", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + saveItem = function (rowStep) { + rowStep = rowStep.getData(); + data = { + "cto_type_obj": rowStep.obj_type, + "cto_uid_obj": rowStep.obj_uid, + "cto_condition": (typeof rowStep.cto_condition != 'undefined') ? rowStep.cto_condition : '', + "cto_position": rowStep.cto_position + }; + restClient = new PMRestClient({ + endpoint: 'case-tracker/object', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + data = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems saved, please try again.".translate() + }); + restClient.executeRestClient(); + return data; + }; + + updateItem = function (rowStep, i) { + rowStep = rowStep.getData(); + rowStep.cto_position = i + 1; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + rowStep.cto_uid, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true + } + }); + + editCondition = function () { + var visible, dataEdit; + + conditionform = new PMUI.form.Form({ + id: 'conditionform', + title: "", + fieldset: true, + visibleHeader: false, + width: 500, + items: [ + new CriteriaField({ + id: 'cto_condition', + pmType: 'textarea', + name: 'cto_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 200, + width: 250, + controlsWidth: 285, + renderType: 'textarea' + }) + ] + }); + + if (rowStep != '' && rowStep != undefined) { + dataEdit = conditionform.getFields(); + dataEdit[0].setValue(rowStep['cto_condition']); + } + + conditionWindows = new PMUI.ui.Window({ + id: 'conditionWindows', + title: 'Condition'.translate(), + width: 500, + height: 'auto', + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: conditionformIsDirty, + buttons: [ + { + id: 'conditionObjectWindowButtonClose', + text: "Cancel".translate(), + handler: conditionformIsDirty, + buttonType: 'error' + }, + { + id: 'conditionObjectWindowButtonSave', + text: "Save".translate(), + handler: function () { + var i, item; + if (conditionform.isValid()) { + idrowStep = (typeof rowStep.cto_uid_obj != 'undefined') ? rowStep.cto_uid_obj : rowStep.obj_uid; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + item = gridPanelObjects.getItems()[i].getData(); + idObj = (typeof item.cto_uid_obj != 'undefined') ? item.cto_uid_obj : item.obj_uid; + if (idObj == idrowStep) { + rowStep.cto_condition = conditionform.getData()['cto_condition']; + gridPanelObjects.getItems()[i].setData(rowStep); + break; + } + } + conditionWindows.close(); + } + }, + buttonType: 'success' + } + ] + }); + conditionWindows.addItem(conditionform); + conditionWindows.open(); + conditionWindows.showFooter(); + applyStyleWindowForm(conditionWindows); + conditionWindows.defineEvents(); + conditionWindows.footer.html.style.textAlign = 'right'; + conditionform.setFocus(); + style = $('#cto_condition .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#cto_condition .pmui-field-label').attr("style", style); + }; + + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + width: '640px', + style: {cssClasses: ['itemsSteps']}, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_label", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonProperties', + title: '', + dataType: 'button', + buttonLabel: "Condition".translate(), + iconPosition: "center", + buttonStyle: {cssClasses: ['mafe-button-editstep']}, + buttonTooltip: 'Edit Properties'.translate(), + onButtonClick: function (row, grid) { + rowStep = row.getData(); + editCondition(); + } + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + flagEdit = 1; + rowStep = row.getData(); + index = (row.getData().cto_uid_obj != 'undefined') ? arrayObjectStepsCaseTracker.indexOf(row.getData().cto_uid_obj) : arrayObjectStepsCaseTracker.indexOf(row.getData().obj_uid); + if (index > -1) { + arrayObjectAvailableObjects.push(row.getData().cto_uid_obj); + arrayObjectStepsCaseTracker.splice(index, 1); + } + objType = (typeof row.getData().cto_type_obj != 'undefined') ? row.getData().cto_type_obj : row.getData().obj_type; + grid.removeItem(row); + switch (objType) { + case 'DYNAFORM': + treePanelObjects.getItems()[0].addItem(row); + break; + case 'INPUT_DOCUMENT': + treePanelObjects.getItems()[1].addItem(row); + break; + case 'OUTPUT_DOCUMENT': + treePanelObjects.getItems()[2].addItem(row); + break; + case 'EXTERNAL_STEP': + treePanelObjects.getItems()[3].addItem(row); + break; + default: + break; + } + } + } + ], + onDrop: function (grid, item, index) { + flagEdit = 1; + if (item.data.customKeys.obj_uid === '') { + return false; + } + rowStep = item.getData(); + rowStep.cto_position = index + 1; + item.setData(rowStep); + + index = (typeof item.getData().cto_uid_obj != 'undefined') ? arrayObjectAvailableObjects.indexOf(item.getData().cto_uid_obj) : arrayObjectAvailableObjects.indexOf(item.getData().obj_uid); + + if (index > -1) { + itemPush = (typeof item.getData().cto_uid_obj != 'undefined') ? item.getData().cto_uid_obj : item.getData().obj_uid; + arrayObjectStepsCaseTracker.push(itemPush); + arrayObjectAvailableObjects.splice(index, 1); + } + }, + onSort: function (grid, item, index) { + rowStep = item.getData(); + } + }); + + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-steps-tree' + ] + } + }); + + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-stesp-grid' + ] + } + }); + + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 4, + 'margin-top': 4, + 'margin-left': 4 + } + }, + layout: "hbox" + }); + + panelContainerObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 320, + fieldset: true, + items: [ + treePanelObjects, + gridPanelObjects + ], + layout: "hbox" + }); + + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: DEFAULT_WINDOW_HEIGHT * 0.70, + fieldset: true, + items: [ + panelLabelObjects, + panelContainerObjects + ], + layout: "vbox" + }); + + caseTrackerWindow = new PMUI.ui.Window({ + id: 'caseTrackerWindow', + title: "Case Tracker".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: "bottom", + onBeforeClose: formIsDirty, + visibleFooter: false, + footerAling: "right", + footerItems: [{ + id: 'btnCloseCaseTracker', + text: 'Cancel'.translate(), + buttonType: "error", + handler: formIsDirty + }, + { + id: 'btnSaveCaseTracker', + text: "Save".translate(), + buttonType: "success", + handler: function () { + if (caseTrackerForm.isValid()) { + data = caseTrackerForm.getData(); + updateCaseTrackerPropertiesAndObjects(data); + } + } + } + ], + spaceButtons: 30 + }); + + caseTrackerWindow.addItem(caseTrackerForm); + caseTrackerWindow.addItem(panelObjects); + caseTrackerWindow.open(); + caseTrackerWindow.showFooter(); + applyStyleWindowForm(caseTrackerWindow); + caseTrackerWindow.defineEvents(); + caseTrackerWindow.footer.html.style.textAlign = 'right'; + caseTrackerForm.setFocus(); + + applyStylesWindow = function () { + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': 'auto'}); + $('#caseTrackerForm :eq(2)').css({'padding': '0px 10px 0px 10px'}); + $('#caseTrackerForm :eq(0)').remove(); + items = caseTrackerWindow.getItems()[0].getItems(); + $(items[1].getHTML()).find('table').css('border', 'none'); + $(items[2].getHTML()).find('table').css('border', 'none'); + $(items[3].getHTML()).find('table').css('border', 'none'); + }; + + showObjects = function () { + disableAllItems(); + + loadPropertiesCaseTracker(); + caseTrackerWindow.getItems()[0].setVisible(true); + caseTrackerWindow.showFooter(); + caseTrackerWindow.setTitle("Case Tracker Properties".translate()); + + if (dataCaseTracker != '') { + var dataEdit = caseTrackerForm.getFields(); + dataEdit[1].setValue((dataCaseTracker['map_type'] == 'PROCESSMAP') ? '["1"]' : '[]'); + dataEdit[2].setValue((dataCaseTracker['routing_history'] == 1) ? '["1"]' : '[]'); + dataEdit[3].setValue((dataCaseTracker['message_history'] == 1) ? '["1"]' : '[]'); + } + + + getValuesCaseTrackerObjects(); + caseTrackerWindow.getItems()[1].setVisible(true); + caseTrackerWindow.setTitle("Case Tracker".translate()); + + caseTrackerWindow.body.style.overflow = 'initial'; + + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(640); + gridPanelObjects.setHeight(270); + applyStylesWindow(); + treePanelObjects.style.addProperties({float: 'left'}); + treePanelObjects.style.addProperties({overflow: 'auto'}); + treePanelObjects.setWidth(200); + treePanelObjects.setHeight(270); + + applyStyleTreePanel(treePanelObjects); + + panelLabelObjects.setHeight(15); + caseTrackerWindow.defineEvents(); + + caseTrackerWindow.setBodyPadding(5); + + panelObjects.style.addProperties({marginLeft: '15px'}); + for (var i = 0; i < gridPanelObjects.getItems().length; i += 1) { + arrayObjectStepsCaseTracker[i] = gridPanelObjects.getItems()[i].getData().cto_uid_obj; + arrayObjectDropAssignedObjects[i] = gridPanelObjects.getItems()[i].getData(); + } + }; + showObjects(); + }; + + PMDesigner.caseTracker.showObjects = function () { + PMDesigner.caseTracker(); + }; + +}()); +PMDesigner.gatewayProperties = function (gateway) { + if (gateway.getGatewayType() !== "PARALLEL") { + PMDesigner.RoutingRule(gateway); + } +}; + +PMDesigner.RoutingRule = function (shape) { + var formRoutingRule, + formPanelSelected, + arrayShapeIdRemoved = [], + buttonAdd, + windowConnections, + warningMessageWindowDelete, + warningMessageWindowDirty, + containerLabels, + deleteButton, + buttonSave, + buttonCancel, + labelNextTask, + labelCondition, + typeShapeValueText, + dataRouteGroup = [], + arrayElementName = [], + availableShapes = []; + + warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDelete', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Do you want to delete this routing rule?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, + { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteRow(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowConnections.close(); + }, + buttonType: "success" + } + ] + }); + + buttonAdd = new PMUI.ui.Button({ + id: 'routingRuleButtonAdd', + text: 'Add Routing Rule'.translate(), + style: { + cssProperties: { + marginLeft: '50px', + marginTop: '10px', + marginBottom: '10px', + padding: "5px" + } + }, + buttonType: 'success', + handler: function () { + // to add a new row + addRow(); + enableSorting(); + } + }); + buttonSave = new PMUI.ui.Button({ + id: 'windowConnectionsButtonSave', + text: 'Save'.translate(), + handler: function () { + //validate routing rules form + if (isValidRoutingRules()) { + //remove all flows an get points + var allPoints = removeConnectionsIntoCanvas(); + saveConnections(allPoints); + } + + }, + buttonType: 'success' + }); + buttonCancel = new PMUI.ui.Button({ + id: 'windowConnectionsButtonCancel', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + if (formRoutingRule.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowConnections.close(); + } + } + }); + + labelNextTask = new PMUI.ui.TextLabel({ + text: 'Next Task'.translate() + }); + labelNextTask.setWidth(382); + labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + + labelCondition = new PMUI.ui.TextLabel({ + text: 'Condition'.translate() + }); + labelCondition.setWidth(410); + labelCondition.style.addProperties({padding: '5px 0px 0px 5px'}); + labelCondition.style.addProperties({marginLeft: '31%'}); + + containerLabels = new PMUI.core.Panel({ + layout: 'hbox', + width: 'auto', + height: 29, + style: { + cssProperties: { + 'border-bottom': '1px solid #c0c0c0' + } + } + }); + containerLabels.addItem(labelNextTask); + containerLabels.addItem(labelCondition); + containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + + formRoutingRule = new PMUI.form.Form({ + id: 'formRoutingRule', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + height: 'auto', + items: [], + style: { + cssProperties: { + 'margin-left': '35px' + } + } + }); + formRoutingRule.hideFooter(); + + windowConnections = new PMUI.ui.Window({ + id: 'windowConnections', + title: 'Routing Rule'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + buttonPanelPosition: 'bottom', + items: [ + buttonAdd + ], + buttons: [ + buttonCancel, + buttonSave + ] + }); + + typeShapeValueText = (shape.gat_type === 'EXCLUSIVE') ? 'EXCLUSIVE'.translate() : 'INCLUSIVE'.translate(); + windowConnections.setTitle('Routing Rule'.translate() + ' - ' + typeShapeValueText); + windowConnections.showFooter(); + windowConnections.addItem(containerLabels); + if (formRoutingRule.dirty === null) { + formRoutingRule.dirty = false; + } + windowConnections.addItem(formRoutingRule); + windowConnections.open(); + + loadConnections(); + enableSorting(); + /** + * add a new row + * @returns {PMUI.form.FormPanel|*} + */ + function addRow() { + var dropDownControl, + criteriaField, + deleteButton, + newRow, + max, + i; + newRow = new PMUI.form.FormPanel({ + layout: 'hbox' + }); + + dropDownControl = new PMUI.field.DropDownListField({ + id: 'dropdownNextTask', + name: 'act_name', + valueType: 'string', + label: 'Next Task'.translate(), + labelPosition: 'top', + labelVisible: false, + value: '', + readOnly: false, + controlsWidth: 360, + proportion: 0.9, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + criteriaField = new CriteriaField({ + id: 'textCondition', + pmType: 'text', + renderType: 'textarea', + name: 'flo_condition', + valueType: 'string', + label: 'Condition'.translate(), + labelPosition: 'top', + labelVisible: false, + controlsWidth: 345, + required: false, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + deleteButton = new PMUI.field.ButtonField({ + id: 'buttonDelete', + value: 'Delete'.translate(), + handler: function (e, a) { + formPanelSelected = this.getParent(); + warningMessageWindowDelete.open(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; + warningMessageWindowDelete.showFooter(); + enableSorting(); + }, + name: 'delete', + labelVisible: false, + buttonAling: 'left', + controlsWidth: 60, + proportion: 0.1, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + newRow.addItem(dropDownControl); + newRow.addItem(criteriaField); + newRow.addItem(deleteButton); + loadOptions(dropDownControl); + //apply styles; + if (availableShapes && availableShapes.length > 0) { + deleteButton.controls[0].button.setButtonType('error'); + $(deleteButton.getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(newRow); + for (i = 0, max = formRoutingRule.getItems().length; i < max; i += 1) { + formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); + } + dropDownControl.dom.labelTextContainer.style.display = 'none'; + criteriaField.dom.labelTextContainer.style.display = 'none'; + criteriaField.setValue(true); + } else { + PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer, 'error'); + } + return newRow; + } + + function loadOptions(dropdown) { + var i, + customShapes, + element, + nameGroup, + evnLabelMap; + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + dropdown.clearOptions(); + dropdown.setUID = function (uid) { + this.uid = uid; + }; + dropdown.getUID = function () { + return this.uid; + }; + dropdown.addOptionGroup({ + label: 'Task'.translate(), + selected: true, + options: [] + }); + dropdown.addOptionGroup({ + label: 'Sub-process'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Event'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Gateway'.translate(), + options: [] + }); + customShapes = PMUI.getActiveCanvas().getCustomShapes(); + + for (i = 0; i < customShapes.getSize(); i += 1) { + element = customShapes.get(i); + // verify pool and participant + if (element.getType() !== 'PMParticipant' && element.getType() !== 'PMPool') { + //itself verify and same parent + if (shape.getID() !== element.getID() + && element.businessObject + && shape.businessObject + && shape.businessObject.elem.$parent + && element.businessObject.elem.$parent + && element.businessObject.elem.$parent.id === shape.businessObject.elem.$parent.id) { + switch (element.type) { + case 'PMActivity': + nameGroup = element.act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); + dropdown.addOption({ + value: element.act_uid, + label: element.act_name + }, nameGroup); + arrayElementName[element.act_uid] = element.act_name; + availableShapes.push(element); + break; + case 'PMEvent': + evnLabelMap = { + 'END': 'End Event'.translate(), + 'INTERMEDIATE': 'Intermediate Event'.translate() + }; + + if (element.evn_type !== 'START') { + dropdown.addOption({ + value: element.evn_uid, + label: element.evn_name || evnLabelMap[element.evn_type] + }, 'Event'.translate()); + + arrayElementName[element.evn_uid] = element.evn_name || evnLabelMap[element.evn_type]; + availableShapes.push(element); + } + break; + case 'PMGateway': + dropdown.addOption({ + value: element.gat_uid, + label: element.gat_name || 'Gateway'.translate() + }, 'Gateway'); + arrayElementName[element.gat_uid] = element.gat_name || 'Gateway'.translate(); + availableShapes.push(element); + break; + } + } + } + } + } + + function removeConnectionsIntoCanvas() { + var shapeDest, connection, dt, allPoints = {}, i, j; + for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', arrayShapeIdRemoved[j]); + dt = shape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() === connection.getSrcPort().getParent().getID() && + shapeDest.getID() === connection.getDestPort().getParent().getID()) { + //caching points + allPoints[shapeDest.getID()] = getPoints(connection); + removeConnection(connection); + + break; + } + } + } + arrayShapeIdRemoved = []; + return allPoints; + } + + /** + * to remove a individual connection and getting points + * @param connection + */ + function removeConnection(connection) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().executeCommandDelete(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + } + + /** + * gets conenctions inital and final points + * @param connection + */ + function getPoints(connection) { + var result = []; + result[0] = connection.points[0]; + result[1] = connection.points[connection.points.length - 1]; + return result; + } + + + function editAllConnections(connArray) { + var i, + elem, + canvas = PMUI.getActiveCanvas(); + for(i = 0; i < connArray.length; i += 1) { + elem = connArray[i]; + if (elem && elem.connection) { + elem.oldShapeDest.removePort(elem.connection.destPort); + elem.shapeDest.addPort(elem.connection.destPort, 100, 100, + false, elem.connection.srcPort); + + elem.connection.lineSegments.clear(); + canvas.commandStack.add(new PMUI.command.CommandConnect(elem.connection)); + elem.connection.connect(); + canvas.triggerPortChangeEvent(elem.connection.destPort); + } + } + } + + + function createEndShape() { + var customShape, canvas = PMUI.getActiveCanvas(), command, x, y; + customShape = canvas.shapeFactory('END'); + + x = shape.getX() + shape.getWidth(); + y = shape.getY() + shape.getHeight() + 20; + + canvas.addElement(customShape, x, y, + customShape.topLeftOnCreation); + + //since it is a new element in the designer, we triggered the + //custom on create element event + canvas.updatedElement = customShape; + + // create the command for this new shape + command = new PMUI.command.CommandCreate(customShape); + canvas.commandStack.add(command); + command.execute(); + return customShape; + } + + /** + * new method to validate routing rules + * @returns {boolean} + */ + function isValidRoutingRules() { + var result = true, + arrayAux = [], + i, + max, + id, + dt = formRoutingRule.getItems(); + if (!formRoutingRule.isValid()) { + result = false; + return; + } + + for (i = 0, max = dt.length; i < max; i += 1) { + id = dt[i].getField("act_name").getValue(); + if (typeof(arrayAux[id]) === "undefined") { + arrayAux[id] = "1"; + } else { + result = false; + PMDesigner.msgWinError("The routing rule to \"{0}\" already exists".translate([arrayElementName[id]])); + return; + } + } + return result; + } + + function saveConnections(allPoints) { + var dt = formRoutingRule.getItems(), + id, + i, + oldId, + shapeDest, + oldShapeDest, + connection, + newConnection, + dataRouteAll, + dataRoute, + restClient, + newPoints, + conectionsArray = []; + + + for (i = 0; i < dt.length; i += 1) { + id = dt[i].getField('act_name').getValue(); + oldId = dt[i].getField('act_name').getUID(); + if (id !== '0') { + dataRouteGroup.push(id); + if (dt[i].getField('flo_condition').getValue() == "") { + dt[i].getField('flo_condition').setValue(true); + } + if (oldId === undefined) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + //getting current connection + + newPoints = allPoints[id]; + + newConnection = createConnection(shape, shapeDest, newPoints); + newConnection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id === oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id !== oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + oldShapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', oldId); + connection = isConnection(shape, oldShapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + conectionsArray.push({ + "connection" : isConnection(shape, oldShapeDest) || null, + "shapeDest": shapeDest, + "oldShapeDest": oldShapeDest + }); + } + } else { + var customShape = createEndShape(); + createConnection(shape, customShape); + } + } + editAllConnections(conectionsArray); + + /*update routing order*/ + dataRouteAll = []; + for (i = 0; i < dataRouteGroup.length; i += 1) { + dataRoute = { + 'rou_case': parseInt(i) + 1, + 'rou_next_task': dataRouteGroup[i], + 'pro_uid': PMDesigner.project.id + }; + dataRouteAll.push(dataRoute); + } + restClient = new PMRestClient({ + endpoint: 'update-route-order', + typeRequest: 'update', + data: dataRouteAll, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the routing rule, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + /*end update routing order*/ + + windowConnections.close(); + PMDesigner.msgFlash('Saved correctly'.translate(), document.body); + PMDesigner.project.dirty = true; + PMDesigner.project.setDirty(true); + } + + function createConnection(sourceShape, shape, points) { + var sourcePort, endPort, connection, canvas = PMUI.getActiveCanvas(), points; + sourcePort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + endPort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + if (!points) { + points = findBestPorts(sourceShape, shape); + } + sourceShape.addPort(sourcePort, points[0].x - sourceShape.getZoomX(), points[0].y - sourceShape.getZoomY()); + shape.addPort(endPort, points[1].x - shape.getZoomX(), points[1].y - shape.getZoomY(), false, sourcePort); + + //add ports to the canvas array for regularShapes + //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); + //create the connection + connection = new PMFlow({ + srcPort: sourcePort, + destPort: endPort, + segmentColor: new PMUI.util.Color(0, 0, 0), + name: '', + canvas: shape.canvas, + segmentStyle: shape.connectionType.segmentStyle, + flo_type: shape.connectionType.type + }); + connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' + && shape.connectionType.srcDecorator !== null) ? + shape.connectionType.srcDecorator : 'mafe-sequence', + decoratorType: 'source', + parent: connection + })); + connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' + && shape.connectionType.destDecorator !== null) ? + shape.connectionType.destDecorator : 'mafe-sequence', + decoratorType: 'target', + parent: connection + })); + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + + //connect the two ports + connection.connect(); + connection.setSegmentMoveHandlers(); + + //add the connection to the canvas, that means insert its html to + // the DOM and adding it to the connections array + canvas.addConnection(connection); + + // Filling PMFlow fields + connection.setTargetShape(endPort.parent); + connection.setOriginShape(sourcePort.parent); + connection.savePoints(); + + // now that the connection was drawn try to create the intersections + connection.checkAndCreateIntersectionsWithAll(); + + //attaching port listeners + sourcePort.attachListeners(sourcePort); + endPort.attachListeners(endPort); + + // finally trigger createEvent + canvas.triggerCreateEvent(connection, []); + connection.flo_state = connection.points; + return connection; + } + + function findBestPorts(sourceShape, shape) { + var result = [], i, j, + distance = 99999999, + initPoint, + secondPoint, + midPoints = getMiddlePoints(sourceShape), + midPoints2 = getMiddlePoints(shape); + for (i = 0; i < midPoints.length; i += 1) { + initPoint = midPoints[i]; + for (j = 0; j < midPoints2.length; j += 1) { + secondPoint = midPoints2[j]; + if (distance > initPoint.getManhattanDistance(secondPoint)) { + distance = initPoint.getManhattanDistance(midPoints2[j]); + result[0] = (initPoint); + result[1] = (midPoints2[j]); + } + } + } + return result; + } + + function getMiddlePoints(shape) { + return [ + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), 0 + shape.getZoomY()), // TOP + new PMUI.util.Point(shape.zoomWidth + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()), // RIGHT + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), shape.zoomHeight + shape.getZoomY()), // BOTTOM + new PMUI.util.Point(0 + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()) // LEFT + ]; + } + + function loadConnections() { + var row, connection, dt = shape.getPorts().asArray(), + i, j; + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID() && shape.gat_default_flow !== connection.flo_uid) { + row = addRow(); + row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); + row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); + row.getField('flo_condition').setValue(connection.getFlowCondition()); + + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + } + } + } + + function isConnection(sourceShape, shape) { + var connection, + i, + dt = sourceShape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && + shape.getID() === connection.getDestPort().getParent().getID()) { + return connection; + } + } + return false; + } + + function deleteRow() { + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); + } + + function enableSorting() { + var index = 0, + div = $(formRoutingRule.getHTML()).find(">div:nth-child(2)").css({"overflow": "initial"}); + div.sortable({ + items: '>div', + placeholder: 'steps-placeholder', + cursor: "move", + change: function (event, ui) { + index = ui.placeholder.index(); + }, + start: function (event, ui) { + }, + stop: function (event, ui) { + var dt = [], + row, + formPanelSelected, + id, + i, + j, + shapeDest, + connection; + + ui.item.parent().find(">div").each(function (i, e) { + dt.push(PMUI.getPMUIObject(e)); + }); + for (i = 0; i < dt.length; i += 1) { + formPanelSelected = dt[i]; + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + } + for (i = 0; i < dt.length; i += 1) { + row = addRow(); + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + row.getField('act_name').setValue(dt[i].getField('act_name').getValue()); + row.getField('flo_condition').setValue(dt[i].getField('flo_condition').getValue()); + id = dt[i].getField('act_name').getValue(); + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + } + enableSorting(); + } + }); + } +}; + +PMDesigner.RoutingRuleDeleteAllFlow = function (shape) { + var warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + id: 'warningMessageWindowDelete', + message: 'Do you want to delete all routing rules?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteAllConnection(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + + function deleteAllConnection() { + var connection, elements = [], + i, + sw, + msg, + ports; + PMUI.getActiveCanvas().emptyCurrentSelection(); + //IMPORTANT: You must empty elements in another array due to the array reference indices managed. + //referer: PMDesigner.canvas.removeConnection & element.getPorts().asArray() + + ports = shape.getPorts().asArray(); + for (i = 0; i < ports.length; i += 1) { + elements.push(ports[i]); + } + sw = false; + for (i = 0; i < elements.length; i += 1) { + connection = elements[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID()) { + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().removeElements(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + sw = true; + } + } + msg = sw ? 'Routing rules deleted successfully' : 'There aren\'t routing rules'; + PMDesigner.msgFlash(msg.translate(), document.body); + } + + warningMessageWindowDelete.open(); + warningMessageWindowDelete.showFooter(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; +}; + +PMDesigner.RoutingRuleSetOrder = function (diagram) { + var restClient = new PMRestClient({ + endpoint: 'update-route-order-from-project', + typeRequest: 'update', + data: {}, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + } + }); + restClient.executeRestClient(); +}; +PMDesigner.dynaformDesigner = function (data) { + var old = PMUI.activeCanvas, a; + PMUI.activeCanvas = false; + a = new FormDesigner.main.Designer(data); + a.show(); + a.onHide = function () { + PMUI.activeCanvas = old; + }; + return a; +}; + +PMDesigner.complexRoutingRule = function (shape) { + var formRoutingRule, + formPanelSelected, + arrayShapeIdRemoved = [], + buttonAdd, + windowConnections, + warningMessageWindowDelete, + containerLabels, + buttonSave, + buttonCancel, + labelNextTask, + labelCondition, + warningMessageWindowDirty, + deleteButton; + + //Window + //button add routing rule + buttonAdd = new PMUI.ui.Button({ + id: 'routingRuleButtonAdd', + text: 'Add Routing Rule'.translate(), + style: { + cssProperties: { + marginLeft: '50px', + marginTop: '10px', + marginBottom: '10px', + fontSize: '16px' + } + }, + buttonType: 'success', + height: 31, + handler: function () { + var item, btnDel; + if (countActivities() > 0) { + item = addRow(); + item.getItems()[2].style.addProperties({display: 'none'}); + item.getItems()[2].controls[0].button.setButtonType('error'); + formRoutingRule.addItem(item); + for (var i = 0; i < formRoutingRule.getItems().length; i += 1) { + //formRoutingRule.getItems()[i].style.addProperties({'box-sizing': 'initial'}); + //item.style.addProperties({padding : 'initial'}); + formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); + } + item.getItems()[0].dom.labelTextContainer.style.display = "none"; + item.getItems()[1].dom.labelTextContainer.style.display = "none"; + + } else { + PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer); + } + } + }); + //button Save + buttonSave = new PMUI.ui.Button({ + id: 'windowConnectionsButtonSave', + text: 'Apply'.translate(), + handler: function () { + removeConnectionsIntoCanvas(); + saveConnections(); + }, + buttonType: 'success', + height: 31 + }); + //Button cancel + buttonCancel = new PMUI.ui.Button({ + id: 'windowConnectionsButtonCancel', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + if (formRoutingRule.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowConnections.close(); + } + } + }); + + windowConnections = new PMUI.ui.Window({ + id: 'windowConnections', + title: 'Routing Rule'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + buttonPanelPosition: 'top', + items: [ + buttonAdd + ], + buttons: [ + buttonCancel, + buttonSave + ] + }); + windowConnections.showFooter(); + //END WINDOW + + containerLabels = new PMUI.core.Panel({ + layout: 'hbox', + width: 'auto', + height: 29, + style: { + cssProperties: { + 'border-bottom': '1px solid #c0c0c0' + } + } + }); + + labelNextTask = new PMUI.ui.TextLabel({ + text: 'Next Task'.translate(), + style: { + cssProperties: { + 'font-weight': 'bold' + } + } + }); + + labelCondition = new PMUI.ui.TextLabel({ + text: 'Description'.translate(), + style: { + cssProperties: { + 'font-weight': 'bold' + } + } + }); + + containerLabels.addItem(labelNextTask); + containerLabels.addItem(labelCondition); + + windowConnections.addItem(containerLabels); + + formRoutingRule = new PMUI.form.Form({ + id: 'formRoutingRule', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + height: 'auto', + items: [], + style: { + cssProperties: { + 'margin-left': '35px' + } + } + }); + + warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDelete', + windowMessageType: 'warning', + width: 490, + title: "Routing Rule".translate(), + bodyHeight: 'auto', + message: 'Do you want to delete this routing rule?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteRow(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Routing Rule".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + }, + buttonType: "error" + }, + { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowConnections.close(); + }, + buttonType: "success" + } + ] + }); + + //main + formRoutingRule.hideFooter(); + windowConnections.addItem(formRoutingRule); + windowConnections.open(); + labelNextTask.setWidth(382); + labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + labelCondition.setWidth(410); + labelCondition.style.addProperties({padding: '5px 0px 0px 0px'}); + containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + windowConnections.setTitle('Routing Rule'.translate() + ' - ' + ((shape.gat_type === 'COMPLEX') ? 'Exclusive (Manual)'.translate() : shape.gat_type)); + loadConnections(); + + function countActivities() { + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + var n = 0, i, dt; + dt = PMDesigner.project.getDirtyObject().diagrams[0].activities; + for (i = 0; i < dt.length; i += 1) { + n = n + 1; + } + + dt = PMDesigner.project.getDirtyObject().diagrams[0].events; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].evn_type !== 'START') { + n = n + 1; + } + } + return n; + } + + function addRow() { + + var dropDownControl, description, deleteButton, newRow; + + newRow = new PMUI.form.FormPanel({ + layout: 'hbox' + }); + + dropDownControl = new PMUI.field.DropDownListField({ + id: 'dropdownNextTask', + name: 'act_name', + valueType: 'string', + label: 'Next Task'.translate(), + labelPosition: 'top', + labelVisible: false, + value: '', + readOnly: true, + controlsWidth: 360, + proportion: 1.1, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + description = new PMUI.field.TextField({ + id: 'textCondition', + pmType: 'text', + name: 'flo_description', + valueType: 'string', + label: 'Description'.translate(), + labelPosition: 'top', + labelVisible: false, + controlsWidth: 320, + required: true, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + deleteButton = new PMUI.field.ButtonField({ + id: 'buttonDelete', + value: 'Delete'.translate(), + handler: function (e, a) { + var i; + for (i = 0; i < formRoutingRule.getItems().length; i += 1) { + if (formRoutingRule.getItems()[i].getItems()[2].controls[0].button.id == this.id) { + formPanelSelected = formRoutingRule.getItems()[i]; + warningMessageWindowDelete.open(); + warningMessageWindowDelete.dom.titleContainer.style.height = "17px"; + warningMessageWindowDelete.showFooter(); + } + } + + }, + name: 'delete', + labelVisible: false, + buttonAling: 'left', + controlsWidth: 100, + proportion: 0.3, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + newRow.addItem(dropDownControl); + newRow.addItem(description); + newRow.addItem(deleteButton); + loadActivities(dropDownControl); + return newRow; + } + + function loadActivities(dropdown) { + var i, dt; + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + dropdown.clearOptions(); + dropdown.setUID = function (uid) { + this.uid = uid; + }; + dropdown.getUID = function () { + return this.uid; + }; + dropdown.addOptionGroup({ + label: 'Task'.translate(), + selected: true, + options: [] + }); + dropdown.addOptionGroup({ + label: 'Sub-process'.translate(), + options: [] + }); + dt = PMDesigner.project.getDirtyObject().diagrams[0].activities, nameGroup; + dt = dt.sort(function (a, b) { + return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); + }); + for (i = 0; i < dt.length; i += 1) { + nameGroup = dt[i].act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); + dropdown.addOption({ + value: dt[i].act_uid, + label: dt[i].act_name + }, nameGroup); + } + + dropdown.addOptionGroup({ + label: 'End of process'.translate(), + options: [] + }); + dt = PMDesigner.project.getDirtyObject().diagrams[0].events; + dt = dt.sort(function (a, b) { + return a.evn_name.toString().toLowerCase() > b.evn_name.toString().toLowerCase(); + }); + for (i = 0; i < dt.length; i += 1) { + if (dt[i].evn_type !== 'START') { + dropdown.addOption({ + value: dt[i].evn_uid, + label: dt[i].evn_name + }, 'End of process'.translate()); + } + } + } + + function removeConnectionsIntoCanvas() { + var shapeDest, connection, dt, i, j; + for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { + shapeDest = getShapeForId(arrayShapeIdRemoved[j]); + dt = shape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() === connection.getSrcPort().getParent().getID() && + shapeDest.getID() === connection.getDestPort().getParent().getID()) { + PMDesigner.canvas.emptyCurrentSelection(); + PMDesigner.canvas.setCurrentConnection(connection); + PMDesigner.canvas.removeElements(); + connection.saveAndDestroy(); + PMDesigner.canvas.removeConnection(connection); + break; + } + } + } + arrayShapeIdRemoved = []; + } + + function editShapeDestConnection(shapeDest, oldShape) { + var connection, canvas = PMDesigner.canvas; + connection = isConnection(shape, oldShape); + oldShape.removePort(connection.destPort); + shapeDest.addPort(connection.destPort, 100, 100, + false, connection.srcPort); + + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + connection.connect(); + canvas.triggerPortChangeEvent(connection.destPort); + } + + function createEndShape() { + var customShape, canvas = PMDesigner.canvas, command, x, y; + customShape = canvas.shapeFactory('END'); + + x = shape.getX() + shape.getWidth(); + y = shape.getY() + shape.getHeight() + 20; + + canvas.addElement(customShape, x, y, + customShape.topLeftOnCreation); + + //since it is a new element in the designer, we triggered the + //custom on create element event + canvas.updatedElement = customShape; + + // create the command for this new shape + command = new PMUI.command.CommandCreate(customShape); + canvas.commandStack.add(command); + command.execute(); + return customShape; + } + + function saveConnections() { + var dt, i; + if (!formRoutingRule.isValid()) { + return; + } + dt = formRoutingRule.getItems(), id, oldId, shapeDest, oldShapeDest, connection; + for (i = 0; i < dt.length; i += 1) { + id = dt[i].getField('act_name').getValue(); + oldId = dt[i].getField('act_name').getUID(); + if (id !== '0') { + if (oldId === undefined) { + shapeDest = getShapeForId(id); + createConnection(shape, shapeDest).setFlowCondition(dt[i].getField('flo_description').getValue()); + } + if (oldId !== undefined && id === oldId) { + shapeDest = getShapeForId(id); + connection = isConnection(shape, shapeDest); + $a = connection; + connection.setFlowCondition(dt[i].getField('flo_description').getValue()); + } + if (oldId !== undefined && id !== oldId) { + shapeDest = getShapeForId(id); + oldShapeDest = getShapeForId(oldId); + connection = isConnection(shape, oldShapeDest); + connection.setFlowCondition(dt[i].getField('flo_description').getValue()); + editShapeDestConnection(shapeDest, oldShapeDest); + } + } else { + var customShape = createEndShape(); + createConnection(shape, customShape); + } + } + windowConnections.close(); + PMDesigner.msgFlash('Saved correctly'.translate(), document.body); + PMDesigner.project.dirty = true; + } + + function getShapeForId(id) { + var dt = PMDesigner.canvas.getChildren().asArray(), i; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].act_uid === id || dt[i].evn_uid === id) { + return dt[i]; + } + } + return null; + } + + function createConnection(sourceShape, shape) { + //referer to /processmaker/vendor/colosa/MichelangeloFE/src/connectiondrop.js + //method PMConnectionDropBehavior.prototype.onDrop + var sourcePort, endPort, connection, canvas = PMDesigner.canvas; + sourcePort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + endPort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + + sourceShape.addPort(sourcePort, 100, 100); + shape.addPort(endPort, 100, 100, + false, sourcePort); + + //add ports to the canvas array for regularShapes + //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); + //create the connection + connection = new PMFlow({ + srcPort: sourcePort, + destPort: endPort, + segmentColor: new PMUI.util.Color(92, 156, 204), + name: "", + canvas: shape.canvas, + segmentStyle: shape.connectionType.segmentStyle, + flo_type: shape.connectionType.type + }); + connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' + && shape.connectionType.srcDecorator !== null) ? + shape.connectionType.srcDecorator : "mafe-sequence", + decoratorType: "source", + parent: connection + })); + connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' + && shape.connectionType.destDecorator !== null) ? + shape.connectionType.destDecorator : "mafe-sequence", + decoratorType: "target", + parent: connection + })); + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + + //connect the two ports + connection.connect(); + connection.setSegmentMoveHandlers(); + + //add the connection to the canvas, that means insert its html to + // the DOM and adding it to the connections array + canvas.addConnection(connection); + + // Filling PMFlow fields + connection.setTargetShape(endPort.parent); + connection.setOriginShape(sourcePort.parent); + connection.savePoints(); + + // now that the connection was drawn try to create the intersections + connection.checkAndCreateIntersectionsWithAll(); + + //attaching port listeners + sourcePort.attachListeners(sourcePort); + endPort.attachListeners(endPort); + + // finally trigger createEvent + canvas.triggerCreateEvent(connection, []); + return connection; + } + + function loadConnections() { + var row, connection, dt = shape.getPorts().asArray(), i, j; + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID()) { + row = addRow(); + row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); + row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); + row.getField('flo_description').setValue(connection.getFlowCondition()); + + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = "none"; + row.getItems()[1].dom.labelTextContainer.style.display = "none"; + } + } + } + + function isConnection(sourceShape, shape) { + var connection, dt, i; + dt = sourceShape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && + shape.getID() === connection.getDestPort().getParent().getID()) { + return connection; + } + } + return false; + } + + function deleteRow() { + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); + } + +}; + +var PMVariables = function (options) { + var that = this; + this.initialFormAcceptedValuesKeyValue = null; + this.initialFormAcceptedValuesValue = null; + this.initialGridAcceptedValuesOrder = []; + this.validateAcceptedValuesFlag = false; + this.var_uid = null; + this.var_name = null; + this.edit = false; + this.editRow = null; + this.dirtyAcceptedValue = false; + this.fieldInfo = null; + this.onSave = new Function(); + this.onEdit = new Function(); + this.clickedClose = true; + this.editingOptions = false; + this.editRow = null; + this.currentVariable = null; + this.onWindowClose = new Function(); + this.buttonCreate = new PMUI.ui.Button({ + id: 'buttonCreate', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + + }, + handler: function () { + that.showForm(); + } + }); + + this.buttonCreateInputDocument = new PMUI.field.ButtonField({ + id: 'buttonCreateInputDocument', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + proportion: 0.8, + handler: function (field) { + var inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.method = "POST"; + } + }); + + this.buttonEditInputDocument = new PMUI.field.ButtonField({ + id: 'buttonEditInputDocument', + value: 'Edit'.translate(), + labelVisible: false, + buttonAlign: 'center', + proportion: 0.8, + handler: function (field) { + var form = that.formVariables, + fieldInpDoc = form.getField('inp_doc_uid'), + inp_doc_uid = fieldInpDoc.getValue(), + defaultText = "- Select an input document -".translate(), + inputDocument; + if (inp_doc_uid && inp_doc_uid !== defaultText) { + inputDocument = new InputDocument(); + inputDocument.build(); + inputDocument.inputDocumentOriginDataForUpdate = {}; + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(inp_doc_uid); + } else { + fieldInpDoc.setValue(""); + form.isValid(); + } + } + }); + + that.buttonCreateInputDocument.controls[0].button.setButtonType("success"); + that.buttonCreateInputDocument.controls[0].button.setStyle({ + cssClasses: ["mafe-button-create-variable", "pmui-success"], + cssProperties: {padding: "8px 15px", border: "0px"} + }); + that.buttonEditInputDocument.controls[0].button.setButtonType("success"); + that.buttonEditInputDocument.controls[0].button.setStyle({ + cssClasses: ["mafe-button-edit-variable", "pmui-success"], + cssProperties: {padding: "8px 15px", border: "0px"} + }); + + var inp_doc_uid = new PMUI.field.DropDownListField({ + id: "inp_doc_uid", + name: "inp_doc_uid", + value: "", + required: true, + label: "Related Input Document".translate(), + controlsWidth: 460, + valueType: "string", + labelPosition: "top", + onChange: function () { + that.validateInputDoc(); + } + }); + + this.buttonFieldAdd = new PMUI.field.ButtonField({ + id: 'buttonFieldAdd', + pmType: 'buttonField', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.8, + handler: function (field) { + that.addAcceptedValue(); + }, + style: { + cssProperties: { + "margin-left": "10px" + } + } + }); + this.buttonFieldAdd.getControl().button.setButtonType("success"); + this.buttonFieldCancel = new PMUI.field.ButtonField({ + id: 'buttonFieldCancel', + pmType: 'buttonField', + value: 'Cancel'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 55, + proportion: 0.6, + handler: function (field) { + that.clickedClose = false; + that.cancelAcceptedValue(); + that.editingOptions = false; + } + }); + this.buttonFieldCancel.getControl().button.setButtonType("error"); + + this.formVariables = new PMUI.form.Form({ + id: 'formVariables', + width: 'auto', + title: '', + visibleHeader: false, + items: [ + { + pmType: 'text', + label: 'Variable Name'.translate(), + placeholder: "Name".translate(), + id: 'variableName', + value: '', + name: 'var_name', + required: true, + valueType: 'string', + maxLength: 60, + controlsWidth: 460, + validators: [ + { + pmType: "regexp", + criteria: /^[a-zA-Z\_]{1}\w+$/, + errorMessage: "A valid variable starts with a letter or underscore, followed by any number of letters, numbers, or underscores.".translate() + } + ] + }, { + pmType: 'text', + label: 'Label'.translate(), + placeholder: 'Label'.translate(), + id: 'variableLabel', + value: 'label', + name: 'var_label', + valueType: 'string', + maxLength: 60, + controlsWidth: 460, + visible: false + }, { + pmType: 'dropdown', + label: 'Variable Type'.translate(), + placeholder: 'Variable type'.translate(), + id: 'varType', + value: 'string', + name: 'var_field_type', + required: true, + valueType: 'string', + controlsWidth: 460, + options: [ + { + label: 'String', + value: 'string' + }, { + label: 'Integer', + value: 'integer' + }, { + label: 'Float', + value: 'float' + }, { + label: 'Boolean', + value: 'boolean' + }, { + label: 'Datetime', + value: 'datetime' + }, { + label: 'Grid', + value: 'grid' + }, { + label: 'Array', + value: 'array' + }, { + label: "File", + value: "file" + }, { + label: "Multiple File", + value: "multiplefile" + }, { + label: "Object", + value: "object" + } + + ], + onChange: function (newValue, oldValue) { + var sw = that.gridAcceptedValues.visible === false ? true : (that.gridAcceptedValues.getData().length === 0); + var sw2 = that.formBooleanOptions.visible === false ? true : (that.formBooleanOptions.getField('trueOption').getValue() + that.formBooleanOptions.getField('falseOption').getValue()) === ''; + if (sw && sw2) { + that.changeViewFieldType(newValue, oldValue); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + return; + } + var message_window = new PMUI.ui.MessageWindow({ + id: 'messageWindowCancel', + width: 490, + title: 'Variables'.translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: "This action will delete all options. Do you want to continue?".translate(), + footerItems: [ + { + id: 'messageWindowNo', + text: 'No'.translate(), + handler: function () { + message_window.close(); + that.formVariables.getField('var_field_type').setValue(oldValue); + }, + buttonType: "error" + }, + { + id: 'messageWindowYes', + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + that.changeViewFieldType(newValue, oldValue); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + }, + buttonType: "success" + } + ], + onClose: function () { + } + }); + message_window.open(); + message_window.showFooter(); + } + }, { + pmType: "panel", + id: "inp_doc_uidPanel", + fieldset: false, + layout: "hbox", + items: [ + inp_doc_uid, + that.buttonCreateInputDocument, + that.buttonEditInputDocument + ] + }, + { + id: 'booleanPanel', + pmType: 'panel', + legend: 'Options'.translate(), + fieldset: true, + layout: 'vbox', + items: [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + new PMLabelField({ + text: 'Key'.translate(), + textMode: 'plain', + style: { + cssProperties: { + color: '#AEAEAE', + 'font-weight': 'bold' + } + }, + proportion: 0.3 + }), + new PMLabelField({ + text: 'Label'.translate(), + textMode: 'plain', + style: { + cssProperties: { + color: '#AEAEAE', + 'font-weight': 'bold' + } + } + }) + ] + }, + { + pmType: 'text', + name: 'trueOption', + label: 'True'.translate(), + controlsWidth: 460, + valueType: 'string', + maxLength: 100, + required: true + }, { + pmType: 'text', + name: 'falseOption', + label: 'False'.translate(), + controlsWidth: 460, + valueType: 'string', + maxLength: 100, + required: true + } + ] + }, + { + pmType: 'dropdown', + label: 'Database Connection'.translate(), + placeholder: 'Database Connection'.translate(), + id: 'varConnection', + value: 'none', + name: 'var_dbconnection', + controlsWidth: 460, + options: [{ + label: 'PM Database', + value: 'workflow' + } + ], + onChange: function (newValue, oldValue) { + } + }, { + pmType: 'textarea', + label: 'SQL'.translate(), + placeholder: "Insert a SQL query like: SELECT [Key field], [Label field] FROM [Table name]".translate(), + id: 'varSql', + value: '', + name: 'var_sql', + valueType: 'string', + controlsWidth: 460, + style: {cssClasses: ['mafe-textarea-resize']} + }, { + pmType: 'checkbox', + label: 'Define accepted variable values'.translate(), + id: "chckboxOption", + name: 'var_options_control', + controlsWidth: 460, + options: [{value: '1', label: ''}], + onChange: function (newValue, oldValue) { + that.changeViewFieldType(that.formVariables.getField('var_field_type').getValue()); + } + }, + { + id: 'formAcceptedValues', + pmType: 'panel', + fieldset: false, + layout: 'hbox', + items: [ + { + pmType: 'text', + name: 'keyValue', + id: "variable-keyvalue", + label: 'Key'.translate(), + labelWidth: '100%', + controlsWidth: 210, + proportion: 2.5, + valueType: 'string', + maxLength: 255, + labelPosition: "top" + }, + { + pmType: 'text', + name: 'value', + id: "variable-value", + label: 'Label'.translate(), + labelWidth: '100%', + controlsWidth: 300, + valueType: 'string', + maxLength: 255, + proportion: 3.4, + labelPosition: "top" + }, + that.buttonFieldCancel, + that.buttonFieldAdd + ] + } + ] + }); + this.formVariables.getData = function () { + var data = getData2PMUI(that.formVariables.html); + return data; + }; + this.gridVariables = new PMUI.grid.GridPanel({ + id: 'gridVariables', + pageSize: 10, + width: '96%', + style: { + cssClasses: ['mafe-gridPanel'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: 'varName', + title: 'Name'.translate(), + dataType: 'string', + columnData: 'var_name', + alignmentCell: 'left', + width: '300px', + sortable: true + }, { + id: 'varType', + title: 'Type'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'var_field_type', + sortable: true + }, { + id: 'varEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: '60px', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + that.showFormEdit(row.getData()); + } + }, { + id: 'varDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: '70px', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + that.del(row.getData(), row, grid); + } + } + ], + dataItems: null + }); + this.gridAcceptedValues = new PMUI.grid.GridPanel({ + id: 'gridAcceptedValues', + pageSize: 5, + style: {cssClasses: ['mafe-gridPanel']}, + filterPlaceholder: 'Text to Search'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + filterable: false, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: 'keyvalue', + title: 'Key'.translate(), + columnData: 'keyValue', + dataType: 'string', + alignmentCell: 'left', + width: 180 + }, { + id: 'label', + title: 'Label'.translate(), + columnData: 'value', + dataType: 'string', + alignmentCell: 'left', + width: 300 + }, { + id: 'buttonEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: 60, + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + that.editRow = row; + that.editAcceptedValue(row); + } + }, { + id: 'buttonDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: 75, + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + if (row !== that.editRow) { + that.deleteAcceptedValue(row); + } else { + PMDesigner.msgFlash('The row can not be removed, because is being edited.'.translate(), document.getElementById('windowVariables'), 'error', 1000, 5); + } + } + } + ], + dataItems: null, + behavior: 'dragdropsort' + }); + this.isDirtyFormVariables = function () { + $("input,select,textarea").blur(); + if (this.formVariables.isVisible()) { + this.validateAcceptedValues(); + if (this.formVariables.isDirty() || this.dirtyAcceptedValue || this.validateAcceptedValuesFlag) { + //if (this.formVariables.getField("var_options_control").controls[0].selected) { + var message_window = new PMUI.ui.MessageWindow({ + id: "messageWindowCancel", + width: 490, + title: "Variables".translate(), + windowMessageType: "warning", + bodyHeight: "auto", + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: "messageWindowNo", + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: "messageWindowYes", + text: "Yes".translate(), + handler: function () { + if (that.clickedClose) { + that.windowVariables.close(); + } + message_window.close(); + that.showGrid(); + that.windowVariables.hideFooter(); + }, + buttonType: "success" + }, + ] + }); + + message_window.open(); + message_window.showFooter(); + /*} else { + that.showGrid(); + }*/ + } else { + if (that.clickedClose) { + that.windowVariables.close(); + } else { + that.showGrid(); + } + this.initialFormAcceptedValuesKeyValue = null; + this.initialFormAcceptedValuesValue = null; + this.initialGridAcceptedValuesOrder = []; + that.windowVariables.hideFooter(); + } + } else { + this.windowVariables.close(); + } + }; + this.windowVariables = new PMUI.ui.Window({ + id: 'windowVariables', + title: 'Variables'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFormVariables(); + }, + footerItems: [ + new PMUI.ui.Button({ + id: "windowVariablesCancel", + text: "Cancel".translate(), + + handler: function () { + that.clickedClose = false; + that.isDirtyFormVariables(); + }, + + buttonType: "error" + }), + + new PMUI.ui.Button({ + id: "windowVariablesSave", + text: "Save".translate(), + + handler: function () { + if (that.edit) { + that.updateVariables(); + } else { + that.saveVariables(); + } + }, + + buttonType: "success" + }) + ], + onClose: function () { + that.onWindowClose(that.currentVariable); + }, + visibleFooter: true, + buttonPanelPosition: "bottom" + }); + PMVariables.prototype.init.call(this); + that.setInputDocuments(inp_doc_uid); +}; +PMVariables.prototype.init = function () { + var that = this, + acceptedValuesForm, + label; + + that.buttonCreate.defineEvents(); + + that.windowVariables.addItem(that.gridVariables); + that.windowVariables.addItem(that.formVariables); + that.windowVariables.addItem(that.gridAcceptedValues); + that.windowVariables.hideFooter(); + that.windowVariables.open(); + label = $('#booleanPanel'); + acceptedValuesForm = $('#formAcceptedValues'); + that.customCss(); + acceptedValuesForm.find(".pmui-field-message").css("marginLeft", 10); + $("#gridAcceptedValues").css({"height": "254px", "margin": "0 10px"}); + $("#requiredMessage").css({"margin-top": "10px"}); + $("#inp_doc_uid").find(".pmui-field-message:eq(0)").css("left", "226px"); + this.formAcceptedValues = PMUI.getPMUIObject(acceptedValuesForm.get(0)); + + this.buttonFieldAdd.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + this.buttonFieldCancel.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + $('#gridVariables .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + that.gridVariables.dom.toolbar.appendChild(that.buttonCreate.getHTML()); + + this.formBooleanOptions = PMUI.getPMUIObject(label.get(0)); + that.showGrid(); + that.loadDataBaseConnections(); + + validateKeysField(that.formVariables.getField('var_name').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + + that.resetAcceptedValuesPanel(); + label = $('#booleanPanel').css({'width': '675px', margin: '10px'}).find(".pmui-pmlabelfield"); + $(label[0]).replaceWith($(label[0]).find(".pmui-pmlabelcontrol").css({ + "font-size": "14px", + "margin-right": "127px" + })); + $(label[1]).replaceWith($(label[1]).find(".pmui-pmlabelcontrol").css({ + "font-size": "14px", + "margin-right": "127px" + })); + this.formVariables.panel.html.style.overflow = "scroll !important"; + $(this.formVariables.panel.html).removeClass("pmui-formpanel"); + $(this.formVariables.panel.html).append(that.formAcceptedValues.html); + $(this.formVariables.panel.html).append(that.gridAcceptedValues.html); + $(that.formAcceptedValues.html).find(".pmui-formpanel").css({"display": "inline-block"}); + that.windowVariables.footer.html.style.textAlign = "right"; +}; +PMVariables.prototype.saveVariables = function () { + var that = this, + data, + inp_doc_uid_value = this.formVariables.getField("inp_doc_uid").controls[0].value; + this.formVariables.getField("inp_doc_uid").setValue(inp_doc_uid_value); + if (!this.formVariables.isValid()) { + return; + } + if (this.formBooleanOptions.visible && !this.formBooleanOptions.isValid()) { + return; + } + data = this.formVariables.getData(); + data.var_label = data.var_field_type; + + data.var_default = ''; + data.var_accepted_values = that.getDataAcceptedValues(); + data.var_field_size = 10; + if (!this.formVariables.getField('var_sql').visible) + data.var_sql = ""; + (new PMRestClient({ + endpoint: 'process-variable', + typeRequest: 'post', + functionSuccess: function (xhr, response) { + if (that.onSave(xhr, response) === false) { + that.var_uid = null; + return; + } + that.showGrid(); + that.load(); + that.var_uid = null; + that.windowVariables.hideFooter(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ' ', + data: data, + messageSuccess: 'Variable saved successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.updateVariables = function () { + var that = this, + data, + inp_doc_uid_value = this.formVariables.getField("inp_doc_uid").controls[0].value; + this.formVariables.getField("inp_doc_uid").setValue(inp_doc_uid_value); + if (!this.formVariables.isValid()) { + return; + } + if (this.formBooleanOptions.visible && !this.formBooleanOptions.isValid()) { + return; + } + data = this.formVariables.getData(); + data.var_label = data.var_field_type; + data.var_field_size = 10; + if (that.formVariables.getField('var_name').getValue().trim() === that.var_name.trim()) { + delete data['var_name']; + } + data.var_default = ''; + data.var_accepted_values = that.getDataAcceptedValues(); + if (!this.formVariables.getField('var_sql').visible) + data.var_sql = ""; + (new PMRestClient({ + endpoint: 'process-variable/' + that.var_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + if (that.onEdit(xhr, response, data) === false) { + that.var_uid = null; + return; + } + var var_name_old = that.currentVariable.var_name; + that.currentVariable = data; + that.currentVariable.var_uid = that.var_uid; + that.currentVariable.var_name_old = var_name_old; + that.showGrid(); + that.load(); + that.var_uid = null; + that.windowVariables.hideFooter(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ' ', + messageSuccess: 'Variable edited successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.deleteVariable = function (var_uid) { + var that = this; + (new PMRestClient({ + endpoint: 'process-variable/' + var_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'working...'.translate(), + messageSuccess: 'Variable deleted successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; +PMVariables.prototype.load = function () { + var that = this; + var restProxy = new PMRestClient({ + endpoint: 'process-variables', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var listInputDocs = response; + that.gridVariables.setDataItems(listInputDocs); + that.gridVariables.sort('var_name', 'asc'); + $(that.gridVariables.dom.toolbar).find("input").val(""); + that.gridVariables.clearFilter(); + if (that.currentVariable !== null) { + var var_name_old = that.currentVariable.var_name_old; + for (var i = 0; i < response.length; i++) { + if (that.currentVariable.var_uid === response[i].var_uid) { + that.currentVariable = response[i]; + } + } + that.currentVariable.var_name_old = var_name_old; + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +PMVariables.prototype.del = function (data, row, grid) { + var that = this; + var confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDel', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Variables".translate(), + message: 'Do you want to delete this variable?'.translate(), + footerItems: [{ + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.deleteVariable(data.var_uid, row); + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMVariables.prototype.customCss = function () { + $("#inp_doc_uidPanel").css({padding: ""}); + $("#inp_doc_uid").css({width: "75%"}).find("label:eq(0)").css({float: "left", width: "31.5%"}); + + var td = $("#chckboxOption .pmui-field-control-table td")[0]; + + if (typeof(td) != "undefined") { + td.setAttribute("style", "padding:0px !important"); + } + + this.formVariables.panel.getHTML().setAttribute("style", "overflow: initial"); +}; + +PMVariables.prototype.showGrid = function () { + var that = this; + that.formVariables.setVisible(false); + that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(false); + that.disableBooleanPanel(); + $(that.gridVariables.dom.toolbar).find("input").val(""); + that.gridVariables.clearFilter(); + that.gridVariables.setVisible(true); + that.windowVariables.setTitle('Variables'.translate()); +}; +PMVariables.prototype.showForm = function () { + var that = this; + that.edit = false; + that.dirtyAcceptedValue = false; + that.formVariables.setVisible(true); + that.enableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true); + that.enableBooleanPanel(); + that.gridVariables.setVisible(false); + that.windowVariables.setTitle('Create Variable'.translate()); + that.formVariables.reset(); + that.formVariables.setFocus(); + that.changeViewFieldType('string'); + that.resetAcceptedValuesPanel(); + that.gridAcceptedValues.clearItems(); + that.resetBooleanPanel(); + that.buttonFieldCancel.setVisible(false); + that.windowVariables.showFooter(); + that.buttonCreateInputDocument.setVisible(false); + that.buttonEditInputDocument.setVisible(false); +}; +PMVariables.prototype.showFormEdit = function (data) { + var that = this; + that.showForm(); + that.var_uid = data.var_uid; + that.edit = true; + that.var_name = data.var_name; + that.windowVariables.setTitle('Edit Variable'.translate()); + that.formVariables.getField('var_dbconnection').setValue(data.var_dbconnection); + that.formVariables.getField('var_field_type').setValue(data.var_field_type); + that.formVariables.getField('var_label').setValue(data.var_label); + that.formVariables.getField('var_name').setValue(data.var_name); + that.formVariables.getField('var_sql').setValue(data.var_sql); + that.formVariables.getField('inp_doc_uid').setValue(data.inp_doc_uid); + + that.setVarOptionsControl(data.var_accepted_values); + that.changeViewFieldType(data.var_field_type); + that.setDataAcceptedValues(data.var_accepted_values); + that.currentVariable = data; + that.currentVariable.var_name_old = that.currentVariable.var_name; +}; +PMVariables.prototype.loadDataBaseConnections = function () { + var that = this; + var restProxy = new PMRestClient({ + endpoint: 'database-connections', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var dropdown = that.formVariables.getField('var_dbconnection'); + for (var i = 0; i < response.length; i++) { + if (response[i].dbs_connection_type == "TNS") { + dropdown.addOption({ + label: "[" + response[i].dbs_tns + "] " + response[i].dbs_type + " : " + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } else { + dropdown.addOption({ + label: "[" + response[i].dbs_server + ":" + response[i].dbs_port + "] " + response[i].dbs_type + ": " + response[i].dbs_database_name + response[i].dbs_database_description, + value: response[i].dbs_uid + }); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); +}; +PMVariables.prototype.changeViewFieldType = function (newValue) { + var that = this; + var sw = that.formVariables.getField('var_options_control').controls[0].selected; + + that.formVariables.getField('var_dbconnection').setVisible(false); + that.formVariables.getField('var_sql').setVisible(false); + that.formVariables.getField('var_options_control').setVisible(false); + that.formVariables.getField('inp_doc_uid').setVisible(false); + that.formVariables.getField('inp_doc_uid').setRequired(false); + that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(false); + that.disableBooleanPanel(); + that.buttonCreateInputDocument.setVisible(false); + that.buttonEditInputDocument.setVisible(false); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), []); + + if (this.fieldInfo === null) { + this.fieldInfo = document.createTextNode(''); + var a = that.formVariables.getField('var_field_type').getControls()[0]; + a.html.parentNode.appendChild(document.createElement('br')); + a.html.parentNode.appendChild(this.fieldInfo); + } + + switch (newValue) { + case 'string': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + + + break; + case 'integer': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'ishyphen']); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + break; + case 'float': + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + + validateKeysField(that.formAcceptedValues.getField('keyValue').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isperiod', 'ishyphen']); + this.fieldInfo.data = "Supported Controls: text, textarea, dropdown, radio, suggest, hidden.".translate(); + break; + case 'boolean': + that.enableBooleanPanel(); + this.fieldInfo.data = "Supported Controls: checkbox, radio, hidden.".translate(); + break; + case 'datetime': + this.fieldInfo.data = "Supported Controls: datetime, hidden.".translate(); + break; + case "grid": + this.fieldInfo.data = "Supported Controls: grid.".translate(); + break; + case "array": + that.formVariables.getField('var_dbconnection').setVisible(true); + that.formVariables.getField('var_sql').setVisible(true); + that.formVariables.getField('var_options_control').setVisible(true); + sw ? that.enableAcceptedValuesPanel() : that.disableAcceptedValuesPanel(); + that.gridAcceptedValues.setVisible(true && sw); + this.fieldInfo.data = "Supported Controls: checkgroup.".translate(); + break; + case 'file': + that.formVariables.getField('inp_doc_uid').setVisible(true); + that.buttonCreateInputDocument.setVisible(true); + that.buttonEditInputDocument.setVisible(true); + that.formVariables.getField('inp_doc_uid').setRequired(true); + this.fieldInfo.data = "Supported Controls: file.".translate(); + that.validateInputDoc(); + break; + case 'multiplefile': + this.fieldInfo.data = "Supported Controls: Multiple File.".translate(); + break; + case 'object': + this.fieldInfo.data = "Supported Controls:".translate(); + break; + } +}; +/** + * Enable or disable edit button of input document + */ +PMVariables.prototype.validateInputDoc = function () { + var form = this.formVariables, + fieldInpDoc = form.getField("inp_doc_uid"), + defaultText = "- Select an input document -".translate(); + if (fieldInpDoc && fieldInpDoc.getValue() && fieldInpDoc.getValue() !== defaultText) { + this.buttonEditInputDocument.enable(); + } else { + this.buttonEditInputDocument.disable(); + } +}; +PMVariables.prototype.addAcceptedValue = function () { + var that = this, + key = jQuery.trim(that.formAcceptedValues.getField('keyValue').getValue()), + value = jQuery.trim(that.formAcceptedValues.getField('value').getValue()); + + if (that.isAcceptedValueAdded()) { + return PMDesigner.msgFlash('The key value already exists.'.translate(), + document.getElementById('windowVariables'), 'error', 1000, 5); + } + if (!(key && value)) { + return PMDesigner.msgFlash('The key and label must be supplied.'.translate(), + document.getElementById('windowVariables'), 'error', 1000, 5); + } + if (that.editRow === null) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + keyValue: key, + value: value + } + })); + } else { + this.editingOptions = false; + that.editRow.setData({ + keyValue: key, + value: value + }); + } + that.dirtyAcceptedValue = true; + that.cancelAcceptedValue(); +}; +PMVariables.prototype.editAcceptedValue = function (row) { + var that = this; + this.editingOptions = true; + that.editRow = row; + var data = row.getData(); + that.formAcceptedValues.getField('keyValue').setValue(data.keyValue); + that.formAcceptedValues.getField('value').setValue(data.value); + that.buttonFieldAdd.setValue('Save'.translate()); + that.buttonFieldCancel.setVisible(true); + + that.initialFormAcceptedValuesKeyValue = data.keyValue; + that.initialFormAcceptedValuesValue = data.value; +}; +PMVariables.prototype.deleteAcceptedValue = function (row) { + var that = this; + var confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Variables".translate(), + message: 'Do you want to delete this Key Value?'.translate(), + footerItems: [{ + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.gridAcceptedValues.removeItem(row); + that.dirtyAcceptedValue = true; + }, + buttonType: "success" + } + ] + }); + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; +PMVariables.prototype.getDataAcceptedValues = function () { + var that = this, data = [], i, dt = []; + if (that.gridAcceptedValues.visible) { + dt = that.gridAcceptedValues.getData(); + for (i = 0; i < dt.length; i++) { + delete dt[i].key; + delete dt[i].type; + data.push({ + value: dt[i].keyValue, + label: dt[i].value + }); + } + } + if (that.formBooleanOptions.visible) { + var a = that.formBooleanOptions.getItems("fields").reduce(function (prev, curr) { + prev[curr.getName()] = curr.getValue(); + return prev; + }, {}); + + data = [ + {value: '1', label: a.trueOption}, + {value: '0', label: a.falseOption} + ]; + } + return data; +}; +PMVariables.prototype.setDataAcceptedValues = function (stringJsonData) { + if (!stringJsonData) { + return; + } + var that = this, i, data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + if (that.gridAcceptedValues.visible) { + for (i = 0; i < data.length; i++) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + keyValue: data[i].keyValue ? data[i].keyValue : data[i].value, + value: data[i].keyValue ? data[i].value : data[i].label + } + })); + that.initialGridAcceptedValuesOrder.push(data[i].keyValue ? data[i].keyValue : data[i].value); + } + } + if (that.formBooleanOptions.visible) { + that.formBooleanOptions.getField('trueOption').setValue(data[0].label); + that.formBooleanOptions.getField('falseOption').setValue(data[1].label); + } +}; +PMVariables.prototype.validateAcceptedValues = function () { + var that = this, + dirty = false, + finalVal1, + finalVal2, + initVal1, + initVal2, + gridAcceptedValues, + finalGridAcceptedValuesOrder = [], + key; + if (that.initialFormAcceptedValuesValue && that.formAcceptedValues.getField('value').getValue() != '') { + finalVal1 = that.formAcceptedValues.getField('value').getValue(); + finalVal2 = that.formAcceptedValues.getField('keyValue').getValue(); + initVal1 = that.initialFormAcceptedValuesValue; + initVal2 = that.initialFormAcceptedValuesKeyValue; + if (finalVal1 !== initVal1 || finalVal2 !== initVal2) { + dirty = true; + } + } else if (that.formAcceptedValues.getField('value').getValue() !== '' || that.formAcceptedValues.getField('keyValue').getValue()) { + dirty = true; + } + + if (that.initialGridAcceptedValuesOrder.length) { + gridAcceptedValues = that.gridAcceptedValues.getData(); + for (key in gridAcceptedValues) { + if (gridAcceptedValues.hasOwnProperty(key)) { + finalGridAcceptedValuesOrder.push(gridAcceptedValues[key].keyValue); + } + } + if (JSON.stringify(finalGridAcceptedValuesOrder) !== JSON.stringify(that.initialGridAcceptedValuesOrder)) { + dirty = true; + } + } + this.validateAcceptedValuesFlag = dirty; +}; +PMVariables.prototype.setVarOptionsControl = function (stringJsonData) { + if (!stringJsonData) { + return; + } + var that = this, i, data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + if (data.length > 0) { + that.formVariables.getField('var_options_control').setValue("['1']"); + } +}; +PMVariables.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that.buttonFieldAdd.setValue('Add'.translate()); + that.buttonFieldCancel.setVisible(false); + that.resetAcceptedValuesPanel(); +}; +PMVariables.prototype.isAcceptedValueAdded = function () { + var that = this, i, keyValue, data, exist, i, index, rowEditValue; + data = that.gridAcceptedValues.getData(); + keyValue = that.formAcceptedValues.getField('keyValue').getValue() || ""; + if (this.editingOptions) { + rowEditValue = this.editRow.getData()["keyValue"]; + for (i = 0; i < data.length; i++) { + if (rowEditValue === data[i].keyValue) { + index = i; + break; + } + } + for (i = 0; i < data.length; i++) { + if (i !== index) { + if (keyValue === data[i].keyValue) { + exist = true; + } + } + } + if (exist) { + return true; + } else { + return false; + } + } else { + for (i = 0; i < data.length; i++) { + if (data[i].keyValue === keyValue) { + return true; + } + } + } + return false; +}; +PMVariables.prototype.setInputDocuments = function (inp_doc_uid) { + var restClient = new PMRestClient({ + endpoint: 'input-documents', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + inputDocumentsData = response; + var arrayOptions = []; + arrayOptions[0] = { + label: "- Select an input document -".translate(), + value: "", + disabled: true, + selected: true + }; + for (var i = 0; i <= inputDocumentsData.length - 1; i++) { + arrayOptions.push( + { + value: inputDocumentsData[i].inp_doc_uid, + label: inputDocumentsData[i].inp_doc_title + } + ); + } + inp_doc_uid.setOptions(arrayOptions); + inp_doc_uid.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + }); + restClient.executeRestClient(); +}; +PMVariables.prototype.setInputDocumentsFromIDModule = function (inp_doc_uid, response) { + var inp_doc_uid_val = $("#inp_doc_uid").find("select:eq(0) option:selected").val(); + var arrayOptions = []; + inputDocumentsData = response; + arrayOptions[0] = { + label: "- Select an input document -".translate(), + value: "", + disabled: true, + selected: true + }; + for (var i = 0; i <= inputDocumentsData.length - 1; i++) { + arrayOptions.push( + { + value: inputDocumentsData[i].inp_doc_uid, + label: inputDocumentsData[i].inp_doc_title + } + ); + } + inp_doc_uid.setOptions(arrayOptions); + inp_doc_uid.setValue(arrayOptions[0].value); + if (inp_doc_uid_val) { + inp_doc_uid.setValue(inp_doc_uid_val); + } +}; +PMVariables.prototype.isWindowActive = function () { + if ($("#formVariables").is(":visible")) { + return true; + } + return false; +}; +/** + * Reset the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.resetBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.getItems("fields").forEach(function (i) { + i.setValue(""); + }); + } + return this; +}; +/** + * Disable the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.disableBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.setVisible(false) + .getItems("fields").forEach(function (i) { + i.disable(); + }); + } + return this; +}; +/** + * Enable the fields from the form's boolean panel. + * @returns {PMVariables} + */ +PMVariables.prototype.enableBooleanPanel = function () { + if (this.formBooleanOptions) { + this.formBooleanOptions.setVisible(true) + .getItems("fields").forEach(function (i) { + i.enable(); + }); + } + return this; +}; +/** + * Reset the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.resetAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.getItems().forEach(function (i) { + i.setValue(""); + }); + } + return this; +}; +/** + * Enable the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.enableAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.setVisible(true) + .getItems('fields').forEach(function (i) { + i.enable(""); + }); + } + return this; +}; +/** + * Disable the fields from the form's Accepted Values panel. + * @returns {PMVariables} + */ +PMVariables.prototype.disableAcceptedValuesPanel = function () { + if (this.formAcceptedValues) { + this.formAcceptedValues.setVisible(false) + .getItems('fields').forEach(function (i) { + i.disable(""); + }); + } + return this; +}; +PMDesigner.variables = function () { + var pmvariables = new PMVariables(); + pmvariables.load(); +}; +PMDesigner.variables.create = function () { + var pmvariables = new PMVariables(); + pmvariables.showForm(); + pmvariables.load(); +}; + +RowVariableCondition = function () { + PMUI.form.FormPanel.call(this, { + layout: 'hbox' + }); + RowVariableCondition.prototype.init.call(this); +}; +RowVariableCondition.prototype = new PMUI.form.FormPanel(); +RowVariableCondition.prototype.createHTML = function () { + var items; + PMUI.form.FormPanel.prototype.createHTML.call(this); + items = this.getItems(); + items[0].dom.labelTextContainer.style.display = 'none'; + items[1].dom.labelTextContainer.style.display = 'none'; + items[2].dom.labelTextContainer.style.display = 'none'; + items[2].style.addProperties({display: 'none'}); + items[2].controls[0].button.setButtonType('error'); + return this.html; +}; +RowVariableCondition.prototype.init = function () { + var that = this, + typeData, + field, + remove; + field = new PMUI.field.TextField({ + id: 'idField', + name: '', + required: true, + controlsWidth: 425, + proportion: 2.1, + labelVisible: false + }); + typeData = new PMUI.field.DropDownListField({ + id: 'idTypeData', + name: '', + valueType: 'string', + value: '', + readOnly: true, + controlsWidth: 200, + labelVisible: false, + options: [{ + value: 'integer', + label: 'Integer'.translate() + }, { + value: 'string', + label: 'String'.translate() + }, { + value: 'float', + label: 'Float'.translate() + }, { + value: 'boolean', + label: 'Boolean'.translate() + }, { + value: 'date', + label: 'Date'.translate() + }, { + value: 'datetime', + label: 'Datetime'.translate() + } + ] + }); + remove = new PMUI.field.ButtonField({ + id: 'idRemove', + value: 'Delete'.translate(), + labelVisible: false, + handler: function (e, a) { + that.getParent().removeItem(that); + }, + name: 'delete', + controlsWidth: 60 + }); + that.addItem(field); + that.addItem(typeData); + that.addItem(remove); +}; + +PropertiesReceiveMessage = function (menuOption) { + this.variables = []; + this.onApply = new Function(); + this.onCancel = new Function(); + this.menuOption = menuOption; + Mafe.Window.call(this); + PropertiesReceiveMessage.prototype.init.call(this); +}; +PropertiesReceiveMessage.prototype = new Mafe.Window(); +PropertiesReceiveMessage.prototype.init = function () { + var that = this; + that.setTitle(that.menuOption.getMenuTargetElement().evn_name); + that.setButtons([ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + handler: function () { + that.close(); + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSaveOpen', + text: 'Apply'.translate(), + buttonType: 'success', + height: 31, + handler: function () { + that.onApply(); + } + }) + ]); + that.buttonAdd = new PMUI.ui.Button({ + text: 'Add Variable'.translate(), + buttonType: 'success', + height: 31, + style: {cssProperties: {marginLeft: '50px', marginTop: '10px'}}, + handler: function () { + that.addVariable(); + } + }); + that.form = new Mafe.Form({ + title: that.menuOption.getMenuTargetElement().evn_name, + width: DEFAULT_WINDOW_WIDTH - 60, + style: {cssProperties: {'margin-left': '35px'}} + }); + that.conditionForm = new Mafe.Form({ + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + style: {cssProperties: {'margin-left': '35px'}}, + items: [{ + label: 'Condition', + labelPosition: 'top', + pmType: 'textarea', + rows: 100, + style: {cssClasses: ['mafe-textarea-resize']} + } + ] + }); + + that.addItem(that.buttonAdd); + that.addItem(that.form); + that.addItem(that.conditionForm); + + that.addVariable(); +}; +PropertiesReceiveMessage.prototype.addVariable = function () { + var that = this, a, i; + a = new RowVariableCondition(this.variables); + that.form.addItem(a); + //force padding + for (i = 0; i < that.form.getItems().length; i += 1) { + that.form.getItems()[i].style.addProperties({'padding': 'initial'}); + } +}; + +EventMessagesGrid = function () { + this.onCreate = new Function(); + this.onEdit = new Function(); + this.onDel = new Function(); + Mafe.Grid.call(this); + EventMessagesGrid.prototype.init.call(this); +}; +EventMessagesGrid.prototype = new Mafe.Grid(); +EventMessagesGrid.prototype.createHTML = function () { + Mafe.Grid.prototype.createHTML.call(this); + this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); + return this.html; +}; +EventMessagesGrid.prototype.init = function () { + var that = this; + that.buttonCreate = new PMUI.ui.Button({ + id: 'idButtonEventMessagesGrid', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: {cssClasses: ['mafe-button-create']}, + handler: function (event) { + that.onCreate(event); + } + }); + that.buttonCreate.defineEvents(); + that.setID('idEventMessagesGrid'); + that.setColumns([{ + id: '', + title: 'Nombre', + sortable: true, + width: '460px', + dataType: 'string', + alignmentCell: 'left', + columnData: 'mes_title' + }, { + id: 'dynaformGridPanelEdit', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-edit']}, + buttonLabel: function (row, data) { + return 'Edit'.translate(); + }, + onButtonClick: function (row, grid) { + that.onEdit(row, grid); + } + }, { + id: 'dynaformGridPanelDelete', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-delete']}, + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + onButtonClick: function (row, grid) { + that.onDel(row, grid); + } + } + ]); + that.load(); +}; +EventMessagesGrid.prototype.show = function () { + +}; +EventMessagesGrid.prototype.create = function () { + +}; +EventMessagesGrid.prototype.load = function () { + var that = this, + dt = [ + {mes_title: 'message1-1'}, + {mes_title: 'message1-2'}, + {mes_title: 'message1-3'}, + {mes_title: 'message1-4'} + ]; + that.setDataItems(dt); +}; + +EventMessagesForm = function () { + Mafe.Form.call(this); + EventMessagesForm.prototype.init.call(this); +}; +EventMessagesForm.prototype = new Mafe.Form(); +EventMessagesForm.prototype.init = function () { + var that = this; + that.setID('idEventMessagesForm'); + that.setItems({ + id: '', + pmType: 'text', + label: 'Name'.translate(), + value: '', + maxLength: 100, + placeholder: '', + name: '', + required: true, + controlsWidth: 300 + }); + that.buttons = [ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + handler: function () { + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformPmtableSave', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + handler: function () { + that.onSave(); + } + }) + ]; +}; +EventMessagesForm.prototype.getButtons = function () { + return this.buttons; +}; + +EventMessages = function () { + Mafe.Window.call(this); + + this.list = new EventMessagesGrid(); + this.form = new EventMessagesForm(); + + EventMessages.prototype.init.call(this); +}; +EventMessages.prototype = new Mafe.Window(); +EventMessages.prototype.init = function () { + var that = this; + that.list.onCreate = function () { + that.resetView(); + that.form.setVisible(true); + }; + that.setTitle("Event Messages"); + that.addItem(that.list); +}; +EventMessages.prototype.showForm = function () { + this.list.show(); +}; + +PMDesigner.eventMessages = function () { + var a = new EventMessages(); + a.open(); +}; +PMDesigner.eventMessages.create = function () { +}; + +var UserPicker = function (options) { + this.relatedField = null; + this.processId = null; + this.workspace = null; + this.window = null; + this.currentVariable = {}; + this.pageSize = 10; + UserPicker.prototype.init.call(this, options); +}; + +UserPicker.prototype.type = 'UserPicker'; + +UserPicker.prototype.family = 'UserPicker'; + +UserPicker.prototype.init = function (options) { + var defaults = { + relatedField: null, + processId: PMDesigner.project.projectId, + workspace: WORKSPACE + }; + + jQuery.extend(true, defaults, options); + + this.setRelatedField(defaults.relatedField) + .setProcessId(defaults.processId) + .setWorkspace(defaults.workspace); +}; + +UserPicker.prototype.setRelatedField = function (field) { + if (field instanceof PMUI.form.Field) { + this.relatedField = field; + } + return this; +}; + +UserPicker.prototype.setProcessId = function (process) { + this.processId = process; + return this; +}; + +UserPicker.prototype.setWorkspace = function (workspace) { + this.workspace = workspace; + return this; +}; + +UserPicker.prototype.open = function (callback) { + var w, rc, fieldC, dataGrid, panel, textField, that = this, button, panelFilter; + button = new PMUI.ui.Button({ + id: 'insertUser', + text: 'Insert User'.translate(), + handler: function () { + if (callback && callback.success && typeof callback.success === 'function') { + callback.success.call(that, that.currentVariable); + } + that.close(); + }, + disabled: true + }); + + textField = new PMUI.field.TextField({ + id: 'textFieldSearch', + label: '', + placeholder: 'Search ...'.translate() + }); + + w = new PMUI.ui.Window({ + id: 'processVariables', + title: 'Process Users'.translate(), + width: 480, + height: 420, + closable: true, + modal: true, + buttons: [ + button + ], + buttonsPosition: 'center' + }); + + textField = new PMUI.field.TextField({ + id: 'textFieldSearch', + label: '', + placeholder: 'Search ...'.translate(), + width: 150 + }); + + dataGrid = new PMUI.grid.GridPanel({ + id: 'gridPanel', + selectable: true, + pageSize: this.pageSize, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'gridPanelUserName', + title: 'User Name'.translate(), + columnData: 'usr_username', + width: 150, + sortable: true, + alignmentCell: 'left' + }, + { + id: 'gridPanelRole', + title: 'Role'.translate(), + columnData: 'usr_role', + width: 230, + sortable: false, + alignmentCell: 'left' + } + ], + onRowClick: function (row, data) { + button.enable(); + that.currentVariable.username = data.usr_username; + that.currentVariable.uid = data.usr_uid; + } + + }); + + panelFilter = new PMUI.core.Panel({ + id: 'panelFilter', + layout: 'vbox', + items: [/*fieldC,*/ textField] + }); + + panel = new PMUI.core.Panel({ + id: 'paneldataGrid', + layout: 'vbox', + items: [panelFilter, dataGrid] + }); + + rc = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + console.log(response); + that.window = w; + dataGrid.setDataItems(response); + w.open(); + w.showFooter(); + w.addItem(panel); + panelFilter.setWidth(430); + textField.controls[0].onKeyUp = function () { + console.log(textField.controls[0].html.value); + dataGrid.filter(textField.controls[0].html.value); + }; + dataGrid.dom.toolbar.style.display = 'none'; + textField.dom.labelTextContainer.innerHTML = ''; + textField.dom.labelTextContainer.style.marginTop = 5; + panel.style.addProperties({'padding-left': 20}); + textField.dom.labelTextContainer.style.display = 'none'; + textField.controls[0].setWidth(200); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + rc.setBaseEndPoint('users').executeRestClient(); +}; + +UserPicker.prototype.close = function () { + if (this.window) { + this.window.close(); + this.window = null; + } +}; + +var CriteriaUserField = function (options) { + this.renderType = (options && options.renderType) || "text"; + PMUI.field.TextField.call(this, options); + this.process = null; + this.workspace = null; + this.buttonHTML = null; + this.rows = options.rows; + this.user_uid = null; + CriteriaUserField.prototype.init.call(this, options); +}; + +CriteriaUserField.prototype = new PMUI.field.TextField(); + +CriteriaUserField.prototype.setProcess = function (process) { + this.process = process; + return this; +}; + +CriteriaUserField.prototype.setWorkspace = function (workspace) { + this.workspace = workspace; + return this; +}; + +CriteriaUserField.prototype.init = function (options) { + var defaults = { + process: PMDesigner.project.projectId, + workspace: WORKSPACE + }; + jQuery.extend(true, defaults, options); + this.setProcess(defaults.process) + .setWorkspace(defaults.workspace); +}; + +CriteriaUserField.prototype.createVariablePicker = function () { + var vp = new UserPicker({ + relatedField: this, + processId: this.process + }); + return vp; +}; + +CriteriaUserField.prototype.setControls = function () { + if (this.controls.length) { + return this; + } + if (this.renderType === 'text') { + this.controls.push(new PMUI.control.TextControl()); + } else { + this.controls.push(new PMUI.control.TextAreaControl({style: {cssProperties: {resize: 'vertical'}}})); + } + return this; +}; + +CriteriaUserField.prototype.createCallBack = function () { + var that = this, oldValue, newValue, init = 0; + return { + success: function (variable) { + init = that.controls[0].html.selectionStart; + prevText = that.controls[0].html.value.substr(0, init); + lastText = that.controls[0].html.value.substr(that.controls[0].html.selectionEnd, that.controls[0].html.value.length); + newValue = variable.username; + + that.setValue(newValue); + that.user_uid = variable.uid; + that.controls[0].html.selectionEnd = init + variable.username.length; + } + }; +}; + +CriteriaUserField.prototype.createHTML = function () { + var button, that = this; + PMUI.field.TextField.prototype.createHTML.call(this); + + button = new PMUI.ui.Button({ + id: 'buttonCriteriaUserField', + text: '...', + handler: function () { + that.createVariablePicker().open(that.createCallBack()); + }, + style: { + cssProperties: { + background: '#2d3e50', + fontSize: 18, + paddingLeft: '15px', + paddingRight: '15px', + borderRadius: '4px', + verticalAlign: 'top' + } + } + }); + + this.buttonHTML = button; + $(this.helper.html).before(button.getHTML()) + this.buttonHTML.style.addProperties({"margin-left": "10px"}); + this.buttonHTML.html.tabIndex = -1; + + if (this.rows != null) + this.controls[0].setHeight(this.rows); + button.defineEvents(); + + return this.html; +}; + +// Overwrite original init function for FormItemFactory +PMUI.form.FormItemFactory.prototype.init = function () { + var defaults = { + products: { + "criteria": CriteriaUserField, + "field": PMUI.form.Field, + "panel": PMUI.form.FormPanel, + "text": PMUI.field.TextField, + "password": PMUI.field.PasswordField, + "dropdown": PMUI.field.DropDownListField, + "radio": PMUI.field.RadioButtonGroupField, + "checkbox": PMUI.field.CheckBoxGroupField, + "textarea": PMUI.field.TextAreaField, + "datetime": PMUI.field.DateTimeField, + "optionsSelector": PMUI.field.OptionsSelectorField, + "buttonField": PMUI.field.ButtonField, + "annotation": PMUI.field.TextAnnotationField + }, + defaultProduct: "panel" + }; + this.setProducts(defaults.products) + .setDefaultProduct(defaults.defaultProduct); +}; + +/** + * Class representing a Web Entry + * @param relatedShape + * @constructor + */ +var WebEntry = function (relatedShape) { + this.relatedShape = null; + this.groupType = null; + this.groupLabel = null; + this.stepsType = null; + this.actUid = null; + this.evenUid = null; + this.weeUid = null; + this.stepsAssigned = null; + this.elementAccordionOpen = null; + this.configWebEntry = null; + this.isNewWebEntry = null; + this.windowWebEntry = null; + this.windowAlternative = null; + this.tabForm = null; + this.tabProperties = null; + this.tabLink = null; + this.confirmWindow = null; + this.tabPanelWindow = null; + this.suggestUser = null; + this.stepsAssignTree = null; + this.stepsAssignAccordion = null; + this.labelsPanel = null; + this.userGuest = {}; + WebEntry.prototype.initialize.call(this, relatedShape); +}; +/** + * A module representing a Web Entry + **/ +WebEntry.prototype = { + /** + * Sets the actUid + * @param {string} actUid + */ + setActUid: function (actUid) { + this.actUid = actUid; + return this; + }, + + /** + * Sets the evenUid + * @param {string} evenUid + */ + setEvnUid: function (evenUid) { + this.evenUid = evenUid; + return this; + }, + + /** + * Sets the weeUid + * @param {string} weeUid + */ + setWeeUid: function (weeUid) { + this.weeUid = weeUid; + return this; + }, + + /** + * Sets the configWebEntry + * @param {object} configWebEntry + */ + setConfigWebEntry: function (configWebEntry) { + this.configWebEntry = configWebEntry; + return this; + }, + + /** + * Sets the isNewWebEntry + * @param {boolean} isNewWebEntry + */ + setIsNewWebEntry: function (isNewWebEntry) { + this.isNewWebEntry = isNewWebEntry; + return this; + }, + + /** + * Sets the windowWebEntry + * @param {object} windowWebEntry + */ + setWindowWebEntry: function (windowWebEntry) { + this.windowWebEntry = windowWebEntry; + return this; + }, + + /** + * Sets the windowAlternative + * @param {object} windowAlternative + */ + setWindowAlternative: function (windowAlternative) { + this.windowAlternative = windowAlternative; + return this; + }, + + /** + * Sets the relatedShape + * @param {object} relatedShape + */ + setRelatedShape: function (relatedShape) { + this.relatedShape = relatedShape; + return this; + }, + + /** + * Sets the tabForm + * @param {object} tabForm + */ + setTabForm: function (tabForm) { + this.tabForm = tabForm; + return this; + }, + + /** + * Sets the tabProperties + * @param {object} tabProperties + */ + setTabProperty: function (tabProperties) { + this.tabProperties = tabProperties; + return this; + }, + + /** + * Sets the tabLink + * @param {object} tabLink + */ + setTabLink: function (tabLink) { + this.tabLink = tabLink; + return this; + }, + + /** + * Sets the confirmWindow + * @param {object} confirmWindow + */ + setConfirmWin: function (confirmWindow) { + this.confirmWindow = confirmWindow; + return this; + }, + + /** + * Sets the tabPanelWindow + * @param {object} tabPanelWindow + */ + setTabPanelWindow: function (tabPanelWindow) { + this.tabPanelWindow = tabPanelWindow; + return this; + }, + + /** + * Sets the suggestUser + * @param {object} suggestUser + */ + setSuggestUser: function (suggestUser) { + this.suggestUser = suggestUser; + return this; + }, + + /** + * Sets the stepsAssignTree + * @param {object} stepsAssignTree + */ + setStepsTree: function (stepsAssignTree) { + this.stepsAssignTree = stepsAssignTree; + return this; + }, + + /** + * Sets the stepsAssignAccordion + * @param {object} stepsAssignAccordion + */ + setStepsAccordion: function (stepsAssignAccordion) { + this.stepsAssignAccordion = stepsAssignAccordion; + return this; + }, + + /** + * Sets the labelsPanel + * @param {object} labelsPanel + */ + setLabelPanel: function (labelsPanel) { + this.labelsPanel = labelsPanel; + return this; + }, + + /** + * Sets the userGuest + * @param userGuest + */ + setUserGuest: function (userGuest) { + this.userGuest = userGuest; + return this; + }, + + /** + * Get the userGuest + * @returns {Object} userGuest + */ + getUserGuest: function () { + return this.userGuest || {}; + }, + + /** + * Get the actUid value + * @returns {null|*|string} The actUid value + */ + getActUid: function () { + return this.actUid || ""; + }, + + /** + * Get the isNewWebEntry value + * @returns {null|*|boolean} The isNewWebEntry value + */ + getRelatedShape: function () { + return this.relatedShape || []; + }, + + /** + * Get the evenUid value + * @returns {null|*|string} The evenUid value + */ + getEvnUid: function () { + return this.evenUid || ""; + }, + + /** + * Get the weeUid value + * @returns {null|*|string} The weeUid value + */ + getWeeUid: function () { + return this.weeUid || ""; + }, + + /** + * Get the configWebEntry value + * @returns {*|null|Array} The configWebEntry value + */ + getConfigWebEntry: function () { + return this.configWebEntry || []; + }, + + /** + * Get the isNewWebEntry value + * @returns {null|*|boolean} The isNewWebEntry value + */ + getIsNewWebEntry: function () { + return this.isNewWebEntry || false; + }, + + /** + * Get the windowWebEntry value + * @returns {null|*} The windowWebEntry value + */ + getWindowWebEntry: function () { + return this.windowWebEntry || null; + }, + + /** + * Get the windowAlternative value + * @returns {*|null} The windowAlternative value + */ + getWindowAlternative: function () { + return this.windowAlternative || null; + }, + + /** + * Get the tabForm value + * @returns {*|null} The tabForm value + */ + getTabForm: function () { + return this.tabForm || null; + }, + + /** + * Get the tabProperties value + * @returns {null|*} The tabProperties value + */ + getTabProperty: function () { + return this.tabProperties || null; + }, + + /** + * Get the tablink value + * @returns {null|*} The tablink value + */ + getTabLink: function () { + return this.tabLink || null; + }, + + /** + * Get the confirmWindow value + * @returns {null|*} The confirmWindow value + */ + getConfirmWin: function () { + return this.confirmWindow || null; + }, + + /** + * Get the tabPanelWindow + * @returns {*|null} + */ + getTabPanelWindow: function () { + return this.tabPanelWindow || null; + }, + + /** + * get the suggestUser value + * @returns {*|null} The suggestUser value + */ + getSuggestUser: function () { + return this.suggestUser || null; + }, + + /** + * Sets the stepsAssignTree + * @returns {*|null} + */ + getStepsTree: function () { + return this.stepsAssignTree || null; + }, + + /** + * Get the stepsAssignAccordion value + * @returns {*|null} The stepsAssignAccordion value + */ + getStepsAccordion: function () { + return this.stepsAssignAccordion || null; + }, + + /** + * get the labelsPanel value + * @returns {null|*} The labelsPanel value + */ + getLabelPanel: function () { + return this.labelsPanel || null; + }, + + /** + * initialize App + * @param relatedShape + */ + initialize: function (relatedShape) { + this.groupType = [ + 'DYNAFORM', 'INPUT_DOCUMENT', + 'OUTPUT_DOCUMENT', 'EXTERNAL' + ]; + this.groupLabel = [ + 'Dynaform (s)'.translate(), 'Input Document (s)'.translate(), + 'OutPut Document (s)'.translate(), 'External (s)'.translate() + ]; + this.stepsType = { + 'DYNAFORM': 'Dynaform'.translate(), + 'INPUT_DOCUMENT': 'Input Document'.translate(), + 'OUTPUT_DOCUMENT': 'Output Document'.translate(), + 'EXTERNAL': 'External'.translate() + }; + + this.setRelatedShape(relatedShape) + .setEvnUid(relatedShape.evn_uid); + + if (this.getRelatedShape().getPorts().getFirst()) { + this.setActUid(this.getRelatedShape().getPorts().getFirst().getConnection().getDestPort().getParent() + .act_uid); + } + if (__env.USER_GUEST) { + $.extend(true, this.userGuest, __env.USER_GUEST); + } + this.stepsAssigned = new PMUI.util.ArrayList(); + this.elementAccordionOpen = new PMUI.util.ArrayList(); + }, + + /** + * Render form + * @returns {WebEntry} + */ + render: function () { + this.getWindow().addItem(this.getTabPanel()); + this.getWindow().open(); + this.getWindow().showFooter(); + this.initializeData(); + return this; + }, + + /** + * Populate Web Entry data + */ + initializeData: function () { + //Pupulate web entry data + this.getInstanceWebEntryData(); + this.setWebEntryConfiguration(); + this.initializeAccordionAndTreepanelData(); + }, + + /** + * Populate accordion and treepanel data + */ + initializeAccordionAndTreepanelData: function () { + var that = this; + //clear global array stepsAssigned + this.stepsAssigned.clear(); + //get accordion data + this.getAccordionData( + function (xhr, response) { + //populate data accordion tabForms + that.loadAccordionItems(response); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + //get getTreePanelData data + this.getTreePanelData( + function (xhr, response) { + //populate data treePanel tabForms + that.loadTreePanelData(response); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + this.addEventSortableInAccordionElements(); + this.addEventSortableInTreePanelElements(); + }, + + /** + * Get all dynaforms + * Execute restClient(GET/project/dynaforms) + * @param successCallback + * @param failureCallback + */ + getDynaforms: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'dynaforms', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get users + * Execute restClient(GET/users/uid_usr) + * @param uidUser + * @param successCallback + * @param failureCallback + */ + getUserData: function (uidUser, successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'users/' + uidUser, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).setBaseEndPoint("").executeRestClient(); + }, + + /** + * Get WebEntry Configuration + * Execute restClient(GET/web-entry-event/event/) + * Execute restClient(POST/web-entry-event/) + * @param successCallback + * @returns {Array} + */ + getWebEntryConfiguration: function (successCallback) { + var that = this, + restProxy = new PMRestClient({ + endpoint: 'web-entry-event/event/' + that.getEvnUid(), + typeRequest: "get", + functionSuccess: function (xhr, response) { + successCallback(response, false); + that.initializeSomeVariables(response, false); + }, + functionFailure: function (xhr, response) { + restProxy = new PMRestClient({ + endpoint: 'web-entry-event', + typeRequest: "post", + data: { + act_uid: that.getActUid(), + evn_uid: that.getEvnUid(), + wee_title: that.getEvnUid(), + we_type: "MULTIPLE", + we_authentication: "LOGIN_REQUIRED", + we_callback: "PROCESSMAKER", + we_callback_url: "", + we_show_in_new_case: "0", + usr_uid: that.getUserGuest().uid || '' + }, + functionSuccess: function (xhr, response) { + successCallback(response, true); + that.initializeSomeVariables(response, true); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + } + }); + restProxy.executeRestClient(); + return this; + }, + + /** + * Update data Web Entry Configuration + * Execute restClient(PUT/web-entry-event/weeuid) + * @param data + * @param successCallback + * @param failureCallback + * @returns {PMRestClient} + */ + updateWebEntryConfiguration: function (data, successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + this.weeUid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get Accordion Data (Tab Forms) + * Execute restClient(GET/steps, GET/step/triggers) + * @returns {Array} + */ + getAccordionData: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/steps', + method: 'GET' + }, { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/step/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).executeRestClient(); + }, + + /** + * Get TreePanel Data (TabForm) + * Execute restClient(GET/available-steps GET/triggers) + * @returns {Array} + */ + getTreePanelData: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/available-steps', + method: 'GET' + }, { + url: 'triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Get steps Availables (TreePanel) + * Execute restClient(GET/available-steps) + * @param successCallback + * @param failureCallback + * @returns {Array} + */ + getStepAvailables: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + this.getConfigWebEntry().tas_uid + '/available-steps', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Load Skin and Languages + * Execute restClient(GET/system/languages GET/system/skins) + * @returns {Array} + */ + getSkinLanguage: function (successCallback, failureCallback) { + return new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'system/languages', + method: 'GET' + }, { + url: 'system/skins', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }).setBaseEndPoint("").executeRestClient(); + }, + + /** + * Delete the WebEntry configuration. + * @param successCallback + * @param failureCallback + */ + deleteWebEntryConfiguration: function (successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + this.weeUid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Generate webEntry Link + * @param weeUid + * @param successCallback + * @param failureCallback + */ + generateLink: function (weeUid, successCallback, failureCallback) { + return new PMRestClient({ + endpoint: 'web-entry-event/' + weeUid + '/generate-link', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + successCallback(xhr, response); + }, + functionFailure: function (xhr, response) { + failureCallback(xhr, response); + } + }).executeRestClient(); + }, + + /** + * Creates an instance of the WebEntry class + * @returns {null} + */ + getInstanceWebEntryData: function () { + this.getWebEntryConfiguration( + function (webEntryEvent, isNew) { + if (isNew) { + webEntryEvent.we_type = 'SINGLE'; + webEntryEvent.we_authentication = 'ANONYMOUS'; + webEntryEvent.wee_url = ''; + webEntryEvent.wee_title = ''; + } + } + ); + return this; + }, + + /** + * Get Main Container Window + * @returns {PMUI.ui.Window} + */ + getWindow: function () { + if (this.getWindowWebEntry() === null) { + this.setWindowWebEntry(this.buildWindow()); + } + return this.getWindowWebEntry(); + }, + + /** + * Build Window Container + * @returns {PMUI.ui.Window} + */ + buildWindow: function () { + var that = this; + return new PMUI.ui.Window({ + id: 'windowWebEntry', + title: 'Web Entry'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + onBeforeClose: function () { + if (that.isNewWebEntry) { + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } else { + that.getWindow().close(); + } + that.getWindow().close(); + }, + buttonPanelPosition: 'bottom', + buttonsPosition: 'right', + buttons: [ + { + id: 'windowWebEntryButtonDelete', + text: 'Delete'.translate(), + handler: function () { + that.handlerDeleteWebEntry(); + }, + buttonType: "error" + }, + { + id: 'windowWebEntryButtonCancel', + text: 'Cancel'.translate(), + handler: function () { + if (that.isNewWebEntry) { + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } else { + that.getWindow().close(); + } + }, + buttonType: "error" + }, + { + id: 'windowWebEntryButtonSave', + text: 'Save'.translate(), + handler: function (e) { + that.checkUserGuest('saveConfig'); + }, + buttonType: 'success' + } + ] + }); + }, + + /** + * Return Second Window Container + * @returns {PMUI.ui.Window} + */ + getWindowAlternativeForm: function () { + if (this.getWindowAlternative() === null) { + this.setWindowAlternative(this.buildWindowAlternative()); + } + return this.getWindowAlternative(); + }, + + /** + * Build Second Window Container + * @returns {PMUI.ui.Window} + */ + buildWindowAlternative: function () { + return new PMUI.ui.Window({ + visibleFooter: true, + title: 'Trigger'.translate(), + footerAlign: 'right', + footerItems: [{ + text: "@@", + id: "secondaryWindow-criteria", + style: { + cssProperties: { + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + }, + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-cancel', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + } + }, { + id: 'secondaryWindow-save', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + } + }] + }); + }, + + /** + * Get TabPanel Container + * @returns {TabPanel} + */ + getTabPanel: function () { + if (this.getTabPanelWindow() === null) { + this.setTabPanelWindow(this.buildPanelWindow()); + } + return this.getTabPanelWindow(); + }, + + /** + * Build TabPanel (TabForms, TabProperties, TabLink) + * @returns {PMUI.panel.TabPanel} + */ + buildPanelWindow: function () { + return new PMUI.panel.TabPanel({ + id: 'windowWebEntryTabPanel', + width: DEFAULT_WINDOW_WIDTH - 50, + items: [ + { + id: 'tabForms', + title: 'Forms'.translate(), + panel: this.getTabForms() + }, + { + id: 'tabProperties', + title: 'Properties'.translate(), + panel: this.getTabProperties() + }, + { + id: 'tabLink', + title: 'Link'.translate(), + panel: this.getTabLinkForm() + } + ], + style: { + cssProperties: { + 'margin-left': '10px' + } + }, + itemsPosition: { + position: 'left' + } + }); + }, + + /** + * Get Panel TabForms + * @returns {Panel} + */ + getTabForms: function () { + if (this.getTabForm() === null) { + this.setTabForm(this.buildTabForms()); + } + return this.getTabForm(); + }, + + /** + * Build Tab Forms + * @returns {PMUI.core.Panel} + */ + buildTabForms: function () { + var that = this, + singleDynaform, + stepsMainContainer; + + singleDynaform = new PMUI.form.Form({ + id: 'singleDynaform', + width: DEFAULT_WINDOW_WIDTH - 220, + height: 180, + name: 'singleDynaform', + visibleHeader: false, + items: [ + { + id: 'singleDynaformRadio', + pmType: 'radio', + labelVisible: false, + value: 'SINGLE', + name: 'options', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'singleDynaform', + label: 'Single Dynaform'.translate(), + value: 'SINGLE', + selected: true + } + ], + onChange: function (newVal, oldVal) { + that.weeFormModeChange(newVal, oldVal); + }, + labelWidth: '0%' + }, + { + id: 'weeSelectDynaform', + name: 'tabFormsDropdownDyanform', + pmType: 'dropdown', + label: 'Dynaform'.translate(), + helper: 'Select Dynaform use in case.'.translate(), + required: true, + controlsWidth: 400, + labelWidth: '25%', + style: { + cssProperties: { + 'padding-left': '100px' + } + }, + options: [ + { + label: 'Select Dynaform'.translate(), + value: '' + } + ] + + }, + { + id: 'multipleStepsRadio', + pmType: 'radio', + labelVisible: false, + value: '', + name: 'options', + required: false, + controlPositioning: 'vertical', + maxDirectionOptions: 4, + options: [ + { + id: 'multipleSteps', + label: 'Multiple Steps'.translate(), + value: 'MULTIPLE' + } + ], + onChange: function (newVal, oldVal) { + that.weeFormModeChange(newVal, oldVal); + }, + labelWidth: '0%' + + } + ] + }); + + stepsMainContainer = new PMUI.core.Panel({ + id: 'stepsMainContainer', + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH - 220, + items: [ + that.getStepsAssignTree(), + that.getStepsAssignAccordion() + ] + }); + + return new PMUI.core.Panel({ + id: 'mainContainer', + layout: 'vbox', + width: DEFAULT_WINDOW_WIDTH - 220, + items: [ + singleDynaform, + that.getLabelsPanel(), + stepsMainContainer + ] + }); + }, + + /** + * Get Panel TabProperties + * @returns {Panel} + */ + getTabProperties: function () { + if (this.getTabProperty() === null) { + this.setTabProperty(this.buildTabProperties()); + } + return this.getTabProperty(); + }, + + /** + * Build TabProperties + * @returns {PMUI.core.Panel} + */ + buildTabProperties: function () { + var that = this, + propertiesForm; + + propertiesForm = new PMUI.form.Form({ + id: 'idTabFormProperties', + width: DEFAULT_WINDOW_WIDTH - 220, + visibleHeader: false, + items: [ + { + id: 'tabPropertiesWebEntryTitle', + pmType: 'text', + name: 'tabPropertiesWebEntryTitle', + valueType: 'string', + label: 'Web Entry Title'.translate(), + placeholder: 'Enter a title displayed on web entry window (if applies)'.translate(), + helper: 'Enter a title displayed on web entry window (if applies).'.translate(), + required: false, + controlsWidth: 458, + labelWidth: '23%' + }, + { + id: 'tabPropRadioAuthentication', + pmType: 'radio', + labelVisible: true, + label: 'Authentication'.translate(), + value: 'ANONYMOUS', + name: 'authentication', + required: true, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'tabPropertiesOptionRadioAnonymous', + label: 'Anonymous'.translate(), + value: 'ANONYMOUS', + selected: false + } + ], + onChange: function (newVal, oldVal) { + that.anonimusProcedure(newVal, oldVal); + }, + labelWidth: '23%' + }, + { + id: 'tabPropertiesRequireUserLogin', + pmType: 'radio', + labelVisible: false, + value: 'LOGIN_REQUIRED', + required: false, + name: 'authentication', + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'tabPropertiesRadioRequireUserLogin', + label: 'Require user login'.translate(), + value: 'LOGIN_REQUIRED', + selected: false + } + ], + onChange: function (newVal, oldVal) { + that.loginRequired(newVal, oldVal); + }, + labelWidth: '23%' + }, + { + id: 'tabPropertiesHideLoogedInformationBar', + pmType: 'checkbox', + name: 'tabPropertiesHideLoogedInformationBar', + labelVisible: false, + disabled: true, + options: [ + { + id: 'hideLoogedInformationBar', + label: 'Hide Logged Information Bar'.translate(), + value: '1', + selected: false + } + ], + style: { + cssProperties: { + 'padding-left': '50px' + } + } + }, + { + id: 'tabPropertiesRadioCallback', + pmType: 'radio', + labelVisible: true, + label: 'Callback Action'.translate(), + value: 'PROCESSMAKER', + required: true, + disabled: false, + controlPositioning: 'vertical', + labelPosition: 'left', + helper: 'Callback Action...'.translate(), + maxDirectionOptions: 4, + options: [ + { + id: 'redirectPM', + label: 'Redirect to ProcessMaker predefined response page'.translate(), + value: 'PROCESSMAKER', + selected: true + }, + { + id: 'redirectURL', + label: 'Redirect to custom URL'.translate(), + value: 'CUSTOM' + }, + { + id: 'redirectCustom', + label: 'Redirect to custom URL and clear login info'.translate(), + value: 'CUSTOM_CLEAR' + } + ], + onChange: function (newVal, oldVal) { + that.callbackActionChange(newVal, oldVal); + + }, + labelWidth: '23%' + }, + new CriteriaField({ + id: 'criteriaFieldCustomUrl', + pmType: 'text', + name: 'criteriaFieldCustomUrl', + label: 'Custom URL'.translate(), + placeholder: 'Enter a valid URL to be redirected when entry will be completed'.translate(), + labelWidth: '23%', + controlsWidth: 455, + required: true, + disabled: true + }), + { + id: 'showInNewCase', + pmType: 'checkbox', + name: 'showInNewCase', + label: 'Show task in New Case'.translate(), + labelVisible: true, + options: [ + { + id: 'showTaskInNewCase', + value: 'showCase', + selected: false + } + ], + onChange: function (newValue, oldValue) { + this.setValue(newValue); + } + } + ] + }); + + $(propertiesForm.getItem('tabPropRadioAuthentication').getHTML()) + .append($(that.getSuggestField().createHTML())); + + return propertiesForm; + }, + + /** + * Get Panel TabLink + * @returns {Panel} + */ + getTabLinkForm: function () { + if (this.getTabLink() === null) { + this.setTabLink(this.buildTabLink()); + } + return this.getTabLink(); + }, + + /** + * Build TabLink + * @returns {PMUI.core.Panel} + */ + buildTabLink: function () { + var that = this, + tfromLink; + + tfromLink = new PMUI.form.Form({ + id: 'idTabFormLink', + width: DEFAULT_WINDOW_WIDTH - 220, + visibleHeader: false, + items: [ + { + id: 'tabLinkRadioGeneration', + pmType: 'radio', + labelVisible: true, + label: 'Link Generation'.translate(), + value: 'DEFAULT', + name: 'options', + required: true, + controlPositioning: 'vertical', + labelPosition: 'left', + helper: 'Link Generation'.translate(), + controlsWidth: 485, + labelWidth: '24.5%', + maxDirectionOptions: 3, + options: [ + { + id: 'generateLinkDefaultValues', + label: 'Generate link using workspace default values (skin, language)'.translate(), + value: 'DEFAULT', + selected: 'true' + }, + { + id: 'advancedLinkGeneration', + label: 'Advanced link generation'.translate(), + value: 'ADVANCED' + } + ], + onChange: function (newVal) { + that.linkGenerationOnChange(newVal); + }, + labelWidth: '18%' + }, + { + id: 'tabLinkDropdownSkin', + name: 'tabLinkDropdownSkin', + pmType: 'dropdown', + label: 'Skin'.translate(), + helper: 'Select a Skin.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: '24.5%', + onChange: function () { + that.setLinkText(tfromLink, ''); + }, + options: [ + { + label: 'Select a Skin'.translate(), + value: '' + } + ] + }, + { + id: 'tabLinkDropdownLanguage', + name: 'tabLinkDropdownLanguage', + pmType: 'dropdown', + label: 'Language'.translate(), + helper: 'Select a language.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: '24.5%', + onChange: function () { + that.setLinkText(tfromLink, ''); + }, + options: [ + { + label: 'Select a language'.translate(), + value: '' + } + ] + }, + { + id: 'tablinkTextCustomDomain', + pmType: 'text', + name: 'tablinkTextCustomDomain', + valueType: 'string', + label: 'Custom Hostname'.translate(), + placeholder: 'https://example.com:8080'.translate(), + helper: 'Protocol and Hostname, port is optional.'.translate(), + required: true, + controlsWidth: 485, + labelWidth: "24.5%", + validators: [ + { + pmType: "regexp", + criteria: /^(https?:\/\/)?(((\d{1,3}\.){3}\d{1,3})|(([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?))(:\d+)?$/i, + errorMessage: 'Enter a Protocol and Hostname valid value.'.translate() + } + ], + onChange: function () { + that.setLinkText(tfromLink, ''); + } + }, + { + id: 'panelLinkForm', + pmType: 'panel', + layout: 'hbox', + required: true, + width: '155px', + style: { + cssProperties: { + 'margin-left': '-10px', + 'margin-top': '-10px' + } + }, + items: [ + { + pmType: 'annotation', + text: 'Web Entry URL:'.translate(), + id: 'webEntryLinkLabel', + required: true, + name: 'webEntryLinkLabel' + }, + { + pmType: 'annotation', + id: 'webEntryLink', + name: 'webEntryLink', + text: '', + required: true, + textType: 1, + style: { + cssProperties: { + 'margin-left': '-173px' + } + } + } + ] + }, + new PMUI.field.ButtonField({ + id: 'buttonFieldGenerateLink', + pmType: 'buttonField', + value: 'Generate Link'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 180, + proportion: 0.6, + handler: function (field) { + that.checkUserGuest('generateLink'); + }, + buttonType: 'success', + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '10px', + 'padding-right': '0px', + 'padding-bottom': '1px', + 'padding-left': '130px' + } + } + }) + ] + }); + + tfromLink.getItem('buttonFieldGenerateLink').getControl(0).button.setButtonType('success'); + + return tfromLink; + }, + + /** + * Get MessageWindow Container + * @returns {PMUI.ui.MessageWindow} + */ + getConfirmWindow: function () { + if (this.getConfirmWin() === null) { + this.setConfirmWin(this.buildConfirmWindow()); + } + return this.getConfirmWin(); + }, + + /** + * Build MessageWindow + * @returns {PMUI.ui.MessageWindow} + */ + buildConfirmWindow: function () { + return new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: '', + message: '', + footerItems: [ + { + id: 'confirmWindow-footer-no', + text: 'No'.translate(), + visible: true, + buttonType: 'error' + }, { + id: 'confirmWindow-footer-yes', + text: 'Yes'.translate(), + visible: true, + buttonType: 'success' + } + ], + visibleFooter: true + }); + }, + + /** + * Handler button for delete web entry config + */ + handlerDeleteWebEntry: function () { + var that = this, + confirmWindow, + yesButton, + noButton; + confirmWindow = that.getConfirmWindow() + .setMessage('Are you sure you want to delete the Web Entry configuration?'.translate()); + yesButton = that.getConfirmWindow().footer.getItem('confirmWindow-footer-yes'); + yesButton.setHandler(function () { + confirmWindow.close(); + that.deleteWebEntryConfiguration( + function () { + that.getWindow().close(); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + noButton = that.getConfirmWindow().footer.getItem('confirmWindow-footer-no'); + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + that.getConfirmWindow().open(); + return this; + }, + + /** + * Handler button for save web entry config + * @param method + */ + checkUserGuest: function (method) { + var title = 'Web Entry Anonymous Authentication'.translate(), + message = ('Current selected user to act as anonymous will be replaced by the Guest user. ' + + 'This action cannot be undone. Do you want to proceed?').translate(); + + //Validate the data before saving the configuration or generate the link + if (this.isValidWebEntryData(method)) { + (method === 'saveConfig') ? this.handlerSaveButton(message, title) : this.handlerGenerateLinkButton(message, title); + } + return this; + }, + + /** + * Check userGuestUID and save Config + * @param message + * @param title + * @returns {WebEntry} + */ + handlerSaveButton: function (message, title) { + var that = this, + messageWindow = this.getConfirmWindow(); + //Validation is done to be compatible with older versions of webEntry (Now exist guest-type user). + if (this.getUserGuest().uid && this.getSuggestField().value !== this.getUserGuest().uid) { + messageWindow.setMessage(message); + messageWindow.setTitle(title); + + //handler for cancel button + messageWindow.footer.getItem('confirmWindow-footer-no').setHandler(function () { + messageWindow.close(); + }); + + //handler for yes button + messageWindow.footer.getItem('confirmWindow-footer-yes').setHandler(function () { + messageWindow.close(); + that.getSuggestField().set('value', that.getUserGuest().uid); + that.saveWebEntryConfiguration( + function () { + that.getWindow().close(); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + messageWindow.open(); + } else { + //For new configurations we save the configuration without any GUEST user validation. + this.saveWebEntryConfiguration( + function () { + that.getWindow().close(); + }, function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } + return this; + }, + + /** + * Check userGuestUID and generate webEntry Link + * @param message + * @param title + * @returns {WebEntry} + */ + handlerGenerateLinkButton: function (message, title) { + var that = this, + formLink = this.getTabLinkForm(), + messageWindow = this.getConfirmWindow(); + //Validation is done to be compatible with older versions of webEntry (Now exist guest-type user). + if (this.getUserGuest().uid && this.getSuggestField().value !== this.getUserGuest().uid) { + messageWindow.setMessage(message); + messageWindow.setTitle(title); + + //handler for cancel button + messageWindow.footer.getItem('confirmWindow-footer-no').setHandler(function () { + messageWindow.close(); + }); + //handler for yes button + + messageWindow.footer.getItem('confirmWindow-footer-yes').setHandler(function () { + messageWindow.close(); + that.getSuggestField().set('value', that.getUserGuest().uid); + that.setLinkText(formLink, ''); + //save Web Entry Configuration + that.saveWebEntryConfiguration( + function (xhr, response) { + that.getConfigWebEntry().usr_uid = response.usr_uid || that.getConfigWebEntry().usr_uid; + //generate webEntry Link + that.generateLink( + that.getWeeUid(), + function (xhr, response) { + that.setLinkText(formLink, (response.link) ? response.link : ''); + that.initializeAccordionAndTreepanelData(); + that.getSuggestField().html.find("input") + .val(that.getUserGuest().firstname + " " + "(" + that.getUserGuest().username + ")"); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }); + messageWindow.open(); + } else { + //For new configurations we generate the webEntry Link without any GUEST user validation. + this.saveWebEntryConfiguration( + function () { + that.generateLink( + that.getWeeUid(), + function (xhr, response) { + that.setLinkText(formLink, (response.link) ? response.link : ''); + that.initializeAccordionAndTreepanelData(); + }, + function (xhr, response) { + that.setLinkText(formLink, ''); + PMDesigner.msgWinError(response.error.message); + } + ); + }, + function (xhr, response) { + that.setLinkText(formLink, ''); + PMDesigner.msgWinError(response.error.message); + } + ); + } + return this; + }, + + /** + * Get Steps AssignAccordion + * @returns {PMUI.panel.AccordionPanel} + */ + getStepsAssignAccordion: function () { + if (this.getStepsAccordion() === null) { + this.setStepsAccordion(this.buildStepsAssignAccordion()); + } + return this.getStepsAccordion(); + }, + + /** + * Build Steps Assign Accordion + * @returns {PMUI.panel.AccordionPanel} + */ + buildStepsAssignAccordion: function () { + var that = this; + return new PMUI.panel.AccordionPanel({ + id: 'stepsAssignAccordion', + multipleSelection: true, + hiddenTitle: true, + proportion: 1.5, + style: { + cssProperties: { + margin: '0px 0px 0px 0px' + }, + cssClasses: ['mafe-border-panel'] + }, + listeners: { + select: function (accordionItem, event) { + var buttonExpand, buttonCollapse, itemsAccod; + itemsAccod = that.getStepsAssignAccordion().items; + if (accordionItem.collapsed) { + if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { + that.elementAccordionOpen.remove(accordionItem); + } + } else { + if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { + that.elementAccordionOpen.insert(accordionItem); + } + } + buttonCollapse = that.getLabelsPanel().getItem('collapse-button'); + buttonExpand = that.getLabelsPanel().getItem('expand-button'); + if (that.elementAccordionOpen.getSize() === 0) { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(true); + } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { + buttonExpand.setDisabled(true); + buttonCollapse.setDisabled(false); + } else { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(false); + } + } + } + }); + }, + + /** + * Get steps AssignTree + * @returns {PMUI.core.Panel} + */ + getStepsAssignTree: function () { + if (this.getStepsTree() === null) { + this.setStepsTree(this.buildStepsAssignTree()); + } + return this.getStepsTree(); + }, + + /** + * Build steps AssignTree + * @returns {PMUI.panel.TreePanel} + */ + buildStepsAssignTree: function () { + return new PMUI.panel.TreePanel({ + id: 'stepsAssignTree', + proportion: 0.5, + height: 475, + filterable: true, + autoBind: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nodeDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true, + collapsed: false, + itemsDataBind: 'items', + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + behavior: 'drag' + }, + style: { + cssProperties: { + margin: '0px 0px 0px 0px', + float: 'left', + overflow: 'auto' + }, + cssClasses: ['mafe-border-panel'] + } + }); + }, + + /** + * Get Label Panel + * @returns {PMUI.core.Panel} + */ + getLabelsPanel: function () { + if (this.getLabelPanel() === null) { + this.setLabelPanel(this.buildLabelPanel()); + } + return this.getLabelPanel(); + }, + + /** + * Build Label Panel + * @returns {PMUI.core.Panel} + */ + buildLabelPanel: function () { + var that = this; + return new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH - 220, + layout: "hbox", + items: [ + new PMUI.field.TextAnnotationField({ + text: 'Available Elements'.translate(), + proportion: 1.12, + text_Align: 'center' + }), + new PMUI.field.TextAnnotationField({ + text: 'Assigned Elements (Drop here)'.translate(), + proportion: 1.3, + text_Align: 'center' + }), + new PMUI.ui.Button({ + buttonType: 'link', + text: 'Expand all'.translate(), + id: 'expand-button', + proportion: 1.2, + handler: function () { + that.expandAndCollapseHandler('collapse-button', 'expand-button'); + } + }), + new PMUI.ui.Button({ + buttonType: 'link', + text: 'Collapse all'.translate(), + id: 'collapse-button', + proportion: 1.1, + disabled: true, + handler: function () { + that.expandAndCollapseHandler('expand-button', 'collapse-button'); + } + }) + ] + }); + }, + + /** + * Get SuggestField Control + * @returns {SuggestField} + */ + getSuggestField: function () { + if (this.getSuggestUser() === null) { + this.setSuggestUser(this.createSugesstField()); + } + return this.getSuggestUser(); + }, + + /** + * Create Field Suggest (User) + * @returns {SuggestField} + */ + createSugesstField: function () { + return new SuggestField({ + id: 'idSuggestUser', + label: 'Users'.translate(), + width: 450, + placeholder: 'Suggest users'.translate(), + required: true, + disabled: true, + helper: 'When the form is submitted a new case is created with this user account.'.translate(), + dynamicLoad: { + data: [{ + key: 'usr_uid', + label: ['usr_firstname', 'usr_lastname', '(', 'usr_username', ')'] + }], + keys: { + url: HTTP_SERVER_HOSTNAME + '/api/1.0/' + WORKSPACE, + accessToken: credentials.access_token, + endpoints: [{ + method: 'GET', + url: 'users' + }] + } + } + }); + }, + + /** + * Generate Web Entry Link + * @param formLink + * @param linkText + */ + setLinkText: function (formLink, linkText) { + formLink.getItem('panelLinkForm').getItem('webEntryLink') + .setText('' + linkText + ''); + return this; + }, + + /** + * Initialize Some Variables for web Entry (weeUId, actUid, evnUid, response, isNewWebEntry) + * @param response + * @param newWebEntry + */ + initializeSomeVariables: function (response, newWebEntry) { + this.setWeeUid(response.wee_uid) + .setActUid(response.act_uid) + .setEvnUid(response.evn_uid) + .setConfigWebEntry(response) + .setIsNewWebEntry(newWebEntry); + return this; + }, + + /** + * Collapse and Expand Accordion Handler + * @param enableItem + * @param disableItem + */ + expandAndCollapseHandler: function (enableItem, disableItem) { + var items, + i, + item; + items = this.getStepsAssignAccordion().getItems(); + this.getLabelsPanel().getItem(enableItem).setDisabled(false); + this.getLabelsPanel().getItem(disableItem).setDisabled(true); + if (enableItem === 'collapse-button') { + this.elementAccordionOpen.clear(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + item.expand(); + this.elementAccordionOpen.insert(item); + } + } else { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + this.elementAccordionOpen.remove(item); + item.collapse(); + } + } + }, + + /** + * Disable MultipleSteps or Single Dynaform (tabForms) + * @returns {disableMultipleSteps} + */ + weeFormModeChange: function (newVal, oldVal) { + if (newVal === 'SINGLE') { + this.disableMultipleSteps('SINGLE'); + } else { + this.disableSingleDynaform('MULTIPLE'); + this.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform').hideMessage(); + this.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform') + .getControl(0).style.removeClasses(['error']); + } + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Disable MultipleSteps (tabForms) + * @param singleMultiple + * @returns {WebEntry} + */ + disableMultipleSteps: function (singleMultiple) { + var singleDyna = this.getTabForms().getItem('singleDynaform'); + singleDyna.getItem('multipleStepsRadio').setValue(''); + singleDyna.getItem('weeSelectDynaform').enable(); + singleDyna.getItem('weeSelectDynaform').setRequired(true); + singleDyna.getItem('singleDynaformRadio').setValue(singleMultiple); + singleDyna.getItem('singleDynaformRadio').getControl(0).select(); + //Hide step panel + this.getLabelsPanel().setVisible(false); + this.getTabForms().getItem('stepsMainContainer').setVisible(false); + return this; + }, + + /** + * Disable Form SingleDynaform (tabForms) + * @param singleMultiple + * @returns {WebEntry} + */ + disableSingleDynaform: function (singleMultiple) { + var singleDyna = this.getTabForms().getItem('singleDynaform'); + singleDyna.getItem('singleDynaformRadio').setValue(''); + singleDyna.getItem('weeSelectDynaform').disable(); + singleDyna.getItem('weeSelectDynaform').setRequired(false); + singleDyna.getItem('multipleStepsRadio').setValue(singleMultiple); + singleDyna.getItem('multipleStepsRadio').getControl(0).select(); + //Show step panel + this.getLabelsPanel().setVisible(true); + this.getTabForms().getItem('stepsMainContainer').setVisible(true); + return this; + }, + + /** + * Change handler + * @param newValue + * @param oldValue + * @returns {loginRequired} + */ + anonimusProcedure: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(), + //The Callback Actions (PROCESSMAKER is 0, CUSTOM is 1, and CUSTOM_CLEAR is 2) + callbackAction = 2; + propertiesForm.getItem('tabPropertiesRequireUserLogin').setValue('[]'); + propertiesForm.getItem('tabPropertiesHideLoogedInformationBar').disable(); + propertiesForm.getItem('tabPropRadioAuthentication').setRequired(true); + this.getSuggestField().setRequired(true); + this.getSuggestField().hideMessageRequired(); + propertiesForm.getItem('tabPropertiesRadioCallback').disableOption(callbackAction); + if (propertiesForm.getItem('tabPropertiesRadioCallback').getValue() === 'CUSTOM_CLEAR') { + propertiesForm.getItem('tabPropertiesRadioCallback').getControl(callbackAction).deselect(); + propertiesForm.getItem('tabPropertiesRadioCallback').setValue(''); + } + propertiesForm.getItem('criteriaFieldCustomUrl').disable(); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.disable(); + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Change chandler + * @param newValue + * @param oldValue + * @returns {loginRequired} + */ + loginRequired: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(), + //The Callback Actions (PROCESSMAKER is 0, CUSTOM is 1, and CUSTOM_CLEAR is 2) + callbackAction = 2; + propertiesForm.getItem('tabPropRadioAuthentication').setValue('[]'); + propertiesForm.getItem('tabPropRadioAuthentication').setRequired(false); + + this.getSuggestField().setRequired(false); + this.getSuggestField().hideMessageRequired(); + propertiesForm.getItem('tabPropertiesHideLoogedInformationBar').enable(); + propertiesForm.getItem('tabPropertiesRadioCallback').enableOption(callbackAction); + this.callbackActionChange(propertiesForm.getItem('tabPropertiesRadioCallback').getValue(), ''); + this.setLinkText(this.getTabLinkForm(), ''); + return this; + }, + + /** + * Change handler + * @param newValue + * @param oldValue + * @returns {callbackActionChange} + */ + callbackActionChange: function (newValue, oldValue) { + var propertiesForm = this.getTabProperties(); + propertiesForm.getItem("tabPropertiesRadioCallback").setValue(newValue); + switch (newValue) { + case 'PROCESSMAKER': + propertiesForm.getItem('criteriaFieldCustomUrl').disable(); + propertiesForm.getItem('criteriaFieldCustomUrl').setRequired(false); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.disable(); + break; + case 'CUSTOM': + case 'CUSTOM_CLEAR': + propertiesForm.getItem('criteriaFieldCustomUrl').enable(); + propertiesForm.getItem('criteriaFieldCustomUrl').setRequired(true); + propertiesForm.getItem('criteriaFieldCustomUrl').buttonHTML.enable(); + break; + } + return this; + }, + + /** + * Change handler + * @param newValue + * @returns {linkGenerationOnChange} + */ + linkGenerationOnChange: function (newValue) { + var required, + skin, + language, + domain, + tfromLink; + tfromLink = this.getTabLinkForm(); + required = newValue === 'ADVANCED'; + skin = tfromLink.getItem('tabLinkDropdownSkin'); + language = tfromLink.getItem('tabLinkDropdownLanguage'); + domain = tfromLink.getItem('tablinkTextCustomDomain'); + this.setLinkText(tfromLink, ''); + skin.setRequired(required); + language.setRequired(required); + domain.setRequired(required); + if (required) { + skin.enable(); + language.enable(); + domain.enable(); + } else { + skin.disable(); + domain.hideMessage(); + language.disable(); + domain.disable(); + domain.getControl(0).style.removeClasses(['error']); + } + return this; + }, + + /** + * Save webEntry Configuration + * @param successCallback + * @param failureCallback + */ + saveWebEntryConfiguration: function (successCallback, failureCallback) { + var data, + //tabs window web entry + tabProperties = this.getTabPanel().getItem('tabProperties'), + tabLink = this.getTabPanel().getItem('tabLink'), + //form tabs + dataTabSingleDyn = this.getTabForms().getItem('singleDynaform'), + dataTabProperties = tabProperties.getPanel('idTabProperties'), + dataTabLink = tabLink.getPanel('idTabLink'); + + //Prepare Data + data = this.prepareData(dataTabSingleDyn, dataTabProperties, dataTabLink); + //Save web Entry configuration + this.updateWebEntryConfiguration(data, successCallback, failureCallback); + return this; + }, + + /** + * Validate Web Entry Data + * @param method + */ + isValidWebEntryData: function (method) { + var valid = true, + //tabs window web entry + tabForm = this.getTabPanel().getItem('tabForms'), + tabProperties = this.getTabPanel().getItem('tabProperties'), + tabLink = this.getTabPanel().getItem('tabLink'), + //form tabs + dataTabSingleDyn = this.getTabForms().getItem('singleDynaform'), + dataTabProperties = tabProperties.getPanel('idTabProperties'), + dataTabLink = tabLink.getPanel('idTabLink'), + //selected tab + selectedTab = null; + + // validate form tab + if (dataTabSingleDyn instanceof PMUI.form.Form) { + valid = valid && dataTabSingleDyn.isValid(); + selectedTab = !valid && !selectedTab ? tabForm : selectedTab; + } + //validate property tab + if (dataTabProperties instanceof PMUI.form.Form) { + valid = valid && dataTabProperties.isValid(); + selectedTab = !valid && !selectedTab ? tabProperties : selectedTab; + } + //validate suggestField + if (!this.getSuggestField().isValid()) { + this.getSuggestField().showMessageRequired(); + valid = valid && this.getSuggestField().isValid(); + selectedTab = !valid && !selectedTab ? tabProperties : selectedTab; + } + //validate link Tab + if (dataTabLink instanceof PMUI.form.Form) { + valid = valid && dataTabLink.isValid(); + selectedTab = !valid && !selectedTab ? tabLink : selectedTab; + } + if (!valid) { + selectedTab.select(); + } + //validate Link Generate Button + if (!$(dataTabLink.getItem('panelLinkForm').getItem('webEntryLink').text).attr('href') && + method !== 'generateLink') { + PMDesigner.msgFlash('Please press the \"Generate Link\" button.'.translate(), + this.getWindow(), 'error', 3000, 5); + valid = false; + tabLink.select(); + } + return valid; + }, + + /** + * Prepare Data + * @param dataTabSingleDyn + * @param dataTabProperties + * @param dataTabLink + */ + prepareData : function (dataTabSingleDyn, dataTabProperties, dataTabLink) { + var data = {}; + data['act_uid'] = this.getActUid(); + data['evn_uid'] = this.getEvnUid(); + data['wee_title'] = this.getEvnUid(); + data['we_type'] = (dataTabSingleDyn.getItem('singleDynaformRadio').getValue()) ? 'SINGLE' : 'MULTIPLE'; + data['dyn_uid'] = (data['we_type'] === 'SINGLE') ? dataTabSingleDyn.getItem('weeSelectDynaform') + .getValue() : ''; + data['we_custom_title'] = dataTabProperties.getItem('tabPropertiesWebEntryTitle').getValue(); + data['we_authentication'] = dataTabProperties.getItem('tabPropRadioAuthentication').getValue() === '[]' ? + 'LOGIN_REQUIRED' : 'ANONYMOUS'; + data['usr_uid'] = this.getSuggestField().value; + data['we_hide_information_bar'] = dataTabProperties.getItem('tabPropertiesHideLoogedInformationBar') + .getValue() === '[]' ? '0' : '1'; + data['we_callback'] = dataTabProperties.getItem('tabPropertiesRadioCallback').getValue(); + data['we_callback_url'] = (data['we_callback'] !== 'PROCESSMAKER') ? + dataTabProperties.getItem('criteriaFieldCustomUrl').getValue() : ''; + data['we_link_generation'] = dataTabLink.getItem('tabLinkRadioGeneration').getValue(); + data['we_link_skin'] = dataTabLink.getItem('tabLinkDropdownSkin').getValue(); + data['we_link_language'] = dataTabLink.getItem('tabLinkDropdownLanguage').getValue(); + data['we_link_domain'] = (data['we_link_generation'] === 'ADVANCED') ? + dataTabLink.getItem('tablinkTextCustomDomain').getValue() : ''; + data['we_show_in_new_case'] = (dataTabProperties.getItem('showInNewCase').getValue() === '["showCase"]') ? 1 : 0; + return data; + }, + + /** + * Populate all tabPanels (TabForms, TabProperties, TabLink) with data config + * return void + */ + setWebEntryConfiguration: function () { + this.setConfigDataTabForms(); + this.setConfigDataTabProperties(); + this.setConfigDataTabLink(); + this.getWindow().getItem('windowWebEntryTabPanel').getItem('tabForms').select(); + return this; + }, + + /** + * Load and populate Dynaforms Items + * @returns {*} + */ + setConfigDataTabForms: function () { + var that = this, + i, + data, + options = [], + dynaformsControl, + dynaforms = []; + + //execute Rest (get Dynaforms) + this.getDynaforms( + function (xhr, response) { + dynaforms = response[0].response; + //get Controls tab-Forms + dynaformsControl = that.getTabForms().getItem('singleDynaform').getItem('weeSelectDynaform'); + + //Set data Dropdown Single Dynaform + for (i = 0; i < dynaforms.length; i += 1) { + data = {}; + data.label = dynaforms[i]['dyn_title']; + data.value = dynaforms[i]['dyn_uid']; + if (that.getConfigWebEntry().dyn_uid === data.value && + that.getConfigWebEntry().evn_uid === that.getRelatedShape()['evn_uid']) { + data.selected = true; + } + options.push(data); + } + dynaformsControl.setOptions(options); + + //set Disable/Enable single or multiple steps + (that.getConfigWebEntry().we_type === 'SINGLE') ? + that.disableMultipleSteps(that.getConfigWebEntry().we_type) : + that.disableSingleDynaform(that.getConfigWebEntry().we_type); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + + /** + * TabProperties Panel + * Assigns values to tabProperties fields + */ + setConfigDataTabProperties: function () { + var that = this, + webEntryTitle, + radioAuthentication, + radioRequiredLogin, + informationBar, + radioCollback, + customUrl, + user, + showInNewCase; + + //get Controls Tab-Properties + this.getTabPanel().getItem('tabProperties').select(); + webEntryTitle = this.getTabProperties().getItem('tabPropertiesWebEntryTitle'); + radioAuthentication = this.getTabProperties().getItem('tabPropRadioAuthentication'); + radioRequiredLogin = this.getTabProperties().getItem('tabPropertiesRequireUserLogin'); + radioCollback = this.getTabProperties().getItem('tabPropertiesRadioCallback'); + customUrl = this.getTabProperties().getItem('criteriaFieldCustomUrl'); + informationBar = this.getTabProperties().getItem('tabPropertiesHideLoogedInformationBar'); + showInNewCase = this.getTabProperties().getItem('showInNewCase'); + + //set webentry Title + webEntryTitle.setValue(this.getConfigWebEntry().we_custom_title); + + //Loggin required or Anonymous + radioCollback.setValue(this.getConfigWebEntry().we_callback); + if (this.getConfigWebEntry().we_authentication === 'LOGIN_REQUIRED') { + radioRequiredLogin.getControl(0).select(); + radioRequiredLogin.setValue(this.getConfigWebEntry().we_authentication); + this.loginRequired(); + } else { + radioAuthentication.getControl(0).select(); + radioAuthentication.setValue(this.getConfigWebEntry().we_authentication); + this.anonimusProcedure(); + } + + //set value suggest user + this.getSuggestField().html.find('input').val(''); + this.getConfigWebEntry().usr_uid = this.getConfigWebEntry().usr_uid || this.getUserGuest().uid; + if (this.getConfigWebEntry().usr_uid) { + this.getUserData( + this.getConfigWebEntry().usr_uid, + function (xhr, response) { + user = response[0].response; + that.getSuggestField().html.find("input").val(user.usr_firstname + " " + + user.usr_lastname + " " + "(" + user.usr_username + ")"); + that.getSuggestField().set("value", user.usr_uid); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + } + + //set Hide Logged Information Bar + if (this.getConfigWebEntry().we_hide_information_bar === '1') { + informationBar.setValue('["1"]'); + informationBar.getControl(0).select(); + } else { + informationBar.setValue('[]'); + informationBar.getControl(0).deselect(); + } + + //set Callback Action + switch (this.getConfigWebEntry().we_callback) { + case 'PROCESSMAKER': + radioCollback.getControl(0).select(); + break; + case 'CUSTOM': + radioCollback.getControl(1).select(); + break; + case 'CUSTOM_CLEAR': + radioCollback.getControl(2).select(); + break; + } + + //set custom URL + customUrl.setValue(this.getConfigWebEntry().we_callback_url); + + //set show task in new case + if (this.getConfigWebEntry().we_show_in_new_case === '1'){ + showInNewCase.setValue('["showCase"]'); + }else{ + showInNewCase.setValue('[]'); + } + + //customize suggest styles + this.getSuggestField().inputField[0].style.width = '280px'; + this.getSuggestField().inputLabel[0].parentElement.style.width = '120px'; + this.getSuggestField().inputLabel[0].parentElement.style.marginLeft = '220px'; + }, + + /** + * TabLink Panel + * Assigns values to tabLink fields + */ + setConfigDataTabLink: function () { + var that = this, + options = [], + customDomain, + radioGeneration, + languages = [], + skins = [], + dropDownLanguages, + dropDownSkins, + data, + i; + + //execute Rest (Get languages and Skins) + this.getSkinLanguage( + function (xhr, response) { + languages = response[0].response.data; + skins = response[1].response.data; + //get controls Tab-link + that.getTabPanel().getItem('tabLink').select(); + radioGeneration = that.getTabLinkForm().getItem('tabLinkRadioGeneration'); + dropDownSkins = that.getTabLinkForm().getItem('tabLinkDropdownSkin'); + dropDownLanguages = that.getTabLinkForm().getItem('tabLinkDropdownLanguage'); + customDomain = that.getTabLinkForm().getItem('tablinkTextCustomDomain'); + + //set Link generation (Default or Advanced) + radioGeneration.setValue(that.getConfigWebEntry().we_link_generation); + (that.getConfigWebEntry().we_link_generation === 'DEFAULT') ? radioGeneration.getControl(0).select() : + radioGeneration.getControl(1).select(); + + //set Languages Dropdown + if (jQuery.isArray(languages)) { + for (i = 0; i < languages.length; i += 1) { + data = {}; + data.label = languages[i].LANG_NAME; + data.value = languages[i].LANG_ID; + if (languages[i].LANG_ID === that.getConfigWebEntry().we_link_language) { + data.selected = true; + } + options.push(data); + } + dropDownLanguages.setOptions(options); + } + //set Skins Dropdown + if (jQuery.isArray(skins)) { + options = []; + for (i = 0; i < skins.length; i += 1) { + data = {}; + data.label = skins[i].SKIN_NAME; + data.value = skins[i].SKIN_FOLDER_ID; + if (that.getConfigWebEntry().we_link_skin === skins[i].SKIN_FOLDER_ID) { + data.selected = true; + } + options.push(data); + } + dropDownSkins.setOptions(options); + } + + //set Custom Domain + customDomain.setValue(that.getConfigWebEntry().we_link_domain); + //Enable or Disable (Skin, Language, CustomDomain) + that.linkGenerationOnChange(that.getConfigWebEntry().we_link_generation); + //set Link text + that.setLinkText(that.getTabLinkForm(), that.getConfigWebEntry().wee_url); + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + }, + + /** + * Load and populate Accordion Data Items + * @param response + */ + loadAccordionItems: function (response) { + var firstResp = [], + secondResp = [], + i, + item, + assigmentConfig, + firstRes = 0, + secondRes = 1; + this.getStepsAssignAccordion().clearItems(); + if (jQuery.isArray(response) && response.length) { + if (typeof response[firstRes] === "object") { + firstResp = response[firstRes].response ? response[firstRes].response : []; + } + if (typeof response[secondRes] === "object") { + secondResp = response[secondRes].response ? response[secondRes].response : []; + } + } + if (firstResp.length) { + for (i = 0; i < firstResp.length; i += 1) { + item = this.createAccordionItem(firstResp[i], true, true); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = firstResp[i]; + this.customAccordionItemButtons(item.html, firstResp[i], item); + } + } + assigmentConfig = { + step_type_obj: "Assignment".translate(), + triggers: secondResp, + st_type: "ASSIGNMENT", + obj_title: "Assignment".translate(), + step_uid_obj: "Assignment" + }; + item = this.createAccordionItem(assigmentConfig); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = assigmentConfig; + assigmentConfig = { + step_type_obj: "Routing".translate(), + triggers: secondResp, + obj_title: "Routing".translate(), + st_type: 'ROUTING', + step_uid_obj: "Routing" + }; + item = this.createAccordionItem(assigmentConfig); + this.getStepsAssignAccordion().addItem(item); + item.dataItem = assigmentConfig; + this.getStepsAssignAccordion().defineEvents(); + }, + + /** + * Create Accordion + * @param data + * @returns {PMUI.item.AccordionItem} + */ + createAccordionItem: function (data) { + var that = this, + gridBefore, + gridAfter, + beforeTitle, + afterTitle, + i, + textLabel; + if (this.stepsType[data.step_type_obj]) { + textLabel = this.stepsType[data.step_type_obj]; + } else { + textLabel = data.step_type_obj; + } + beforeTitle = new PMUI.field.TextAnnotationField({ + text: 'Before'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left' + }); + afterTitle = new PMUI.field.TextAnnotationField({ + text: 'After'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left', + visible: data.st_type === "ASSIGNMENT" ? false : true + }); + + gridBefore = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + st_type: 'BEFORE', + step_uid: data.step_uid, + visibleFooter: false, + width: '96%', + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: "st_position", + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 210 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-delete'] + }, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + }], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + }, + onDragStart: function (grid, row) { + var items; + items = grid.getItems(); + if (jQuery.isArray(items)) { + if (items.length === 1) { + grid.showEmptyCell(); + } + } + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridBefore.st_type = 'BEFORE'; + } else if (data.st_type === "ROUTING") { + gridBefore.st_type = "BEFORE_ROUTING"; + } else { + gridBefore.st_type = "BEFORE_ASSIGNMENT"; + } + gridBefore.step_uid = data.step_uid; + gridBefore.clearItems(); + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridBefore.st_type === data.triggers[i].st_type) { + gridBefore.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + gridAfter = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + visibleFooter: false, + width: '96%', + visible: data.st_type === "ASSIGNMENT" ? false : true, + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [{ + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: 'st_position', + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 210 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); + }, + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-edit'] + }, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: { + cssClasses: ['mafe-button-delete'] + }, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); + } + }], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + }, + onDragStart: function (grid, row) { + var items; + items = grid.getItems(); + if (jQuery.isArray(items)) { + if (items.length === 1) { + grid.showEmptyCell(); + } + } + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridAfter.st_type = 'AFTER'; + } else if (data.st_type == "ROUTING") { + gridAfter.st_type = "AFTER_ROUTING"; + } else { + gridAfter.st_type = "AFTER_ASSIGNMENT"; + } + gridAfter.step_uid = data.step_uid; + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridAfter.st_type === data.triggers[i].st_type) { + gridAfter.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + var accordionItem = new PMUI.item.AccordionItem({ + id: 'id' + data.step_uid_obj, + dataStep: data, + closeable: true, + body: new PMUI.core.Panel({ + layout: 'vbox', + items: [ + beforeTitle, + gridBefore, + afterTitle, + gridAfter + ] + }) + }); + if (this.stepsType[data.step_type_obj]) { + accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + + this.stepsType[data.step_type_obj] + ')'); + this.stepsAssigned.insert(accordionItem); + } else { + accordionItem.setTitle((this.getStepsAssignAccordion().items.getSize() + 1) + ". " + data.obj_title); + } + return accordionItem; + }, + + /** + * This method is executed when a row is drop in another grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @param draggableItem + * @returns {*} + */ + receiveRowItem: function (receiveData, grid, index, draggableItem) { + var receiveParent = draggableItem.getParent(), + message, + restClient, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: this.getWindow() + }); + index = receiveParent.items.indexOf(draggableItem); + receiveParent.items.remove(draggableItem); + receiveParent.addItem(draggableItem, index); + message.show(); + return false; + } + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger' : 'activity/' + + that.getConfigWebEntry().tas_uid + '/step/' + grid.step_uid + '/trigger', + method: 'POST', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + } + }, { + url: receiveParent.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger/' + receiveData.obj_uid + + '/' + that.getStepType(receiveParent.st_type) : + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + receiveParent.step_uid + + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), + method: 'DELETE' + }] + }, + functionSuccess: function (xhr, response) { + var data; + data = receiveData; + if (data.hasOwnProperty("st_type")) { + data.st_type = grid.st_type; + grid.addDataItem(receiveData, index); + } + receiveParent.removeItem(draggableItem); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.getWindow(), + messageError: [ + 'An unexpected error while assigning the trigger, please try again later.'.translate() + ], + messageSuccess: [ + 'Trigger assigned successfully.'.translate() + ] + }); + restClient.executeRestClient(); + return this; + }, + + /** + * This method is executed when a row is sorted in the grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the new index position row + * @returns {stepsTask} + */ + sortableRowHandler: function (receiveData, grid, index) { + return new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + this.getConfigWebEntry().tas_uid + "/step/trigger/" + receiveData.tri_uid : 'activity/' + + this.getConfigWebEntry().tas_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, + typeRequest: 'update', + data: { + st_type: receiveData.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: this.getWindow(), + messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger assigned successfully.'.translate() + }).executeRestClient(); + }, + + /** + * Return the not items config. + * @returns {{obj_title: *, obj_uid: string, id: string}} + */ + notItemConfig: function () { + var config = { + obj_title: 'N/A'.translate(), + obj_uid: '', + id: "notItem" + }; + return config; + }, + + /** + * Get the steps assigned by a search criterion + * @param criteria, search filter, after running the endpoint getAccordionData method + * @returns {Array}, response with criteria + */ + getStepsAssignedByCriteria: function (criteria) { + var allAssigned = [], + i, + elements, + j, + resp, + data, + respon = []; + + this.getAccordionData( + function (xhr, response) { + allAssigned = response; + if (jQuery.isArray(allAssigned)) { + for (i = 0; i < allAssigned.length; i += 1) { + resp = allAssigned[i]; + if (typeof resp === "object") { + elements = resp.response ? resp.response : []; + for (j = 0; j < elements.length; j += 1) { + data = elements[j]; + if (typeof data === "object") { + if (data.step_type_obj && data.step_type_obj === criteria) { + respon.push(data); + } + } + } + } + } + } + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + return respon; + }, + + /** + * Opens the properties of the selected step with the current settings + * @param step, is the data of selected step + * @chainable + */ + propertiesStepShow: function (step) { + var that = this, + form, + saveButton, + cancelButton, + restClient, + criteriaButton; + this.setWindowAlternative(null); + this.getWindowAlternativeForm().setWidth(520); + this.getWindowAlternativeForm().setHeight(370); + this.getWindowAlternativeForm().setTitle('Step Properties'.translate()); + form = new PMUI.form.Form({ + id: 'stepsEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + { + id: 'step_mode', + pmType: 'radio', + label: 'Mode'.translate(), + value: '', + visible: step.step_type_obj === "DYNAFORM" ? true : false, + name: 'step_mode', + options: [{ + id: 'modeEdit', + label: 'Edit'.translate(), + value: 'EDIT', + selected: true + }, { + id: 'modeView', + label: 'View'.translate(), + value: 'VIEW' + }] + }, + new CriteriaField({ + id: 'step_condition', + pmType: 'textarea', + name: 'step_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea' + }) + ] + }); + this.getWindowAlternativeForm().addItem(form); + + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + form.getField('step_mode').setValue(response.step_mode); + form.getField('step_condition').setValue(response.step_condition); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient; + if (form.isValid()) { + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'update', + data: form.getData(), + functionSuccess: function () { + that.getWindowAlternativeForm().close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems update the Step Trigger, please try again.'.translate() + }); + restClient.executeRestClient(); + } + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.handler = null; + criteriaButton.setVisible(false); + } + this.getWindowAlternativeForm().open(); + }, + + /** + * Opens the step of the selected step with the current settings + * @param step, is the data of selected step + * @param accordioItem + * @chainable + */ + editStepShow: function (step, accordioItem) { + var that = this, + inputDocument; + switch (step.step_type_obj) { + case 'DYNAFORM': + var restProxy = new PMRestClient({ + endpoint: 'dynaform/' + step.step_uid_obj, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var old = PMUI.activeCanvas, + formDesigner; + PMUI.activeCanvas = false; + formDesigner = PMDesigner.dynaformDesigner(response); + formDesigner.onHide = function () { + var assignedDynaform, + i, + data, + title; + assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); + if (jQuery.isArray(assignedDynaform)) { + for (i = 0; i < assignedDynaform.length; i += 1) { + data = assignedDynaform[i]; + if (typeof data === "object") { + if (data.step_uid === step.step_uid) { + title = data.step_position + ". " + data.obj_title; + title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; + accordioItem.setTitle(title); + accordioItem.dataItem = data; + } + } + } + } + PMUI.activeCanvas = old; + }; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + break; + case 'OUTPUT_DOCUMENT': + PMDesigner.output(); + PMDesigner.output.showTiny(step.step_uid_obj); + break; + case 'INPUT_DOCUMENT': + inputDocument = new InputDocument({ + onUpdateInputDocumentHandler: function (data, inputDoc) { + var position, title; + position = accordioItem.dataItem.step_position; + title = position + ". " + data.inp_doc_title; + title = title + ' (' + this.stepsType["INPUT_DOCUMENT"] + ')'; + accordioItem.dataItem.obj_title = data.inp_doc_title; + accordioItem.setTitle(title); + inputDoc.winMainInputDocument.close(); + } + }); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); + break; + } + }, + + /** + * Edit the selected trigger condition + * @param stepID, It is the id of the step to upgrade + * @param triggerID, is the id of the trigger to update + * @param stepType, It is the kind of step to update + * @param row, PMUI.grid.GridPanelRow, is the row affected + */ + editCondition: function (stepID, triggerID, stepType, row) { + var that = this, + saveButton, + cancelButton, + criteriaButton, + form, + dataRow; + dataRow = row.getData(); + this.setWindowAlternative(null); + this.getWindowAlternativeForm().setWidth(500); + this.getWindowAlternativeForm().setHeight(350); + this.getWindowAlternativeForm().setTitle('Condition Trigger'.translate()); + this.getWindowAlternativeForm().setTitle("Trigger".translate()); + form = new PMUI.form.Form({ + id: 'idFormEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + new CriteriaField({ + id: 'st_condition', + pmType: 'textarea', + name: 'st_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea', + value: dataRow.st_condition + }) + ] + }); + this.getWindowAlternativeForm().addItem(form); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var data, + restClient; + data = form.getData(); + data.st_type = stepType; + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + + ((typeof (stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, + typeRequest: 'update', + data: data, + messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + functionSuccess: function (xhr, response) { + dataRow.st_condition = data.st_condition; + row.setData(dataRow); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + that.getWindowAlternativeForm().close(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(false); + criteriaButton.handler = null; + } + this.getWindowAlternativeForm().open(); + }, + + /** + * This method is executed when editing a "trigger" in a row of the grid. + * secondary window opens with the current configuration of the trigger + * @param trigger, is the return value when is update 'trigger' action in the enpoint + * @param triggerID, is the id of the trigger to update + * @chainable + */ + editTrigger: function (trigger, triggerID) { + var that = this, + codeMirror, + saveButton, + cancelButton, + criteriaButton; + this.setWindowAlternative(null); + codeMirror = new PMCodeMirror({ + id: "codeMirror" + }); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + codeMirror.setValue(trigger); + this.getWindowAlternativeForm().setWidth(DEFAULT_WINDOW_WIDTH); + this.getWindowAlternativeForm().setHeight(DEFAULT_WINDOW_HEIGHT); + this.getWindowAlternativeForm().setTitle("Trigger".translate()); + saveButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-save"); + cancelButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.getWindowAlternativeForm().footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + triggerID, + typeRequest: 'update', + data: { + tri_param: '', + tri_webbot: codeMirror.getValue() + }, + messageError: 'There are problems updating the trigger, please try again.'.translate(), + messageSuccess: 'Trigger updated correctly'.translate(), + flashContainer: that.getWindow(), + functionSuccess: function () { + that.getWindowAlternativeForm().close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.getWindowAlternativeForm().close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(true); + criteriaButton.setHandler(function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var cursorPos, + codemirror; + codemirror = codeMirror.cm; + cursorPos = codemirror.getCursor(); + codemirror.replaceSelection(variable); + codemirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }); + } + this.getWindowAlternativeForm().open(); + this.getWindowAlternativeForm().addItem(codeMirror); + codeMirror.cm.setSize(this.getWindowAlternativeForm().getWidth(), 380); + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + codeMirror.cm.refresh(); + }, + + /** + * Returns the type of step, for the execution of "endpoint" + * @param st_type, this a step type, the accepted parameters are: + * - BEFORE_ASSIGNMENT + * - BEFORE_ROUTING + * - AFTER_ROUTING + * - BEFORE + * - AFTER + * @returns {string} + */ + getStepType: function (st_type) { + var value; + switch (st_type) { + case 'BEFORE_ASSIGNMENT': + value = 'before-assignment'; + break; + case 'BEFORE_ROUTING': + value = 'before-routing'; + break; + case 'AFTER_ROUTING': + value = 'after-routing'; + break; + case 'BEFORE': + value = 'before'; + break; + case 'AFTER': + value = 'after'; + break; + default: + value = ''; + break; + } + return value; + }, + + /** + * Checks whether a trigger is already assigned in a grid + * @param grid, is instanceof PMUI.grid.Grid, in conducting the search + * @param tri_uid, search parameter in the rows of the grid + * @returns {boolean} + */ + isTriggerAssigned: function (grid, tri_uid) { + var data, i, exist = false; + data = grid.getData(); + if (grid && jQuery.isArray(data)) { + for (i = 0; i < data.length; i += 1) { + if (data[i].tri_uid === tri_uid) { + exist = true; + break; + } + } + } + return exist; + }, + + /** + * This method eliminates the list of triggers trigger an assigned step + * @param row, the row affected or selected + * @param grid, It is affected or grid to remove selected row + */ + removeTrigger: function (row, grid) { + var that = this, + message = 'Do you want to remove the trigger "', + messageData = row.getData().tri_title ? row.getData().tri_title : "", + yesButton, + noButton, + restClient; + message = message + messageData + '"?'; + this.getConfirmWindow().setMessage(message.translate()); + yesButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-yes"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger/' + row.getData().tri_uid + '/' + + that.getStepType(row.getData().st_type) : 'activity/' + that.getConfigWebEntry().tas_uid + + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + + '/' + that.getStepType(row.getData().st_type), + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + that.getConfirmWindow().close(); + that.updateIndexToGrid(grid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.getWindow(), + messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger removed successfully'.translate() + }); + restClient.executeRestClient(); + }); + } + noButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-no"); + if (noButton) { + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + } + this.getConfirmWindow().open(); + }, + + /** + * Updates indexes of elements selected grid + * @param grid, It is affected or grid to remove selected row + * @returns {stepsTask} + */ + updateIndexToGrid: function (grid) { + var cell, rows, i, row; + if (grid) { + rows = grid.getItems(); + if (jQuery.isArray(rows)) { + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + cell = row.cells.find("columnData"); + if (cell) { + cell.setContent(i + 1); + } + } + } + } + return this; + }, + + /** + * Add custom buttons on the head of an element of stepsAssignAccordion + * are three buttons + * properties + * edit + * remove + * @param html, is the html of the header accordion item + * @param step, the data of the step selected + * @param accordionItem + */ + customAccordionItemButtons: function (html, step, accordionItem) { + var that = this, + propertiesStep, + editStep, + removeStep, + $html, + containerButtons, + title; + if (html) { + $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); + title = step.obj_title + ' (' + step.step_type_obj + ')'; + $html.find(".pmui-accordion-item-title").get(0).title = title; + containerButtons = $('
'); + containerButtons.addClass("propertiesTask-accordionItem"); + propertiesStep = $('' + 'Properties'.translate() + ''); + propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + editStep = $('' + 'Edit'.translate() + ''); + editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + removeStep = $('' + 'Remove'.translate() + ''); + removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); + + propertiesStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.propertiesStepShow(step); + return false; + }); + + editStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.editStepShow(step, accordionItem); + return false; + }); + + removeStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.removeStepShow(step); + return false; + }); + containerButtons.append(propertiesStep); + containerButtons.append(editStep); + containerButtons.append(removeStep); + $html.append(containerButtons); + } + }, + + /** + * Add tooltip in treeNode elements + * @returns {stepsTask} + */ + updateIndexPosition: function (treeNode) { + var items, + i, + item, + $item, + text, + data; + if (treeNode && treeNode.html) { + items = treeNode.getItems(); + if (jQuery.isArray(items)) { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + if (item.html) { + $item = $(item.html); + data = item.getData(); + text = $item.find("a").get(0); + text.title = data.obj_title; + } + } + } + } + return this; + }, + + /** + * This method loads the data to stepsAssignTree + * @param response, the answer is an array containing all the elements + * that will be loaded into the step stepsAssignTree + * @chainable + */ + loadTreePanelData: function (response) { + var data, + i, + j, + type, + label, + items = [], + dataTree = [], + treeNode; + data = response[1].response; + + dataTree.push({ + obj_title: 'Trigger (s)'.translate(), + items: [this.notItemConfig()] + }); + + for (i = 0; i < data.length; i += 1) { + items.push({ + obj_title: data[i]['tri_title'], + obj_type: data[i]['tri_type'], + obj_uid: data[i]['tri_uid'] + }); + } + + if (items.length) { + dataTree.shift(); + dataTree.push({ + obj_title: 'Trigger (s)'.translate(), + items: items, + id: "TRIGGER" + }); + } + + data = response[0].response; + type = this.groupType; + label = this.groupLabel; + items = []; + for (i = 0; i < type.length; i += 1) { + items = []; + for (j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [this.notItemConfig()], + behavior: '', + id: type[i] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items, + behavior: 'drag', + id: type[i] + }); + } + } + this.getStepsAssignTree().clearItems(); + for (i = 0; i < dataTree.length; i += 1) { + this.getStepsAssignTree().addDataItem(dataTree[i]); + treeNode = this.getStepsAssignTree().getItem(i); + treeNode.setID(dataTree[i].id); + this.updateIndexPosition(treeNode); + } + return this; + }, + + /** + * It is an extension to add the "sortable" event "stepsAssignTree". + * when choosing a node treePanel and you want to add to the accordion or the grid + * @chainable + */ + addEventSortableInTreePanelElements: function () { + var that = this, + items = this.getStepsAssignTree().getItems(), + connect, + i, + sw, + nodeItems; + for (i = 0; i < items.length; i += 1) { + nodeItems = items[i].getItems(); + if (nodeItems.length && nodeItems[0].getData().obj_type) { + sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; + connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; + $(items[i].html).find('ul').find('>li').draggable({ + appendTo: document.body, + revert: "invalid", + helper: "clone".translate(), + cursor: "move", + zIndex: 1000, + connectToSortable: connect, + start: function (e) { + var i, nodeTag, node, nodeData, accordionItems, item; + nodeTag = e.target; + node = PMUI.getPMUIObject(nodeTag); + nodeData = node.getData(); + accordionItems = that.getStepsAssignAccordion().getItems(); + $(that.getStepsAssignAccordion().body).hide(); + if (nodeData.obj_type !== "SCRIPT") { + for (i = 0; i < accordionItems.length; i += 1) { + item = accordionItems[i]; + item.collapse(); + } + } + $(that.getStepsAssignAccordion().body).show(); + }, + stop: function () { + var i = 0, + max; + if (that.elementAccordionOpen) { + max = that.elementAccordionOpen.getSize(); + for (i = 0; i < max; i += 1) { + that.elementAccordionOpen.get(i).expand(); + } + } + } + }); + } else { + $(nodeItems[0].html).draggable("disable"); + } + } + }, + + /** + * It is an extension to add the "sortable" event "stepAssignAccordion". + * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. + * @chainable + */ + addEventSortableInAccordionElements: function () { + var that = this, + tagContainer, + newIndex, + index, + treeNodeObject, + treeNodeData; + if (this.getStepsAssignAccordion() && this.getStepsAssignAccordion().html) { + tagContainer = this.getStepsAssignAccordion().body; + $(tagContainer).sortable({ + items: '>div:not(#idAssignment,#idRouting)', + placeholder: 'steps-placeholder', + receive: function (event, ui) { + var item = ui ? ui.item : null; + if (item && item instanceof jQuery && item.length) { + treeNodeObject = PMUI.getPMUIObject(item.get(0)); + treeNodeData = treeNodeObject.getData(); + } + }, + stop: function (event, ui) { + var itemClone = ui ? ui.item : null, + accordionItems, + accordionItem, + dataEdited, + restClientMultipart, + restClient; + var newIndex = ui.item.index(); + accordionItems = that.getStepsAssignAccordion().getItems(); + if (itemClone && itemClone instanceof jQuery && itemClone.length) { + if (treeNodeObject) { + itemClone.remove(); + if (newIndex + 1 > accordionItems.length) { + newIndex = that.stepsAssigned.getSize(); + } + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step', + typeRequest: 'post', + data: { + step_type_obj: treeNodeData.obj_type, + step_uid_obj: treeNodeData.obj_uid, + step_condition: '', + step_position: newIndex + 1, + step_mode: 'EDIT' + }, + functionSuccess: function (xhr, response) { + var item, buttonAfected, treeNode; + that.getStepsAssignTree().removeItem(treeNodeObject); + treeNode = that.getStepsAssignTree().items.find("id", response.step_type_obj); + if (treeNode.items.getSize() === 0) { + treeNode.addDataItem(that.notItemConfig()); + } + response.obj_description = ''; + response.obj_title = treeNodeData.obj_title; + response.triggers = []; + item = that.createAccordionItem(response, true, true); + item.dataItem = response; + if (that.getStepsAssignAccordion().items.getSize() === 2) { + that.getStepsAssignAccordion().addItem(item, 0); + } else { + that.getStepsAssignAccordion().addItem(item, newIndex); + } + that.getStepsAssignAccordion().defineEvents(); + that.customAccordionItemButtons(item.html, response, item); + that.updateItemIndexToAccordion(); + that.addEventSortableInAccordionElements(); + that.addEventSortableInTreePanelElements(); + buttonAfected = that.getLabelsPanel().getItem("expand-button"); + buttonAfected.setDisabled(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while assigning the step, please try again later.' + .translate(), + messageSuccess: 'Step assigned successfully.'.translate(), + flashContainer: that.getStepsAssignAccordion().getParent() + }); + restClient.executeRestClient(); + } else { + accordionItem = PMUI.getPMUIObject(ui.item.get(0)); + index = that.getStepsAssignAccordion().items.indexOf(accordionItem); + if (newIndex !== index) { + that.getStepsAssignAccordion().items.remove(accordionItem); + that.getStepsAssignAccordion().items.insertAt(accordionItem, newIndex); + dataEdited = { + step_position: newIndex + 1, + step_uid: accordionItem.dataItem.step_uid, + step_type_obj: accordionItem.dataItem.step_type_obj, + step_uid_obj: accordionItem.dataItem.step_uid_obj + }; + restClientMultipart = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + + accordionItem.dataItem.step_uid, + typeRequest: 'update', + data: dataEdited, + functionSuccess: function (xhr, response) { + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while editing the step, please try again later.' + .translate(), + messageSuccess: 'Step editing successfully.'.translate(), + flashContainer: that.getWindow() + }); + restClientMultipart.executeRestClient(); + } + } + } + }, + start: function (e, ui) { + newIndex = ui.item.index(); + } + }); + } + }, + + /** + * Updates indexes of elements assigned + * @returns {stepsTask} + */ + updateItemIndexToAccordion: function () { + var title, + i, + item, + dataItem, + items = this.getStepsAssignAccordion().items, + position, + max; + max = items.getSize(); + for (i = 0; i < max; i += 1) { + item = items.get(i); + position = items.indexOf(item); + dataItem = item.dataItem; + title = (position + 1) + ". " + dataItem.obj_title; + if (this.stepsType[dataItem.step_type_obj]) { + title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; + } + item.dataItem.step_position = i + 1; + item.setTitle(title); + } + return this; + }, + + /** + * The window opens for confirmation of the removal step + * @param step, the current step to remove + * @chainable + */ + removeStepShow: function (step) { + var that = this, + title, + yesButton, + noButton, + restClient; + if (this.stepsType[step.step_type_obj] !== undefined) { + title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); + this.getConfirmWindow().setTitle(title); + } else { + this.getConfirmWindow().setTitle("Step " + step.step_type_obj.capitalize()); + } + this.getConfirmWindow().setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); + yesButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-yes"); + noButton = this.getConfirmWindow().footer.getItem("confirmWindow-footer-no"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: 'activity/' + that.getConfigWebEntry().tas_uid + '/step/' + step.step_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.removingStepTask(step, response); + that.getConfirmWindow().close(); + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), + messageSuccess: 'Step removed successfully'.translate(), + flashContainer: that.getWindow().getParent() + }); + restClient.executeRestClient(); + }); + } + if (noButton) { + noButton.setHandler(function () { + that.getConfirmWindow().close(); + }); + } + this.getConfirmWindow().open(); + }, + + /** + * Get the steps is not assigned by a criterion + * @param criteria, It is the filter criteria search + * @param stepAvailable, all steps Unassigned + * @returns {Array}, filtered items + */ + getAvailablesStepsByCriteria: function (criteria, stepAvailable) { + var items = [], + i; + if (jQuery.isArray(stepAvailable)) { + for (i = 0; i < stepAvailable.length; i += 1) { + if (stepAvailable[i].obj_type === criteria) { + items.push(stepAvailable[i]); + } + } + } + return items; + }, + + /** + * Eliminates the step of step Assign Accordion + * @param step, the current step to remove + * @param response, data from the endpoint + */ + removingStepTask: function (step, response) { + var stepObject, + stepAvailable, + treeNodeObject, + stepAvailables, + i, + itemsTreeNode = [], + items = []; + stepObject = this.getStepsAssignAccordion().getItem("id" + step.step_uid_obj); + this.elementAccordionOpen.remove(stepObject); + this.stepsAssigned.remove(stepObject); + this.getStepsAssignAccordion().removeItem(stepObject); + if (stepObject) { + this.getStepAvailables( + function (xhr, response) { + stepAvailable = response[0] ? response[0].response : []; + }, + function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + ); + stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); + for (i = 0; i < stepAvailables.length; i += 1) { + items.push({ + obj_title: stepAvailables[i]['obj_title'], + obj_type: stepAvailables[i]['obj_type'], + obj_uid: stepAvailables[i]['obj_uid'] + }); + } + treeNodeObject = this.getStepsAssignTree().getItem(step.step_type_obj); + itemsTreeNode = treeNodeObject.getItems(); + for (i = 0; i < itemsTreeNode.length; i += 1) { + treeNodeObject.removeItem(itemsTreeNode[i]); + } + treeNodeObject.clearItems(); + treeNodeObject.setDataItems(items); + this.updateIndexPosition(treeNodeObject); + this.addEventSortableInTreePanelElements(); + this.addEventSortableInAccordionElements(); + } + }, + + /** + * This method is executed when an element stepsAssignTree, is assigned in a grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @returns {stepsTask} + */ + receiveTreeNodeItem: function (receiveData, grid, index) { + var restClient, + message, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: this.getWindow() + }); + message.show(); + return; + } + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + that.getConfigWebEntry().tas_uid + '/step/trigger' : 'activity/' + + that.getConfigWebEntry().tas_uid + '/step/' + grid.step_uid + '/trigger', + typeRequest: 'post', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: '', + st_position: index + 1 + }, + functionSuccess: function (xhr, response) { + grid.addDataItem({ + st_condition: '', + st_position: index + 1, + st_type: grid.st_type, + tri_description: '', + tri_title: receiveData.obj_title, + tri_uid: receiveData.obj_uid, + obj_title: receiveData.obj_title, + obj_uid: receiveData.obj_uid + }, index); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return this; + } +}; +var PMMessageType = function (options) { + var that = this; + this.msgt_uid = null; + this.edit = false; + this.editRow = null; + this.dirtyAcceptedValue = false; + this.fieldInfo = null; + this.onSave = new Function(); + this.onEdit = new Function(); + this.requiredMessage = null; + this.clickedClose = true; + this.previousMessageValue = null; + this.buttonCreate = new PMUI.ui.Button({ + id: 'buttonCreate', + text: "Create".translate(), + height: '36px', + width: 100, + style: { + cssClasses: [ + 'mafe-button-create' + ] + }, + handler: function () { + that.showForm(); + } + }); + + this.buttonFieldAdd = new PMUI.field.ButtonField({ + id: 'buttonFieldAdd', + pmType: 'buttonField', + value: 'Create'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.6, + handler: function (field) { + that.addAcceptedValue(); + }, + buttonType: "success", + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '37px', + 'padding-right': '1px', + 'padding-bottom': '1px', + 'padding-left': '1px' + } + } + }); + this.buttonFieldAdd.getControl().button.setButtonType("success"); + + this.buttonFieldCancel = new PMUI.field.ButtonField({ + id: 'buttonFieldCancel', + pmType: 'buttonField', + value: 'Cancel'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.6, + handler: function (field) { + that.cancelAcceptedValue(); + }, + style: { + cssProperties: { + 'vertical-align': 'top', + 'padding-top': '37px', + 'padding-right': '1px', + 'padding-bottom': '1px', + 'padding-left': '1px' + } + } + }); + this.buttonFieldCancel.getControl().button.setButtonType("error"); + + this.frmMessageType = new PMUI.form.Form({ + id: 'frmMessageType', + width: 'auto', + title: '', + visibleHeader: false, + items: [ + { + id: 'txtMessageTypeName', + name: 'txtMessageTypeName', + pmType: 'text', + label: "Name".translate(), + placeholder: "Name".translate(), + value: '', + required: true, + valueType: 'string', + maxLength: 60, + controlsWidth: 460 + }, + { + id: "frmAcceptedValues", + pmType: 'panel', + legend: "Message Field".translate(), + fieldset: true, + layout: 'hbox', + items: [ + { + pmType: "text", + name: "txtMessageTypeVariableName", + label: "Message Field Name".translate(), + labelWidth: "100%", + controlsWidth: "400px", + proportion: 2.5, + valueType: "string", + maxLength: 255, + required: true, + labelPosition: "top", + validators: [ + { + pmType: "regexp", + criteria: /^[a-zA-Z_]+[0-9a-zA-Z_]+$/, + errorMessage: "A valid variable starts with a letter or underscore, followed by any number of letters, numbers, or underscores.".translate() + } + ] + }, + that.buttonFieldCancel, + that.buttonFieldAdd + ] + } + ] + }); + + this.frmMessageType.getData = function () { + var data = getData2PMUI(that.frmMessageType.html); + return data; + }; + + this.gridMessages = new PMUI.grid.GridPanel({ + id: 'gridMessages', + pageSize: 10, + width: '96%', + style: { + cssClasses: ['mafe-gridPanel'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [{ + id: "msgtName", + title: "Name".translate(), + dataType: "string", + columnData: "msgt_name", + alignmentCell: "left", + width: "330px", + sortable: true + }, { + id: 'msgtEdit', + dataType: 'button', + title: '', + buttonLabel: 'Edit'.translate(), + width: '60px', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + that.showFormEdit(row.getData()); + } + }, { + id: 'msgtDelete', + dataType: 'button', + title: '', + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + width: '70px', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + that.del(row.getData(), row, grid); + } + } + ], + dataItems: null + }); + + this.gridAcceptedValues = new PMUI.grid.GridPanel({ + id: 'gridAcceptedValues', + pageSize: 5, + height: 240, + style: {cssClasses: ['mafe-gridPanel']}, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + filterable: false, + tableContainerHeight: 200, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ''; + }, + columns: [ + { + id: "msgtv_name", + title: "Message Field Name".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 180, + sortable: true + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.editAcceptedValue(row); + } + }, + { + id: "btnDelete", + dataType: "button", + title: "", + buttonLabel: function (row, data) { + return "Delete".translate(); + }, + width: 75, + buttonStyle: {cssClasses: ["mafe-button-delete"]}, + onButtonClick: function (row, grid) { + that.deleteAcceptedValue(row); + } + } + ], + dataItems: null + }); + + this.isDirtyFrmMessageType = function () { + $("input,select,textarea").blur(); + if (this.frmMessageType.isVisible()) { + if (this.frmMessageType.isDirty() || this.dirtyAcceptedValue) { + var message_window = new PMUI.ui.MessageWindow({ + id: 'messageWindowCancel', + width: 490, + title: "Message Types".translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'messageWindowNo', + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + id: 'messageWindowYes', + text: 'Yes'.translate(), + handler: function () { + that.requiredMessage.hide(); + if (that.clickedClose) { + that.winMessageType.close(); + } + message_window.close(); + that.showGrid(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if (this.clickedClose) { + this.winMessageType.close(); + } else { + this.showGrid(); + this.requiredMessage.hide(); + } + } + } else { + this.winMessageType.close(); + } + }; + this.winMessageType = new PMUI.ui.Window({ + id: 'winMessageType', + title: '', + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonsPosition: 'right', + onBeforeClose: function () { + that.clickedClose = true; + that.isDirtyFrmMessageType(); + }, + footerItems: [ + new PMUI.ui.Button({ + id: 'winMessageTypeCancel', + text: 'Cancel'.translate(), + handler: function () { + that.clickedClose = false; + that.isDirtyFrmMessageType(); + }, + buttonType: 'error' + }), + new PMUI.ui.Button({ + id: 'winMessageTypeSave', + text: "Save".translate(), + handler: function () { + that.frmAcceptedValues.getItems("fields").forEach(function (i) { + i.disable(); + }); + if (that.edit) { + that.updateMessageType(); + } else { + that.createMessageType(); + } + that.frmAcceptedValues.getItems("fields").forEach(function (i) { + i.enable(); + }); + }, + buttonType: 'success' + }) + ], + buttonPanelPosition: 'bottom' + }); + PMMessageType.prototype.init.call(this); +}; + +PMMessageType.prototype.init = function () { + var that = this; + + that.buttonCreate.defineEvents(); + that.winMessageType.addItem(that.gridMessages); + that.winMessageType.addItem(that.frmMessageType); + that.winMessageType.addItem(that.gridAcceptedValues); + that.winMessageType.hideFooter(); + that.winMessageType.open(); + that.requiredMessage = $(document.getElementById("requiredMessage")); + + this.buttonFieldAdd.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + this.buttonFieldCancel.controls[0].button.setStyle({cssProperties: {padding: "6px 15px"}}); + that.requiredMessage.css({float: "none"}); + that.winMessageType.footer.html.style.textAlign = 'right'; + + that.frmAcceptedValues = PMUI.getPMUIObject($('#frmAcceptedValues').css({'width': '690px'}).get(0)); + $('#gridMessages .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + + //$(that.frmAcceptedValues.getHTML()).find("#requiredMessage").empty(); + that.requiredMessage.hide(); + //that.winMessageType.body.appendChild(that.requiredMessage[0]); + that.gridMessages.dom.toolbar.appendChild(that.buttonCreate.getHTML()); + that.showGrid(); + + validateKeysField(that.frmMessageType.getField('txtMessageTypeName').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + that.resetFrmAcceptedValues(); +}; + +PMMessageType.prototype.createMessageType = function () { + var that = this, + data; + + if (!this.frmMessageType.isValid()) { + return; + } + if (that.gridAcceptedValues.getData().length == 0) { + PMDesigner.msgFlash('Add at least one variable.'.translate(), winMessageType, 'error', 3000, 5); + return; + } + + data = this.frmMessageType.getData(); + data.msgt_name = data.txtMessageTypeName; + data.msgt_variables = that.getDataAcceptedValues(); + + // This returned data is not necessary at sendind, so it is deleted + delete data.txtMessageTypeVariableName; + delete data.buttonFieldCancel; + delete data.buttonFieldAdd; + + (new PMRestClient({ + endpoint: 'message-type', + typeRequest: 'post', + functionSuccess: function (xhr, response) { + if (that.onSave(xhr, response) === false) { + that.msgt_uid = null; + return; + } + that.showGrid(); + that.load(); + that.msgt_uid = null; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: ' ', + data: data, + messageSuccess: "Message Type Saved successfully.".translate(), + flashContainer: that.panel + + })).executeRestClient(); +}; + +PMMessageType.prototype.updateMessageType = function () { + var that = this, + data; + if (!this.frmMessageType.isValid()) { + return; + } + if (that.gridAcceptedValues.getData().length == 0) { + if (!this.frmAcceptedValues.isValid()) { + return; + } else { + PMDesigner.msgFlash('Add at least one variable.'.translate(), winMessageType, 'error', 3000, 5); + return; + } + } + + data = this.frmMessageType.getData(); + data.msgt_name = data.txtMessageTypeName; + data.msgt_variables = that.getDataAcceptedValues(); + + (new PMRestClient({ + endpoint: "message-type/" + that.msgt_uid, + typeRequest: "update", + data: data, + + functionSuccess: function (xhr, response) { + if (that.onEdit(xhr, response, data) === false) { + that.msgt_uid = null; + return; + } + + that.showGrid(); + that.load(); + that.msgt_uid = null; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: ' ', + messageSuccess: "Message Type edited successfully.".translate(), + flashContainer: that.panel + })).executeRestClient(); +}; + +PMMessageType.prototype.deleteMessage = function (msgt_uid) { + var that = this; + + (new PMRestClient({ + endpoint: 'message-type/' + msgt_uid, + typeRequest: 'remove', + + functionSuccess: function (xhr, response) { + that.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + + messageError: 'Working...'.translate(), + messageSuccess: 'Message Type Deleted successfully'.translate(), + flashContainer: that.panel + })).executeRestClient(); +}; + +PMMessageType.prototype.load = function () { + var that = this, restProxy; + + restProxy = new PMRestClient({ + endpoint: 'message-types', + typeRequest: 'get', + + functionSuccess: function (xhr, response) { + that.gridMessages.setDataItems(response); + that.gridMessages.sort('msgt_name', 'asc'); + + $(that.gridMessages.dom.toolbar).find("input").val(""); + that.gridMessages.clearFilter(); + document.getElementById("requiredMessage").style.marginTop = "16px"; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +PMMessageType.prototype.del = function (data, row, grid) { + var that = this, + confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDel', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Message Types".translate(), + message: "Do you want to delete this Message Type?".translate(), + footerItems: [ + { + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.deleteMessage(data.msgt_uid, row); + }, + buttonType: "success" + } + ] + }); + + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMMessageType.prototype.showGrid = function () { + var that = this; + that.frmMessageType.setVisible(false); + that.frmAcceptedValues.setVisible(false); + that.gridAcceptedValues.setVisible(false); + $(that.gridMessages.dom.toolbar).find("input").val(""); + that.gridMessages.clearFilter(); + that.gridMessages.setVisible(true); + that.winMessageType.setTitle("Message Types".translate()); + that.winMessageType.hideFooter(); +}; + +PMMessageType.prototype.showForm = function () { + var that = this; + this.requiredMessage.show(); + that.edit = false; + that.dirtyAcceptedValue = false; + that.frmMessageType.setVisible(true); + that.frmAcceptedValues.setVisible(true); + that.gridAcceptedValues.setVisible(true); + that.gridMessages.setVisible(false); + that.winMessageType.setTitle("Create Message Type".translate()); + that.winMessageType.showFooter(); + that.frmMessageType.reset(); + that.frmMessageType.setFocus(); + that.changeViewFieldType(); + that.resetFrmAcceptedValues(); + that.gridAcceptedValues.clearItems(); + that.buttonFieldCancel.setVisible(false); +}; + +PMMessageType.prototype.showFormEdit = function (data) { + var that = this; + that.showForm(); + that.msgt_uid = data.msgt_uid; + that.edit = true; + + that.winMessageType.setTitle('Edit Message Type'.translate()); + that.frmMessageType.getField('txtMessageTypeName').setValue(data.msgt_name); + + that.setDataAcceptedValues(data.msgt_variables); + document.getElementById("requiredMessage").style.marginTop = "16px"; +}; + +PMMessageType.prototype.changeViewFieldType = function () { + var that = this, sw = true; + + that.frmAcceptedValues.setVisible(true); + that.gridAcceptedValues.setVisible(true); + + validateKeysField(that.frmAcceptedValues.getField('txtMessageTypeVariableName').getControls()[0].getHTML(), ['isbackspace', 'isnumber', 'isletter', 'isunderscore']); + + if (this.fieldInfo === null) { + this.fieldInfo = document.createTextNode(''); + } +}; + +PMMessageType.prototype.addAcceptedValue = function () { + var that = this, + value = $.trim(that.frmAcceptedValues.getField('txtMessageTypeVariableName').getValue()), + message; + + // if the form (form field's RegEx) is invalid, add a Message Field will not be allowed. + if (!that.frmAcceptedValues.isValid()) { + return; + } + + if (that.previousMessageValue !== value && that.isAcceptedValueAdded(value)) { + message = new PMUI.ui.FlashMessage({ + message: "The variable Name already exists.".translate(), + duration: 3000, + severity: 'error', + appendTo: that.winMessageType.footer + }); + message.show(); + return; + } else if (!value) { + message = new PMUI.ui.FlashMessage({ + message: "Please, specify a name for the Message Field.".translate(), + duration: 3000, + severity: 'error', + appendTo: that.winMessageType.footer + }); + return message.show(); + } + that.previousMessageValue = null; + if (that.editRow === null) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + msgtv_name: value + } + })); + } else { + that.editRow.setData({ + msgtv_name: value + }); + } + + that.dirtyAcceptedValue = true; + that.cancelAcceptedValue(); +}; + +PMMessageType.prototype.editAcceptedValue = function (row) { + var that = this, data; + that.editRow = row; + data = row.getData(); + + that.previousMessageValue = data.msgtv_name; + that.frmAcceptedValues.getField('txtMessageTypeVariableName').setValue(data.msgtv_name); + that.buttonFieldAdd.setValue('Save'.translate()); + that.buttonFieldCancel.setVisible(true); +}; + +PMMessageType.prototype.deleteAcceptedValue = function (row) { + var that = this, + confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: "Message Type".translate(), + message: "Are you sure you want to delete the \"variable\"?".translate(), + footerItems: [ + { + text: 'No'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + }, + buttonType: "error" + }, { + text: 'Yes'.translate(), + visible: true, + handler: function () { + confirmWindow.close(); + that.gridAcceptedValues.removeItem(row); + that.dirtyAcceptedValue = true; + }, + buttonType: "success" + } + ] + }); + + confirmWindow.open(); + confirmWindow.dom.titleContainer.style.height = '17px'; + confirmWindow.showFooter(); +}; + +PMMessageType.prototype.getDataAcceptedValues = function () { + var that = this, data = [], i; + + if (that.gridAcceptedValues.visible) { + data = that.gridAcceptedValues.getData(); + + for (i = 0; i < data.length; i += 1) { + delete data[i].key; + delete data[i].type; + } + } + return data; +}; + +PMMessageType.prototype.setDataAcceptedValues = function (stringJsonData) { + var that = this, i, data; + if (!stringJsonData) { + return; + } + + data = stringJsonData; + if (typeof stringJsonData === 'string') { + data = JSON.parse(stringJsonData); + } + + if (that.gridAcceptedValues.visible) { + for (i = 0; i < data.length; i += 1) { + that.gridAcceptedValues.addItem(new PMUI.grid.GridPanelRow({ + data: { + msgtv_name: data[i].msgtv_name, + msgtv_default_value: data[i].msgtv_default_value + } + })); + } + } +}; + +PMMessageType.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that.buttonFieldAdd.setValue("Create".translate()); + that.buttonFieldCancel.setVisible(false); + that.resetFrmAcceptedValues(); +}; +/** + * Validate if the value is present in the data collection. + * @param value + * @returns {boolean} + */ +PMMessageType.prototype.isAcceptedValueAdded = function (value) { + var that = this, i, + data = that.gridAcceptedValues.getData(); + + for (i = 0; i < data.length; i += 1) { + if (data[i].msgtv_name === value) { + return true; + } + } + return false; +}; +/** + * Resets the fields from the form's panel for accepted values. + */ +PMMessageType.prototype.resetFrmAcceptedValues = function () { + this.frmAcceptedValues.getItems('fields').forEach(function (i) { + i.setValue(""); + }); +}; + +PMDesigner.messageType = function () { + var pmvariables = new PMMessageType(); + pmvariables.load(); +}; + +PMDesigner.messageType.create = function () { + var pmvariables = new PMMessageType(); + pmvariables.showForm(); + pmvariables.load(); +}; + +var MessageEventDefinition = function (bpmnEvent) { + var that = this, + msgNameField, + variableSelector; + + this.bpmnEvent = bpmnEvent; + this.arrayMessageType = []; + this.messageEventDefinitionOption = ""; + this.messageEventDefinitionUid = ""; + this.editRow = null; + this.eventType = bpmnEvent.evn_behavior; + this.gridCurrent = null; + this.editMessageForm = null; + this.dirtyGrid = false; + this.myTitle = ""; + + variableSelector = new CriteriaField({ + id: "txtMessageTypeVariableDefaultValue", + name: "txtMessageTypeVariableDefaultValue", + valueType: "string", + label: that.bpmnEvent.evn_marker == "MESSAGECATCH" ? "Store value in".translate() : "Get value from".translate(), + maxLength: 200, + labelWidth: "50%", + controlsWidth: 300, + proportion: 3.4, + required: false + }); + + msgNameField = { + pmType: "text", + id: "txtMessageTypeVariableName", + name: "txtMessageTypeVariableName", + label: (that.bpmnEvent.evn_marker === "MESSAGECATCH" ? "Value" : "Name").translate(), + labelWidth: "40%", + controlsWidth: 200, + proportion: 2.5, + valueType: "string", + maxLength: 255, + readOnly: true, + required: false + }; + + this.cboMessageType = new PMUI.field.DropDownListField({ + id: "cboMessageType", + name: "cboMessageType", + label: "Message Type".translate(), + options: [], + required: true, + controlsWidth: 150, + onChange: function (newValue, prevValue) { + var messageTypeData = that.getMessageTypeByIndex(that.cboMessageType.getValue()); + if (messageTypeData != null) { + that.gridCurrent.setDataItems(messageTypeData.msgt_variables); + + that._resetEditMessageForm(); + } + } + }); + + this.isDirtyFormMessageEvent = function () { + if (that.frmMessageEventDefinition1.isDirty() || that.dirtyGrid) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageType", + width: 490, + title: that.myTitle.translate(), + windowMessageType: "warning", + bodyHeight: 'auto', + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.winMessageEventDefinition.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.winMessageEventDefinition.close(); + } + }; + + this.txtCorrelationValue = new CriteriaField({ + id: "txtCorrelationValue", + name: "txtCorrelationValue", + valueType: "string", + label: "Correlation Value".translate(), + maxLength: 200, + value: "", + controlsWidth: 380 + }); + + this.btnSaveVariable = new PMUI.field.ButtonField({ + id: "btnSaveVariable", + pmType: "buttonField", + value: 'Save'.translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 50, + proportion: 0.8, + handler: function (field) { + that.addVariableInGrdPnlVariable3(); + that.dirtyGrid = true; + }, + buttonType: "success" + }); + + this.btnCancelVariable = new PMUI.field.ButtonField({ + id: "btnCancelVariable", + pmType: "buttonField", + value: "Cancel".translate(), + labelVisible: false, + buttonAlign: 'center', + controlsWidth: 55, + proportion: 0.6, + + handler: function (field) { + that.cancelAcceptedValue(); + }, + buttonType: "error" + }); + + this.frmMessageEventDefinition1 = new PMUI.form.Form({ + id: "frmMessageEventDefinition1", + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + visibleHeader: false, + items: [ + that.cboMessageType, + that.txtCorrelationValue, + { + id: "edit-panel", + pmType: "panel", + legend: "Message content".translate(), + fieldset: true, + layout: "hbox", + items: [ + that.bpmnEvent.evn_marker === "MESSAGECATCH" ? variableSelector : msgNameField, + that.bpmnEvent.evn_marker === "MESSAGECATCH" ? msgNameField : variableSelector, + that.btnCancelVariable, + that.btnSaveVariable + ] + } + ], + style: { + cssProperties: { + marginBottom: '15px' + } + } + }); + + this.editMessageForm = this.frmMessageEventDefinition1.getItem("edit-panel"); + + this.grdPnlVariable3 = new PMUI.grid.GridPanel({ + id: "grdPnlVariable3", + pageSize: 5, + style: {cssClasses: ["mafe-gridPanel"]}, + emptyMessage: "No records found".translate(), + filterable: false, + + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ""; + }, + columns: [ + { + id: "msgtv_name", + title: "Name".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 180 + }, + { + id: "msgtv_default_value", + title: "Get value from".translate(), + columnData: "msgtv_default_value", + dataType: "string", + alignmentCell: "left", + width: 300 + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.setValueMessageEventDefinition(row); + } + } + ], + + dataItems: null + }); + + this.grdPnlReceive = new PMUI.grid.GridPanel({ + id: "grdPnlVariable3", + pageSize: 5, + style: {cssClasses: ["mafe-gridPanel"]}, + emptyMessage: "No records found".translate(), + filterable: false, + tableContainerHeight: 204, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return ""; + }, + + columns: [ + { + id: "msgtv_default_value", + title: "Store value in".translate(), + columnData: "msgtv_default_value", + dataType: "string", + alignmentCell: "left", + width: 200 + }, + { + id: "msgtv_name", + title: "Name Value".translate(), + columnData: "msgtv_name", + dataType: "string", + alignmentCell: "left", + width: 280 + }, + { + id: "btnEdit", + dataType: "button", + title: "", + buttonLabel: "Edit".translate(), + width: 60, + buttonStyle: {cssClasses: ["mafe-button-edit"]}, + + onButtonClick: function (row, grid) { + that.setValueMessageEventDefinition(row); + } + } + ], + dataItems: null + }); + + this.gridCurrent = this.grdPnlVariable3; + + MessageEventDefinition.prototype.init.call(this); +}; + +MessageEventDefinition.prototype.init = function () { + var that = this; + + that.createWindow(); + that.winMessageEventDefinition.addItem(that.frmMessageEventDefinition1); + that.winMessageEventDefinition.addItem(that.gridCurrent); + + that.winMessageEventDefinition.open(); + this.editMessageForm.setVisible(false); + this.applyStylesPost(); + + that.load(); + document.getElementById("requiredMessage").style.marginTop = "15px"; +}; + +MessageEventDefinition.prototype.applyStylesPost = function () { + var that = this; + that.btnSaveVariable.controls[0].addCSSClasses(["pmui pmui-button pmui-success"]); + that.btnCancelVariable.controls[0].addCSSClasses(["pmui pmui-button pmui-error"]); + that.btnSaveVariable.controls[0].html.style.padding = "5px"; + $(that.btnCancelVariable.controls[0].html).css({ + padding: "5px", + width: "auto" + }); +}; + +MessageEventDefinition.prototype.createWindow = function () { + var that = this; + + if (that.bpmnEvent.evn_marker === "MESSAGECATCH") { + that.myTitle = (that.bpmnEvent.evn_type === "START" ? "Start Message Event" : "Intermediate Receive Message Event").translate(); + that.gridCurrent = this.grdPnlReceive; + } else if (that.bpmnEvent.evn_marker === "MESSAGETHROW") { + that.myTitle = (that.bpmnEvent.evn_type == "END" ? "End Message Event" : "Intermediate Send Message Event").translate(); + that.gridCurrent = this.grdPnlVariable3; + } + + that.winMessageEventDefinition = new PMUI.ui.Window({ + id: "winMessageEventDefinition", + title: that.myTitle.translate(), + + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + modal: true, + onBeforeClose: function () { + that.isDirtyFormMessageEvent(); + }, + footerItems: [ + { + pmType: "button", + buttonType: "error", + text: "Cancel".translate(), + handler: function () { + that.isDirtyFormMessageEvent(); + } + }, + { + pmType: "button", + buttonType: "success", + text: "Save".translate(), + + handler: function () { + var correlationValueAux, data; + if (!that.frmMessageEventDefinition1.isValid()) { + return; + } + correlationValueAux = that.frmMessageEventDefinition1.getData(); + data = { + evn_uid: that.bpmnEvent.evn_uid, + msgt_uid: that.cboMessageType.getValue(), + msged_variables: that.getVariablesByArray(that.grdPnlVariable3GetData()), + msged_correlation: correlationValueAux.txtCorrelationValue + }; + + switch (that.messageEventDefinitionOption) { + case "POST": + that.messageEventDefintionPostRestProxy(data); + + that.gridCurrent.clearItems(); + that.winMessageEventDefinition.close(); + break; + case "PUT": + that.messageEventDefintionPutRestProxy(data, that.messageEventDefinitionUid); + that.gridCurrent.clearItems(); + that.winMessageEventDefinition.close(); + break; + } + } + } + ], + + footerAlign: "right", + visibleFooter: true, + closable: true, + buttonPanelPosition: "bottom" + }); +}; + +MessageEventDefinition.prototype.getMessageTypeByIndex = function (messageTypeUid) { + var that = this, + i, + messageTypeData = null; + + if (that.arrayMessageType.length > 0) { + for (i = 0; i <= that.arrayMessageType.length - 1; i += 1) { + if (that.arrayMessageType[i].msgt_uid == messageTypeUid) { + messageTypeData = that.arrayMessageType[i]; + break; + } + } + } + return messageTypeData; +}; + +MessageEventDefinition.prototype.getVariablesByArray = function (arrayVariables) { + var variables = {}, i; + + for (i = 0; i <= arrayVariables.length - 1; i += 1) { + variables[arrayVariables[i].msgtv_name] = arrayVariables[i].msgtv_default_value; + } + + return variables; +}; + +MessageEventDefinition.prototype.getVariablesByObject = function (objectVariable) { + var that = this, + key, aux, + arrayData = []; + + for (key in objectVariable) { + aux = {}; + aux["msgtv_name"] = key; + aux["msgtv_default_value"] = objectVariable[key]; + arrayData.push(aux); + } + return arrayData; +}; + +MessageEventDefinition.prototype.load = function () { + var that = this, restProxy; + + that.messageEventDefinitionUid = ""; + that.messageEventDefinitionOption = ""; + + restProxy = new PMRestClient({ + typeRequest: "get", + endpoint: "message-event-definitions", + + functionSuccess: function (xhr, response) { + var dataResponse = response, + i, + arrayMessageEventDefinition = dataResponse, + arrayMessageEventDefinitionData = {}; + + for (i = 0; i <= arrayMessageEventDefinition.length - 1; i += 1) { + if (arrayMessageEventDefinition[i].evn_uid == that.bpmnEvent.evn_uid) { + that.messageEventDefinitionUid = arrayMessageEventDefinition[i].msged_uid + arrayMessageEventDefinitionData = arrayMessageEventDefinition[i]; + break; + } + } + + that.cboMessageTypeSetOptionsRestProxy(that.cboMessageType, (typeof(arrayMessageEventDefinitionData.msgt_uid) != "undefined") ? arrayMessageEventDefinitionData.msgt_uid : ""); + + if (that.messageEventDefinitionUid == "") { + //POST + that.messageEventDefinitionOption = "POST"; + + that.editMessageForm.getField("txtMessageTypeVariableName").setValue(""); + that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").setValue(""); + } else { + //PUT + that.messageEventDefinitionOption = "PUT"; + + that.gridCurrent.setDataItems(that.getVariablesByObject(arrayMessageEventDefinitionData.msged_variables)); + that.frmMessageEventDefinition1.getField("txtCorrelationValue").setValue(arrayMessageEventDefinitionData.msged_correlation); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.setValueMessageEventDefinition = function (row) { + var that = this, data; + + that.editRow = row; + data = row.getData(); + + that.editMessageForm.getField("txtMessageTypeVariableName").setValue(data.msgtv_name); + that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").setValue(data.msgtv_default_value); + + that.editMessageForm.setVisible(true); +}; + +MessageEventDefinition.prototype.addVariableInGrdPnlVariable3 = function () { + var that = this, + data = { + msgtv_name: that.editMessageForm.getField("txtMessageTypeVariableName").getValue(), + msgtv_default_value: that.editMessageForm.getField("txtMessageTypeVariableDefaultValue").getValue() + }; + + if (that.editRow == null) { + that.gridCurrent.addItem(new PMUI.grid.GridPanelRow({ + data: data + })); + } else { + that.editRow.setData(data); + } + + that.cancelAcceptedValue(); +}; + +MessageEventDefinition.prototype.cancelAcceptedValue = function () { + var that = this; + that.editRow = null; + that._resetEditMessageForm(); + that.editMessageForm.setVisible(false); +}; + +MessageEventDefinition.prototype.grdPnlVariable3GetData = function () { + var that = this, + i, + data = []; + + if (that.gridCurrent.visible) { + data = that.gridCurrent.getData(); + + for (i = 0; i <= data.length - 1; i += 1) { + delete data[i].key; + delete data[i].type; + } + } + return data; +}; + +MessageEventDefinition.prototype.cboMessageTypeSetOptionsRestProxy = function (cboMessageType, messageTypeUidSelected) { + var that = this, restProxy, iAux; + + cboMessageType.clearOptions(); + iAux = 0; + restProxy = new PMRestClient({ + typeRequest: "get", + endpoint: "message-types", + + functionSuccess: function (xhr, response) { + var dataResponse = response, messageTypeData, i, arrayOptions, iAux; + that.arrayMessageType = dataResponse; + arrayOptions = []; + for (i = 0; i <= dataResponse.length - 1; i += 1) { + if (dataResponse[i].msgt_uid == messageTypeUidSelected) { + iAux = i; + } + + arrayOptions.push( + { + value: dataResponse[i].msgt_uid, + label: dataResponse[i].msgt_name + } + ); + } + + if (arrayOptions.length > 0) { + cboMessageType.setOptions(arrayOptions); + + if (messageTypeUidSelected == "") { + //POST + cboMessageType.setValue(arrayOptions[0].value); + messageTypeData = that.getMessageTypeByIndex(arrayOptions[0].value); + + if (messageTypeData != null) { + that.gridCurrent.setDataItems(messageTypeData.msgt_variables); + } + } else { + //PUT + cboMessageType.setValue(arrayOptions[iAux].value); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.messageEventDefintionPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "message-event-definition", + typeRequest: "post", + data: data, + + functionSuccess: function (xhr, response) { + var dataResponse = response; + PMDesigner.msgFlash('The property event was saved successfully.'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; + +MessageEventDefinition.prototype.messageEventDefintionPutRestProxy = function (data, messageEventDefinitionUid) { + var restProxy = new PMRestClient({ + endpoint: "message-event-definition/" + messageEventDefinitionUid, + typeRequest: "update", + data: data, + + functionSuccess: function (xhr, response) { + var dataResponse = response; + PMDesigner.msgFlash('The property event was saved successfully.'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + + restProxy.executeRestClient(); +}; +/** + * Reset the fields from the form's Edit panel. + * @returns {MessageEventDefinition} + * @private + */ +MessageEventDefinition.prototype._resetEditMessageForm = function () { + if (this.editMessageForm) { + this.editMessageForm.getItems().map(function (i) { + i.setValue(""); + }); + } + return this; +}; + +/** + * @class IntroHelper + * Handle Intro helper + * + * @constructor + * Creates a new instance of the class + * @param {Object} options + */ +var IntroHelper = function (options) { + this.steps = []; + this.onExit = null; + this.introjs = null; + IntroHelper.prototype.initObject.call(this, options); +}; +IntroHelper.prototype.type = 'IntroHelper'; + +IntroHelper.prototype.initObject = function (options) { + var defaults = { + steps: [], + skipLabel: "Skip", + onExit : new Function() + }; + $.extend(true, defaults, options); + this.setSteps(defaults.steps); + + this.setSkipLabel(defaults.skipLabel); + this.setNextLabel(defaults.nextLabel); + this.setPrevLabel(defaults.prevLabel); + this.setDoneLabel(defaults.doneLabel); + this.setOnExit(defaults.onExit); +}; + +IntroHelper.prototype.setSteps = function (steps) { + this.steps = steps; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; +IntroHelper.prototype.setNextLabel = function (label) { + this.nextLabel = label; + return this; +}; + +IntroHelper.prototype.setPrevLabel = function (label) { + this.prevLabel = label; + return this; +}; + +IntroHelper.prototype.setDoneLabel = function (label) { + this.doneLabel = label; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; + +IntroHelper.prototype.setOnExit = function (callback) { + if (callback && typeof callback == "function") { + this.onExit = callback; + } + return this; +}; + +IntroHelper.prototype.startIntro = function () { + var that = this; + this.introjs = introJs(); + this.introjs.setOptions({ + steps: this.steps, + skipLabel: this.skipLabel, + nextLabel: this.nextLabel, + prevLabel: this.prevLabel, + doneLabel: this.doneLabel + }); + this.introjs.onexit(function () { + that.onExit(); + }); + + this.introjs.start(); +}; +(function () { + PMDesigner.scriptTaskProperties = function (activity) { + var that = this, + taskUid, + taskType, + triggerSelectedData, + oldValue, + uidProj, + scrtas_uid, + buttonCancel, + restClientNewScriptTask, + restClientUpdateScriptTask, + restClientNewTrigger, + restClientUpdateTrigger, + $ctrlSpaceMessage, + triggerEngine, + getListTrigger, + getScriptTask, + formScriptTask, + buttonSave, + domSettings, + scriptTaskPropertiesWindow, + triggerUid; + + taskUid = activity.getID(); + taskType = activity.getTaskType(); + taskType = "TRIGGER"; + oldValue = ""; + uidProj = PMDesigner.project.id; + scrtas_uid = ""; + triggerUid = ""; + $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelScriptButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + scriptTaskPropertiesWindow.isDirtyFormScript(); + } + }); + + restClientNewScriptTask = function (triggerUid) { + var restClient = new PMRestClient({ + endpoint: 'script-task', + typeRequest: 'post', + data: { + scrtas_obj_uid: triggerUid, + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function () { + scriptTaskPropertiesWindow.close(); + PMDesigner.msgFlash('Script Task saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateScriptTask = function (triggerUid) { + var restClient = new PMRestClient({ + endpoint: 'script-task/' + formScriptTask.getItems()[0].items.get(4).getValue(), + typeRequest: 'update', + data: { + scrtas_obj_uid: triggerUid, /*trigger uid*/ + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function () { + scriptTaskPropertiesWindow.close(); + PMDesigner.msgFlash('Script Task saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientNewTrigger = function (dataToSend, newScriptTask) { + var restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + triggerUid = response.tri_uid; + if (triggerUid != "" && typeof triggerUid != "undefinied") { + if (newScriptTask) { + restClientNewScriptTask(triggerUid); + } else { + restClientUpdateScriptTask(triggerUid); + } + } + }, + functionFailure: function (xhr, response) { + var msg = response.error.message, + arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateTrigger = function (newScriptTask) { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + formScriptTask.getItems()[0].items.get(1).getValue(), + typeRequest: 'update', + data: { + scrtas_obj_uid: formScriptTask.getItems()[0].items.get(1).getValue(), + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + act_uid: taskUid, + scrtas_obj_type: taskType + }, + functionSuccess: function (xhr, response) { + triggerUid = response.tri_uid; + if (newScriptTask) { + restClientNewScriptTask(formScriptTask.getItems()[0].items.get(1).getValue()); + } else { + restClientUpdateScriptTask(formScriptTask.getItems()[0].items.get(1).getValue()); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Script Task, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + buttonSave = new PMUI.ui.Button({ + id: 'saveScriptButton', + text: "Save".translate(), + handler: function (event) { + var newScriptTask, dataToSend; + if (formScriptTask.isValid()) { + if (formScriptTask.getItems()[0].items.get(4).getValue() === "") { /*new*/ + newScriptTask = true; + if (formScriptTask.getItems()[0].items.get(1).getValue() != "") { + restClientUpdateTrigger(newScriptTask); + } else { + dataToSend = { + tri_title: formScriptTask.getItems()[0].items.get(2).getValue(), + tri_description: "", + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + tri_param: "" + }; + restClientNewTrigger(dataToSend, newScriptTask); + } + } else { + newScriptTask = false; + if (formScriptTask.getItems()[0].items.get(1).getValue() !== "") { + restClientUpdateTrigger(newScriptTask); + } else { + dataToSend = { + tri_title: formScriptTask.getItems()[0].items.get(2).getValue(), + tri_description: "", + tri_webbot: formScriptTask.getItems()[1].controls[0].cm.getValue(), + tri_param: "" + }; + restClientNewTrigger(dataToSend, newScriptTask); + } + } + } + }, + buttonType: 'success' + }); + + scriptTaskPropertiesWindow = new PMUI.ui.Window({ + id: "scriptTaskPropertiesWindow", + title: "Script Task Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formScriptTask.getItems()[1].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '208px', + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + } + } + }, + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + scriptTaskPropertiesWindow.isDirtyFormScript(); + } + }); + + scriptTaskPropertiesWindow.isDirtyFormScript = function () { + var that = this, + message_window, + title = "Script Task".translate(); + if (oldValue !== formScriptTask.getItems()[1].controls[0].cm.getValue()) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: title, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + + triggerEngine = new PMUI.field.DropDownListField({ + id: "triggerEngine", + name: "triggerEngine", + label: "Title".translate(), + options: null, + controlsWidth: 400, + required: true, + onChange: function (newValue, prevValue) { + var uidTri = newValue, i; + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid == uidTri) { + formScriptTask.getItems()[1].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + } + } + } + }); + + getListTrigger = function (triggerEngine) { + var restClient = new PMRestClient({ + endpoint: 'triggers', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var arrayOptions = [], i; + triggerSelectedData = response; + arrayOptions[0] = { + label: "- Select a trigger -".translate(), + value: "", + disabled: true, + selected: true + }; + for (i = 0; i <= triggerSelectedData.length - 1; i += 1) { + arrayOptions.push( + { + value: triggerSelectedData[i].tri_uid, + label: triggerSelectedData[i].tri_title + } + ); + } + triggerEngine.setOptions(arrayOptions); + triggerEngine.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + + getScriptTask = function () { + var restClient = new PMRestClient({ + endpoint: 'script-task/activity/' + taskUid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var i; + if (typeof response == "object") { + triggerUid = response.scrtas_obj_uid; + if (triggerUid != "" && typeof triggerUid != "undefinied") { + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid == triggerUid) { + formScriptTask.getItems()[1].controls[0].setValue(triggerSelectedData[i].tri_webbot); + oldValue = triggerSelectedData[i].tri_webbot; + formScriptTask.getItems()[0].items.get(4).setValue(response.scrtas_uid); + formScriptTask.getItems()[0].items.get(1).setValue(triggerUid); + } + } + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + formScriptTask = new PMUI.form.Form({ + id: "formScriptTask", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formScriptTask", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "taskUid", + pmType: "text", + label: "ID".translate(), + value: taskUid, + name: "taskUid", + readOnly: true, + visible: false, + valueType: 'string' + }, + triggerEngine, + { + id: "newScript", + pmType: "text", + label: "Title".translate(), + controlsWidth: 400, + value: "", + name: "newScript", + required: false, + visible: false, + valueType: 'string' + }, + { + id: "taskType", + pmType: "text", + value: taskType, + name: "taskType", + visible: false, + valueType: 'string' + }, + { + id: "scrtas_uid", + pmType: "text", + value: scrtas_uid, + name: "scrtas_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + that.cd = new PMCodeMirrorField({ + labelWidth: '23.8%' + }); + that.cd.setLabel("Code".translate()); + formScriptTask.addItem(that.cd); + formScriptTask.getItems()[1].setName('code'); + formScriptTask.getItems()[1].setID('code'); + formScriptTask.getItems()[1].setHeight(300); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + + getListTrigger(triggerEngine); + getScriptTask(); + /*end form*/ + + domSettings = function () { + var codeMirrorControl, requiredMessage, titleAdd, titleBack; + codeMirrorControl = formScriptTask.getItems()[1].controls[0].cm; + formScriptTask.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(650, 255); //CodeMirror Size + $("#code").find(".CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); + codeMirrorControl.refresh(); + } + requiredMessage = $(document.getElementById("requiredMessage")); + scriptTaskPropertiesWindow.body.appendChild(requiredMessage[0]); + requiredMessage[0].style['marginTop'] = '65px'; + + scriptTaskPropertiesWindow.footer.html.style.textAlign = 'right'; + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + + titleAdd = "Add new".translate(); + titleBack = "Back to list".translate(); + + $("#triggerEngine").find("select").after('  '); + $("#newScript").find("input").after('  '); + $("#titleAdd, #titleBack").tooltip(); + }; + + scriptTaskPropertiesWindow.addItem(formScriptTask); + scriptTaskPropertiesWindow.open(); + scriptTaskPropertiesWindow.showFooter(); + domSettings(); + + $(".showHideScript").on("click", function () { + if (formScriptTask.getItems()[0].items.get(1).isVisible()) { + formScriptTask.getItems()[0].items.get(1).setVisible(false); + } else { + formScriptTask.getItems()[0].items.get(1).setVisible(true); + formScriptTask.getItems()[0].items.get(1).setValue(""); + formScriptTask.getItems()[0].items.get(2).setRequired(false); + formScriptTask.getItems()[0].items.get(1).setRequired(true); + $(formScriptTask.getItems()[0].items.get(1).html).find("select").focus(); + } + + if (!formScriptTask.getItems()[0].items.get(2).isVisible()) { + formScriptTask.getItems()[0].items.get(2).setVisible(true); + formScriptTask.getItems()[0].items.get(1).setRequired(false); + formScriptTask.getItems()[0].items.get(1).setValue(""); + formScriptTask.getItems()[0].items.get(2).setRequired(true); + formScriptTask.getItems()[0].items.get(2).setValue(""); + $(formScriptTask.getItems()[0].items.get(2).html).find("input").focus(); + } else { + formScriptTask.getItems()[0].items.get(2).setVisible(false); + } + formScriptTask.getItems()[1].controls[0].cm.setValue(""); + oldValue = ""; + + }); + + }; +}()); + +(function () { + PMDesigner.timerEventProperties = function (activity) { + var that = this, + evnUid = activity.getID(), + activityType = activity.getEventMarker(), + uidProj = PMDesigner.project.id, + oldValues, + tmrevn_uid = "", + dataTimer = "", + buttonCancel, + restClientNewTimerEvent, + buttonSave, + restClientUpdateTimerEvent, + timerEventPropertiesWindow, + showHourlyItems, + showDailyItems, + showMonthlyItems, + showOneDateTimeItems, + showEveryItems, + showWaitForItems, + showWaitUntilItems, + varshowHourlyItems, + endDate, + oneDateTime, + daysGroup, + monthsGroup, + radioGroup, + dateTimeVariablePicker, + formTimerEvent, + getFormData, + getTimerEventData, + validateItems, + domSettings, + eventType = activity.getEventType(), + regexDay = new RegExp(/^(((0|1|2)?[0-9])|(3[01]))$/), + regexHour = new RegExp(/^(((0|1)?[0-9])|(2[0-4]))$/), + regexMinute = new RegExp(/^([0-5]?[0-9])$/); + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelTimmerButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + formTimerEvent.getField('startDate').controls[0].hideCalendar(); + formTimerEvent.getField('endDate').controls[0].hideCalendar(); + formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); + formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); + timerEventPropertiesWindow.isDirtyFormScript(); + } + }); + + restClientNewTimerEvent = function (dataToSave) { + var restClient = new PMRestClient({ + endpoint: 'timer-event', + typeRequest: 'post', + data: dataToSave, + functionSuccess: function (xhr, response) { + timerEventPropertiesWindow.close(); + PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + restClientUpdateTimerEvent = function (dataToSave) { + var restClient = new PMRestClient({ + endpoint: 'timer-event/' + formTimerEvent.getField("tmrevn_uid").getValue(), + typeRequest: 'update', + data: dataToSave, + functionSuccess: function (xhr, response) { + timerEventPropertiesWindow.close(); + PMDesigner.msgFlash('Timer Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + buttonSave = new PMUI.ui.Button({ + id: 'saveTimmerButton', + text: "Save".translate(), + handler: function (event) { + var i, + opt, + formData; + + formTimerEvent.getField("hourType").setValue(getData2PMUI(formTimerEvent.html).hourType); + formTimerEvent.getField("minuteType").setValue(getData2PMUI(formTimerEvent.html).minuteType); + formTimerEvent.getField("dayType").setValue(getData2PMUI(formTimerEvent.html).dayType); + if (formTimerEvent.isValid()) { + opt = formTimerEvent.getField("radioGroup").getValue(); + formData = formTimerEvent.getData(); + switch (opt) { + case "1": /*hourly*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "HOURLY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "2": /*daily*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "DAILY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), + tmrevn_configuration_data: JSON.parse(formData.daysGroup).map(function (n) { + return Number(n); + }) + }; + break; + case "3": /*monthly*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "MONTHLY", + tmrevn_start_date: formData.startDate.substring(0, 10), + tmrevn_end_date: formTimerEvent.getField("endDate").getValue().substring(0, 10), + tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ), + tmrevn_configuration_data: JSON.parse(formData.monthsGroup).map(function (n) { + return Number(n); + }) + }; + break; + case "4": /*one-date-time*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "ONE-DATE-TIME", + tmrevn_next_run_date: $("#oneDateTime").find("input:eq(0)").val() + }; + for (var i in ENABLED_FEATURES) { + if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { + dataTimer.tmrevn_next_run_date = convertDatetimeToIso8601(dataTimer.tmrevn_next_run_date); + } + } + break; + case "5": /*every*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "EVERY", + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "6": /*wait for*/ + if ((formData.dayType === '' || formData.dayType === '00' || formData.dayType === '0') && + (formData.hourType === '' || formData.hourType === '00' || formData.hourType === '0') && + (formData.minuteType === '' || formData.minuteType === '00' || formData.minuteType === '0')) { + PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); + return; + } else { + if (!regexDay.test(formData.dayType) || !regexHour.test(formData.hourType) || !regexMinute.test(formData.minuteType)) { + PMDesigner.msgWinError("The amount of time entered is not valid. Please fill in at least one of the fields (day, hour, or minute)".translate()); + return; + } + } + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "WAIT-FOR", + tmrevn_day: formData.dayType.length == 1 ? "0" + formData.dayType : (formData.dayType.length == 0 ? "00" : formData.dayType ), + tmrevn_hour: formData.hourType.length == 1 ? "0" + formData.hourType : (formData.hourType.length == 0 ? "00" : formData.hourType ), + tmrevn_minute: formData.minuteType.length == 1 ? "0" + formData.minuteType : (formData.minuteType.length == 0 ? "00" : formData.minuteType ) + }; + break; + case "7": /*wait until specified date time*/ + dataTimer = { + evn_uid: evnUid, + tmrevn_option: "WAIT-UNTIL-SPECIFIED-DATE-TIME", + tmrevn_configuration_data: $("#dateTimeVariablePicker").find("input:eq(0)").val() + }; + break; + } + if (formTimerEvent.getField("tmrevn_uid").getValue() == "") { + restClientNewTimerEvent(dataTimer); + } else { + restClientUpdateTimerEvent(dataTimer); + } + } + }, + buttonType: 'success' + }); + + timerEventPropertiesWindow = new PMUI.ui.Window({ + id: "timerEventPropertiesWindow", + title: "Timer Event Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + formTimerEvent.getField('startDate').controls[0].hideCalendar(); + formTimerEvent.getField('endDate').controls[0].hideCalendar(); + formTimerEvent.getField('oneDateTime').controls[0].hideCalendar(); + formTimerEvent.getField('dateTimeVariablePicker').controls[0].hideCalendar(); + timerEventPropertiesWindow.isDirtyFormScript(); + } + }); + + timerEventPropertiesWindow.isDirtyFormScript = function () { + var that = this, + title = "Timer Event".translate(), + newValues = getFormData($("#formTimerEvent")); + if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: title, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + showHourlyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showDailyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(true); + formTimerEvent.getField('daysGroup').setRequired(true); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showMonthlyItems = function () { + formTimerEvent.getField('startDate').setVisible(true); + formTimerEvent.getField('startDate').setRequired(true); + formTimerEvent.getField('endDateCheckbox').setVisible(true); + formTimerEvent.getField('endDate').setVisible(true); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(true); + formTimerEvent.getField('monthsGroup').setRequired(true); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + + showOneDateTimeItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('startDate').setRequired(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(true); + formTimerEvent.getField('oneDateTime').setRequired(true); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(false); + }; + + showEveryItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('startDate').setRequired(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('oneDateTime').setRequired(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setRequired(true); + }; + /*intermediate*/ + showWaitForItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(false); + formTimerEvent.getField('dateTimeVariablePicker').setRequired(false); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(true); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(true); + }; + + showWaitUntilItems = function () { + formTimerEvent.getField('startDate').setVisible(false); + formTimerEvent.getField('endDateCheckbox').setVisible(false); + formTimerEvent.getField('endDate').setVisible(false); + formTimerEvent.getField('oneDateTime').setVisible(false); + formTimerEvent.getField('daysGroup').setVisible(false); + formTimerEvent.getField('daysGroup').setRequired(false); + formTimerEvent.getField('monthsGroup').setVisible(false); + formTimerEvent.getField('monthsGroup').setRequired(false); + formTimerEvent.getField('dateTimeVariablePicker').setVisible(true); + formTimerEvent.getField('dateTimeVariablePicker').setRequired(true); + formTimerEvent.getItems()[0].items.get(4).getField('dayType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('hourType').setVisible(false); + formTimerEvent.getItems()[0].items.get(4).getField('minuteType').setVisible(false); + }; + + radioGroup = new PMUI.field.RadioButtonGroupField({ + id: 'radioGroup', + controlPositioning: 'horizontal', + maxDirectionOptions: 7, + options: [ + { + label: "Hourly".translate(), + value: "1" + }, + { + label: "Daily".translate(), + value: "2" + }, + { + label: "Monthly".translate(), + value: "3" + }, + { + label: "One date/time".translate(), + value: "4" + }, + { + label: "Every".translate(), + value: "5" + }, + { + label: "Wait for".translate(), + value: "6" + }, + { + label: "Wait until specified date/time".translate(), + value: "7" + } + + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "1": + showHourlyItems(); + break; + case "2": + showDailyItems(); + break; + case "3": + showMonthlyItems(); + break; + case "4": + showOneDateTimeItems(); + break; + case "5": + showEveryItems(); + break; + case "6": + showWaitForItems(); + break; + case "7": + showWaitUntilItems(); + break; + } + }, + value: "1" + }); + + startDate = new PMUI.field.DateTimeField({ + id: 'startDate', + label: 'Start date'.translate(), + datetime: false, + dateFormat: 'yy-mm-dd', + firstDay: 1, + controlsWidth: 100, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + endDate = new PMUI.field.DateTimeField({ + id: 'endDate', + label: "End date".translate(), + value: '', + disabled: true, + datetime: false, + dateFormat: 'yy-mm-dd', + firstDay: 1, + controlsWidth: 100, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + oneDateTime = new PMUI.field.DateTimeField({ + id: 'oneDateTime', + label: 'Date time'.translate(), + datetime: true, + dateFormat: 'yy-mm-dd HH:ii:ss', + firstDay: 1, + controlsWidth: 150, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + daysGroup = new PMUI.field.CheckBoxGroupField({ + label: "Days".translate(), + id: 'daysGroup', + controlPositioning: 'vertical', + maxDirectionOptions: 3, + required: true, + options: [ + { + label: 'Monday'.translate(), + value: 1, + name: 'monday', + selected: true + }, + { + label: 'Tuesday'.translate(), + value: 2, + name: 'tuesday', + selected: true + }, + { + label: 'Wednesday'.translate(), + value: 3, + name: 'wednesday', + selected: true + }, + { + label: 'Thursday'.translate(), + value: 4, + name: 'thursday', + selected: true + }, + { + label: 'Friday'.translate(), + value: 5, + name: 'friday', + selected: true + }, + { + label: 'Saturday'.translate(), + value: 6, + name: 'saturday', + selected: true + }, + { + label: 'Sunday'.translate(), + value: 7, + name: 'sunday', + selected: true + } + ], + onChange: function (newVal, oldVal) { + + } + }); + + monthsGroup = new PMUI.field.CheckBoxGroupField({ + label: "Months".translate(), + id: 'monthsGroup', + controlPositioning: 'vertical', + maxDirectionOptions: 3, + required: true, + options: [ + { + label: 'January'.translate(), + value: 1, + name: 'january', + selected: true + }, + { + label: 'February'.translate(), + value: 2, + selected: true + }, + { + label: 'March'.translate(), + value: 3, + selected: true + }, + { + label: 'April'.translate(), + value: 4, + selected: true + }, + { + label: 'May'.translate(), + value: 5, + selected: true + }, + { + label: 'June'.translate(), + value: 6, + selected: true + }, + { + label: 'July'.translate(), + value: 7, + selected: true + }, + { + label: 'August'.translate(), + value: 8, + selected: true + }, + { + label: 'September'.translate(), + value: 9, + selected: true + }, + { + label: 'October'.translate(), + value: 10, + selected: true + }, + { + label: 'November'.translate(), + value: 11, + selected: true + }, + { + label: 'December'.translate(), + value: 12, + selected: true + } + ], + onChange: function (newVal, oldVal) { + + } + }); + + dateTimeVariablePicker = new PMUI.field.DateTimeField({ + id: 'dateTimeVariablePicker', + label: 'Date time'.translate(), + datetime: true, + dateFormat: 'yy-mm-dd HH:ii:ss', + firstDay: 1, + controlsWidth: 150, + required: false, + readOnly: true, + minDate: 0, + maxDate: 1460 + }); + + formTimerEvent = new PMUI.form.Form({ + id: "formTimerEvent", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formTimerEvent", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "evnUid", + pmType: "text", + value: evnUid, + name: "evnUid", + readOnly: true, + visible: false, + valueType: 'string' + }, + { + id: "activityType", + pmType: "text", + value: activityType, + name: "activityType", + readOnly: true, + visible: false, + valueType: 'string' + }, + radioGroup, + { + pmType: "panel", + id: "datesPanel", + layout: 'hbox', + items: [ + startDate, + { + pmType: "checkbox", + id: "endDateCheckbox", + label: "End date".translate(), + controlPositioning: 'vertical', + maxDirectionOptions: 2, + value: '', + options: [ + { + label: "End date:".translate(), + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + if (newVal[2] == "1") { + $('#endDate').find('input:eq(0)').removeProp("disabled"); + } else { + $('#endDate').find('input:eq(0)').val('').attr("disabled", "disabled"); + formTimerEvent.getField('endDate').setValue(''); + } + } + }, + endDate, + oneDateTime, + dateTimeVariablePicker + ] + }, + { + pmType: "panel", + id: "dayHourMonthPanel", + layout: 'hbox', + items: [ + { + id: "dayType", + label: "Day".translate(), + pmType: "text", + value: "", + name: "dayType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + }, + { + id: "hourType", + label: "Hour".translate(), + pmType: "text", + value: "", + name: "hourType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + }, + { + id: "minuteType", + label: "Minute".translate(), + pmType: "text", + value: "", + name: "minuteType", + visible: true, + valueType: 'integer', + controlsWidth: 50, + maxLength: 2 + } + ] + }, + daysGroup, + monthsGroup, + { + id: "tmrevn_uid", + pmType: "text", + value: tmrevn_uid, + name: "tmrevn_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + formTimerEvent.initialData = function () { + var formElements = this.getItems()[0], + datesPanelElements, + radioGroupValues = {'radioGroup': formElements.items.get(2).getValue()}; + oldValues.push(radioGroupValues); + datesPanelElements = formElements.items.get(3).getItems(); + + }; + + getFormData = function ($form) { + var unindexed_array = $form.serializeArray(), + indexed_array = {}; + + $.map(unindexed_array, function (n, i) { + indexed_array[n['name']] = n['value']; + }); + return indexed_array; + }; + + getTimerEventData = function () { + var restClient = new PMRestClient({ + endpoint: 'timer-event/event/' + formTimerEvent.getField("evnUid").getValue(), + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (typeof response === "object" && JSON.stringify(response).length > 2) { + var opt = response.tmrevn_option.toUpperCase(); + switch (opt) { + case "HOURLY": + $("#radioGroup").find("input:eq(0)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "DAILY": + $("#radioGroup").find("input:eq(1)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + formTimerEvent.getField("daysGroup").setValue(""); + formTimerEvent.getField("daysGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { + return n.toString(); + }))); + break; + case "MONTHLY": + $("#radioGroup").find("input:eq(2)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("startDate").setValue(response.tmrevn_start_date); + if (response.tmrevn_end_date != "") { + formTimerEvent.getField("endDateCheckbox").setValue('["1"]'); + formTimerEvent.getField("endDate").setValue(response.tmrevn_end_date); + formTimerEvent.getField("endDate").enable(); + } + formTimerEvent.getField("dayType").setValue(response.tmrevn_day); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + formTimerEvent.getField("monthsGroup").setValue(""); + formTimerEvent.getField("monthsGroup").setValue(JSON.stringify(response.tmrevn_configuration_data.map(function (n) { + return n.toString(); + }))); + break; + case "ONE-DATE-TIME": + $("#radioGroup").find("input:eq(3)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + var d = response.tmrevn_next_run_date.replace(/-/g, "/"); + for (var i in ENABLED_FEATURES) { + if (ENABLED_FEATURES[i] == 'oq3S29xemxEZXJpZEIzN01qenJUaStSekY4cTdJVm5vbWtVM0d4S2lJSS9qUT0=') { + d = response.tmrevn_next_run_date; + } + } + d = new Date(d); + formTimerEvent.getField("oneDateTime").setValue(d); + break; + case "EVERY": + $("#radioGroup").find("input:eq(4)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "WAIT-FOR": + $("#radioGroup").find("input:eq(5)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + formTimerEvent.getField("dayType").setValue(response.tmrevn_day); + formTimerEvent.getField("hourType").setValue(response.tmrevn_hour); + formTimerEvent.getField("minuteType").setValue(response.tmrevn_minute); + break; + case "WAIT-UNTIL-SPECIFIED-DATE-TIME": + $("#radioGroup").find("input:eq(6)").trigger("click"); + formTimerEvent.getField("tmrevn_uid").setValue(response.tmrevn_uid); + var d = response.tmrevn_configuration_data.replace(/-/g, "/"); + d = new Date(d); + formTimerEvent.getField("dateTimeVariablePicker").setValue(d); + break; + } + } else { + if (eventType == "START") { + $("#radioGroup").find("input:eq(1)").trigger("click"); + } else { + $("#radioGroup").find("input:eq(5)").trigger("click"); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Timer Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + + /*end form*/ + + validateItems = function (itemId) { + var regexTest, + message, + valueItem, + regexTest; + + if (itemId === 'dayType') { + regexTest = regexDay; + message = "Error value: Day: 0 - 31".translate(); + } else if (itemId === 'hourType') { + regexTest = regexHour; + message = "Error value: Hour: 0 - 23".translate(); + } else if (itemId === 'minuteType') { + regexTest = regexMinute; + message = "Error value: Minute: 0 - 59".translate(); + } + + valueItem = $('#' + itemId).find('span input:eq(0)').val(); + + if (!regexTest.test(valueItem)) { + PMDesigner.msgFlash(message, timerEventPropertiesWindow, 'error', 3000, 5); + $('#' + itemId).find('span input:eq(0)').val(''); + return false; + } + }; + + domSettings = function () { + var requiredMessage = $(document.getElementById("requiredMessage")); + timerEventPropertiesWindow.body.appendChild(requiredMessage[0]); + requiredMessage[0].style['marginTop'] = '70px'; + + timerEventPropertiesWindow.footer.html.style.textAlign = 'right'; + + $('#hourType, #dayType, #minuteType').find('span input:eq(0)').bind('blur change', function () { + validateItems($(this).closest('div').attr('id')); + }); + + $("#dayType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "31"}); + $("#hourType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "23"}); + $("#minuteType").find("input").attr({"type": "number", "maxlength": "2", "min": "0", "max": "59"}); + + $("#radioGroup").css({"text-align": "center", "margin-bottom": "20px"}).find("label:eq(0)").remove(); + $("#endDateCheckbox").css({"width": "170px", "top": "6px", "left": "28px"}).find("label:eq(0)").remove(); + $("#endDateCheckbox").find("table:eq(0)").css("border", "0px"); + $("#startDate").css("width", ""); + $("#endDate").css("width", "104px").find("label:eq(0)").remove(); + $("#oneDateTime").css("width", ""); + $("#datesPanel").css("text-align", "center").find("label").css({ + "width": "", + "float": "", + "text-align": "right" + }); + $("#dayHourMonthPanel").css("text-align", "center").find("label").css({"float": "", "width": "34.5%"}); + + $("#daysGroup").css("text-align", "center").find("label:eq(0)").remove(); + $("#monthsGroup").css("text-align", "center").find("label:eq(0)").remove(); + $("#daysGroup").find("input").each(function () { + $(this).attr("name", $(this).val()); + }); + + $("#dateTimeVariablePicker").css("width", ""); + + + if (eventType == "START") { + $(formTimerEvent.getField("radioGroup").controls[0].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[1].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[2].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[3].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[4].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[5].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[6].html).parent().hide(); + $("#radioGroup").find("input:eq(1)").trigger("click"); + } else { + $(formTimerEvent.getField("radioGroup").controls[0].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[1].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[2].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[3].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[4].html).parent().hide(); + $(formTimerEvent.getField("radioGroup").controls[5].html).parent().show(); + $(formTimerEvent.getField("radioGroup").controls[6].html).parent().show(); + $("#radioGroup").find("input:eq(5)").trigger("click"); + } + }; + + timerEventPropertiesWindow.addItem(formTimerEvent); + timerEventPropertiesWindow.open(); + formTimerEvent.eventsDefined = false; + formTimerEvent.defineEvents(); + timerEventPropertiesWindow.showFooter(); + domSettings(); + getTimerEventData(); + oldValues = getFormData($("#formTimerEvent")); + }; +}()); + + +(function () { + PMDesigner.emailEventProperties = function (activity) { + var that = this, + buttonCancel, + buttonSave, + emailEventPropertiesWindow, + emailAcounts, + emailContent, + getEmailAccounts, + formEmailEvent, + emailWindowTinyMCE, + getFormData, + getEmailEventData, + domSettings, + activityId = activity.getID(), + activityType = activity.getEventMarker(), + uidProj = PMDesigner.project.id, + initTinyMCE = null, + oldValues, + emailEventId = "", + prf_uid = "", + ddSize = 21, + auxFromMail = {}, + defaultServerlabel = "Mail (PHP)".translate(), + triggerSelectedData; + /*options to display in drop down*/ + + /*window*/ + buttonCancel = new PMUI.ui.Button({ + id: 'cancelEmailEventsButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = false; + emailEventPropertiesWindow.isDirtyFormScript(); + } + }); + + buttonSave = new PMUI.ui.Button({ + id: 'saveEmailEventsButton', + text: "Save".translate(), + handler: function (event) { + PMDesigner.hideAllTinyEditorControls(); + var dataForm = formEmailEvent.getData(), + selectedAccount = formEmailEvent.getField('emailAcounts').getValue(); + if (formEmailEvent.isValid()) { + if (dataForm.emailEventId == "") { /*insert*/ + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'post', + messageError: '', + data: { + prf_filename: "emailEvent_" + new Date().getTime() + ".html", + prf_path: "templates", + prf_content: dataForm.filecontent + }, + functionSuccess: function (xhr, response) { + var restClient; + prf_uid = response.prf_uid; + if (prf_uid != "" && typeof prf_uid != "undefined") { + restClient = new PMRestClient({ + endpoint: 'email-event', + typeRequest: 'post', + data: { + evn_uid: activityId, + email_event_from: auxFromMail[selectedAccount] || '', + email_event_to: dataForm.ToEmail, + email_event_subject: dataForm.subjectEmail, + email_server_uid: dataForm.emailAcounts, + prf_uid: prf_uid + }, + functionSuccess: function () { + emailEventPropertiesWindow.close(); + PMDesigner.msgFlash('Email Event saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the Email Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + + + } else { + (new PMRestClient({ + endpoint: 'file-manager/' + dataForm.prf_uid, + typeRequest: 'update', + messageError: '', + data: { + prf_content: tinyMCE.activeEditor.getContent() + }, + functionSuccess: function (xhr, response) { + var restClient; + prf_uid = response.prf_uid; + if (prf_uid != "" && typeof prf_uid != "undefined") { + restClient = new PMRestClient({ + endpoint: 'email-event/' + dataForm.emailEventId, + typeRequest: 'update', + data: { + evn_uid: activityId, + email_event_from: auxFromMail[selectedAccount] || '', + email_event_to: dataForm.ToEmail, + email_event_subject: dataForm.subjectEmail, + email_server_uid: dataForm.emailAcounts, + prf_uid: prf_uid + }, + functionSuccess: function () { + emailEventPropertiesWindow.close(); + PMDesigner.msgFlash('Email Event Edited correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems Edited the Email Event, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } + } + }, + buttonType: 'success' + }); + + emailEventPropertiesWindow = new PMUI.ui.Window({ + id: "emailEventPropertiesWindow", + title: "Email Event Properties".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + PMDesigner.hideAllTinyEditorControls(); + clickedClose = true; + emailEventPropertiesWindow.isDirtyFormScript(); + } + }); + + emailEventPropertiesWindow.isDirtyFormScript = function () { + var that = this, + newValues, + message_window, + formData = formEmailEvent.getData(); + formData.filecontent = $(tinyMCE.activeEditor.getContent()).text().trim().length ? tinyMCE.activeEditor.getContent() : ""; + newValues = formData; + if (JSON.stringify(oldValues) !== JSON.stringify(newValues)) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Email Event".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + that.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + that.close(); + } + }; + /*end window*/ + + /*form*/ + emailAcounts = new PMUI.field.DropDownListField({ + id: "emailAcounts", + name: "emailAcounts", + label: "From".translate(), + options: null, + controlsWidth: 400, + required: false, + labelWidth: "15%", + onChange: function (newValue, prevValue) { + var uidTri = newValue, + oldValue, + i; + for (i = 0; i < triggerSelectedData.length; i += 1) { + if (triggerSelectedData[i].tri_uid === uidTri) { + formScriptTask.getItems()[1].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + oldValue = triggerSelectedData[i].tri_webbot; + } + } + } + }); + emailContent = new PMUI.field.TextAreaField({ + id: 'filecontent', + name: 'filecontent', + label: 'Content'.translate(), + required: true, + value: '', + rows: 210, + labelWidth: "15%", + controlsWidth: 720, + onChange: function (currentValue, previousValue) { + }, + style: {cssClasses: ['mafe-textarea-resize']} + }); + getEmailAccounts = function (emailAcounts) { + var restClient = new PMRestClient({ + endpoint: 'email-event/accounts/emailServer', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var i, + arrayOptions; + triggerSelectedData = response; + arrayOptions = []; + arrayOptions[0] = { + label: "Default email account".translate(), + value: "", + disabled: false, + selected: true + }; + for (i = 0; i < triggerSelectedData.length ; i += 1) { + arrayOptions.push({ + value: triggerSelectedData[i].uid, + label: response[i].mess_engine === "MAIL" ? + triggerSelectedData[i].mess_from_name && triggerSelectedData[i].mess_from_name !== "" ? + triggerSelectedData[i].mess_from_name : defaultServerlabel : triggerSelectedData[i].mess_from_name && triggerSelectedData[i].mess_from_name !== "" ? + triggerSelectedData[i].mess_from_name + ' <' + triggerSelectedData[i].mess_account + '>' : ' <' + triggerSelectedData[i].mess_account + '>' + }); + auxFromMail[triggerSelectedData[i].uid] = triggerSelectedData[i].email; + } + emailAcounts.setOptions(arrayOptions); + emailAcounts.setValue(arrayOptions[0].value); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + formEmailEvent = new PMUI.form.Form({ + id: "formEmailEvent", + border: true, + visibleHeader: false, + width: '900px', + height: "300px", + name: "formEmailEvent", + title: '', + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "activityId", + pmType: "text", + value: activityId, + name: "activityId", + visible: false, + valueType: 'string' + }, + { + id: "activityType", + pmType: "text", + value: activityType, + name: "activityType", + visible: false, + valueType: 'string' + }, + emailAcounts, + new CriteriaField({ + id: "ToEmail", + pmType: "text", + helper: "The email can be a string or a variable (@@myEmail), comma separated list of emails".translate(), + label: "To".translate(), + controlsWidth: 400, + value: "", + name: "ToEmail", + required: true, + visible: true, + labelWidth: "15%", + valueType: 'string' + }), + new CriteriaField({ + id: 'subjectEmail', + pmType: 'text', + label: "Subject".translate(), + controlsWidth: 400, + value: "", + name: "subjectEmail", + required: false, + visible: true, + labelWidth: "15%", + valueType: 'string' + }), + emailContent, + { + id: "emailEventId", + pmType: "text", + value: emailEventId, + name: "emailEventId", + visible: false, + valueType: 'string' + }, + { + id: "prf_uid", + pmType: "text", + value: prf_uid, + name: "prf_uid", + visible: false, + valueType: 'string' + } + ] + } + ] + }); + emailWindowTinyMCE = function () { + initTinyMCE = function () { + tinyMCE.activeEditor.domainURL = "/sys" + WORKSPACE + "/" + LANG + "/" + SKIN + "/"; + tinyMCE.activeEditor.processID = PMDesigner.project.id; + }; + formEmailEvent.getField('filecontent').getControls()[0].getHTML().className = 'tmceEditor'; + applyStyleWindowForm(emailEventPropertiesWindow); + tinyMCE.init({ + editor_selector: 'tmceEditor', + mode: 'specific_textareas', + directionality: 'ltr', + verify_html: false, + skin: 'o2k7', + theme: 'advanced', + skin_variant: 'silver', + relative_urls : false, + remove_script_host : false, + convert_urls: false, + plugins: 'advhr,advimage,advlink,advlist,autolink,autoresize,contextmenu,directionality,emotions,example,example_dependency,fullpage,fullscreen,iespell,inlinepopups,insertdatetime,layer,legacyoutput,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,style,tabfocus,table,template,visualblocks,visualchars,wordcount,xhtmlxtras,pmSimpleUploader,pmVariablePicker,style', + theme_advanced_buttons1: 'pmSimpleUploader,|,pmVariablePicker,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect,|,cut,copy,paste', + theme_advanced_buttons2: 'bullist,numlist,|,outdent,indent,blockquote,|,tablecontrols,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor,styleprops', + theme_advanced_buttons3: 'hr,removeformat,visualaid,|,sub,sup,|,ltr,rtl,|,code', + popup_css: "/js/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialogTinyBpmn.css", + oninit: initTinyMCE, + onchange_callback: function (inst) { + formEmailEvent.getField('filecontent').setValue(tinyMCE.activeEditor.getContent({format: 'raw'})); + }, + handle_event_callback: function (e) { + }, + setup: function (ed) { + ed.onSetContent.add(function (ed, l) { + formEmailEvent.getField('filecontent').setValue(tinyMCE.activeEditor.getContent({format: 'raw'})); + }); + } + }); + }; + getFormData = function ($form) { + var unindexed_array = $form.serializeArray(), + indexed_array = {}; + + $.map(unindexed_array, function (n, i) { + indexed_array[n['name']] = n['value']; + }); + return indexed_array; + }; + getEmailEventData = function () { + var restClient = new PMRestClient({ + endpoint: 'email-event/' + activityId, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var valFrom; + if (typeof response === "object") { + emailEventId = response.email_event_uid; + if (emailEventId !== "" && typeof emailEventId !== "undefined") { + formEmailEvent.getField('emailEventId').setValue(response.email_event_uid); + // Set as selected the email server by uid + if (response.email_server_uid !== "" && typeof response.email_server_uid !== "undefined") { + formEmailEvent.getField('emailAcounts').setValue(response.email_server_uid); + } + formEmailEvent.getField('subjectEmail').setValue(response.email_event_subject); + formEmailEvent.getField('ToEmail').setValue(response.email_event_to); + + formEmailEvent.getField('prf_uid').setValue(response.prf_uid); + + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'get', + messageError: '', + data: { + path: "templates" + }, + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i += 1) { + if (response[i].prf_uid == formEmailEvent.getField('prf_uid').getValue()) { + formEmailEvent.getField('filecontent').setValue(response[i].prf_content); + if (!$(tinyMCE.activeEditor.getContent()).text().trim().length) { + tinyMCE.activeEditor.setContent(response[i].prf_content); + } + break; + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + getEmailAccounts(emailAcounts); + + /*end form*/ + + this.deleteEmailEventByEventUid = function () { + (new PMRestClient({ + endpoint: 'email-event/by-event/' + activityId, + typeRequest: 'remove', + messageError: '', + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + })).executeRestClient(); + return this; + }; + + domSettings = function () { + emailEventPropertiesWindow.footer.html.style.textAlign = 'right'; + $("#emailAcounts").find("select:eq(0)").css("height", "auto").attr({ + "onmousedown": "if(this.options.length>" + ddSize + "){this.size=" + ddSize + ";}", + "onchange": "this.size=0;", + "onblur": "this.size=0;" + }); + }; + emailEventPropertiesWindow.addItem(formEmailEvent); + emailEventPropertiesWindow.open(); + emailEventPropertiesWindow.showFooter(); + emailWindowTinyMCE(); + domSettings(); + getEmailEventData(); + oldValues = formEmailEvent.getData(); + }; +}()); + + +SaveAsForm = function (settings) { + Mafe.Form.call(this, settings); + SaveAsForm.prototype.init.call(this, settings); +}; +SaveAsForm.prototype = new Mafe.Form(); +SaveAsForm.prototype.init = function () { + var that = this; + that.onSave = new Function(); + that.onCancel = new Function(); + that.setID("SaveAsForm"); + that.setTitle("Save as".translate()); + that.setItems([{ + id: "prj_name", + name: "pro_title", + pmType: "text", + label: "Title".translate(), + placeholder: "Title".translate(), + maxLength: 100, + required: true + }, { + id: "prj_description", + pmType: "textarea", + name: "pro_description", + label: "Description".translate(), + placeholder: "Description".translate(), + rows: 200 + }, { + id: "pro_category", + name: "pro_category", + pmType: "dropdown", + label: "Category".translate(), + options: [ + {value: "", label: "No Category".translate()} + ] + } + ]); + that.setButtons([{ + id: "idCancel", + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + that.onCancel(); + } + }, { + id: "idSave", + text: "Save".translate(), + buttonType: "success", + handler: function () { + that.onSave(); + } + } + ]); + that.loadCategory(); +}; +SaveAsForm.prototype.loadCategory = function () { + var that = this, + titleProcess; + var a = new PMRestClient({ + typeRequest: "post", + multipart: true, + data: { + calls: [{ + url: "project/categories", + method: "GET" + }, { + url: "project/" + PMDesigner.project.projectId + "/process", + method: "GET" + } + ] + }, + functionSuccess: function (xhr, response) { + var i, dt, category = that.getField("pro_category"); + dt = response[0].response; + for (i = 0; i < dt.length; i++) { + category.addOption({ + value: dt[i].cat_uid, + label: dt[i].cat_name + }); + } + //load data + dt = response[1].response; + titleProcess = "Copy of".translate() + " [" + dt.pro_title + "]"; + that.getField("pro_title").setValue(titleProcess.substring(0, 100)); + that.getField("pro_description").setValue(dt.pro_description); + that.getField("pro_category").setValue(dt.pro_category); + }, + functionFailure: function (xhr, response) { + } + }); + a.setBaseEndPoint(""); + a.executeRestClient(); +}; + +SaveAs = function (settings) { + Mafe.Window.call(this, settings); + SaveAs.prototype.init.call(this, settings); +}; +SaveAs.prototype = new Mafe.Window(); +SaveAs.prototype.init = function () { + var that = this; + that.saveAsForm = new SaveAsForm(); + that.saveAsForm.onYesConfirmCancellation = function () { + that.close(); + }; + that.saveAsForm.onCancel = function () { + that.saveAsForm.loseChanges({title: that.title}); + }; + that.saveAsForm.onSave = function () { + that.saveAsForm.getField("pro_title").setReadOnly(true); + that.saveAsForm.getField("pro_description").setReadOnly(true); + PMUI.getPMUIObject($(that.saveAsForm.html).find("#idSave")[0]).setDisabled(true); + var a = new PMRestClient({ + typeRequest: "post", + multipart: true, + data: { + calls: [{ + url: "project/save-as", + method: "POST", + data: { + prj_uid: PMDesigner.project.projectId, + prj_name: that.saveAsForm.getField("pro_title").getValue(), + prj_description: that.saveAsForm.getField("pro_description").getValue(), + prj_category: that.saveAsForm.getField("pro_category").getValue() + } + } + ] + }, + functionSuccess: function (xhr, response) { + if (response[0].response.prj_uid) { + that.close(); + window.location.href = "designer?prj_uid=" + response[0].response.prj_uid; + } else { + that.saveAsForm.getField("pro_title").setReadOnly(false); + that.saveAsForm.getField("pro_description").setReadOnly(false); + PMUI.getPMUIObject($(that.saveAsForm.html).find("#idSave")[0]).setDisabled(false); + var field = that.saveAsForm.getField("pro_title"); + $(field.html).find(".pmui-textlabel").text(response[0].response); + field.showMessage(); + } + }, + functionFailure: function (xhr, response) { + } + }); + a.setBaseEndPoint(""); + a.executeRestClient(); + }; + + that.setTitle("Save as".translate()); + that.addItem(that.saveAsForm); +}; +(function () { + PMDesigner.granularProcessExport = function () { + var totalObjects = 0, + objectValues, + buttonSave, + objectsGroup, + loadObjects, + domSettings, + granularProcessExportForm, + granularProcessExportWindow, + buttonCancel = new PMUI.ui.Button({ + id: 'cancelButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + granularProcessExportWindow.close(); + } + }); + + buttonSave = new PMUI.ui.Button({ + id: 'saveButton', + text: "Export".translate(), + handler: function (event) { + var selectedObjects, + locationOrigin, + ws = enviromentVariables('WORKSPACE'), + formData = granularProcessExportForm.getData(); + selectedObjects = JSON.parse(formData.objectsGroup).map(function (n) { + return n; + }); + if (selectedObjects.length === 0) { + PMDesigner.msgFlash('At least one object should be selected in order to execute the action.'.translate(), document.body, 'error', 3000, 5); + return; + } + if (!window.location.origin) { + locationOrigin = window.location.protocol + "//" + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { + locationOrigin = HTTP_SERVER_HOSTNAME; + } else { + locationOrigin = window.location.origin; + } + location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + + "/export-granular?access_token=" + PMDesigner.project.keys.access_token + '&objects=' + + encodeURIComponent(JSON.stringify(selectedObjects)); + granularProcessExportWindow.close(); + }, + buttonType: 'success' + }); + + granularProcessExportWindow = new PMUI.ui.Window({ + id: "granularProcessExportWindow", + title: "Export Process Objects".translate(), + width: 350, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + granularProcessExportWindow.close(); + } + }); + + objectsGroup = new PMUI.field.CheckBoxGroupField({ + labelVisible: false, + id: 'objectsGroup', + controlPositioning: 'horizontal', + maxDirectionOptions: 1, + required: true, + options: [], + onChange: function (newVal, oldVal) { + if (totalObjects > JSON.parse(newVal).length) { + granularProcessExportForm.getField('checkAllId').setValue(0); + } + } + }); + + loadObjects = function () { + var objectsList, + restClient, + i; + restClient = new PMRestClient({ + endpoint: 'export/listObjects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var arrayIds = [], + i; + objectsList = JSON.parse(response); + for (i in objectsList.data) { + objectsGroup.addOption({ + label: objectsList.data[i].OBJECT_NAME, + name: objectsList.data[i].OBJECT_NAME, + selected: false, + value: objectsList.data[i].OBJECT_ID + }); + arrayIds.push(objectsList.data[i].OBJECT_ID.toString()); + } + totalObjects = objectsList.data.length; + objectValues = objectsGroup.getValueFromControls(); + objectValues = JSON.parse(objectValues).length ? objectValues : JSON.stringify(arrayIds); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems loading the process objects.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + loadObjects(); + + granularProcessExportForm = new PMUI.form.Form({ + id: "granularProcessExportForm", + border: true, + visibleHeader: false, + width: '340px', + name: "granularProcessExportForm", + title: "", + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + pmType: "checkbox", + id: "checkAllId", + labelVisible: false, + controlPositioning: 'vertical', + maxDirectionOptions: 2, + value: '', + options: [ + { + label: "Check All".translate(), + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + if (newVal[2] === "1") { + objectsGroup.setValueToControls(objectValues); + } else { + objectsGroup.setValueToControls(); + } + } + }, + objectsGroup + ] + } + ] + }); + + domSettings = function () { + $('#objectsGroup').find('label:eq(0)').remove(); + }; + + granularProcessExportWindow.addItem(granularProcessExportForm); + granularProcessExportWindow.open(); + granularProcessExportWindow.showFooter(); + domSettings(); + }; +}()); + + diff --git a/workflow/public_html/lib/mafe/mafe.min.css b/workflow/public_html/lib/mafe/mafe.min.css new file mode 100644 index 000000000..29883a711 --- /dev/null +++ b/workflow/public_html/lib/mafe/mafe.min.css @@ -0,0 +1,7627 @@ +/* + * Default Layout Theme + * + * Created for jquery.layout + * + * Copyright (c) 2010 + * Fabrizio Balliano (http://www.fabrizioballiano.net) + * Kevin Dalman (http://allpro.net) + * + * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) + * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. + * + * Last Updated: 2010-02-10 + * NOTE: For best code readability, view this with a fixed-space font and tabs equal to 4-chars + */ + +/* + * DEFAULT FONT + * Just to make demo-pages look better - not actually relevant to Layout! + */ +/*body { + font-family: Geneva, Arial, Helvetica, sans-serif; + font-size: 100%; + *font-size: 80%; +}*/ + +/* + * PANES & CONTENT-DIVs + */ +.ui-layout-pane { /* all 'panes' */ + background: #FFF; + border: 1px solid #BBB; + padding: 2px; + overflow: auto; + /* DO NOT add scrolling (or padding) to 'panes' that have a content-div, + otherwise you may get double-scrollbars - on the pane AND on the content-div + - use ui-layout-wrapper class if pane has a content-div + - use ui-layout-container if pane has an inner-layout + */ + } + /* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */ + .ui-layout-content { + padding: 10px; + position: relative; /* contain floated or positioned elements */ + overflow: auto; /* add scrolling to content-div */ + } + +/* + * UTILITY CLASSES + * Must come AFTER pane-class above so will override + * These classes are NOT auto-generated and are NOT used by Layout + */ +.layout-child-container, +.layout-content-container { + padding: 0; + overflow: hidden; +} +.layout-child-container { + border: 0; /* remove border because inner-layout-panes probably have borders */ +} +.layout-scroll { + overflow: auto; +} +.layout-hide { + display: none; +} + +/* + * RESIZER-BARS + */ +.ui-layout-resizer { /* all 'resizer-bars' */ + background: #DDD; + border: 1px solid #BBB; + border-width: 0; + } + .ui-layout-resizer-drag { /* REAL resizer while resize in progress */ + } + .ui-layout-resizer-hover { /* affects both open and closed states */ + } + /* NOTE: It looks best when 'hover' and 'dragging' are set to the same color, + otherwise color shifts while dragging when bar can't keep up with mouse */ + .ui-layout-resizer-open-hover , /* hover-color to 'resize' */ + .ui-layout-resizer-dragging { /* resizer beging 'dragging' */ + background: #C4E1A4; + } + .ui-layout-resizer-dragging { /* CLONED resizer being dragged */ + border: 1px solid #BBB; + } + .ui-layout-resizer-north-dragging, + .ui-layout-resizer-south-dragging { + border-width: 1px 0; + } + .ui-layout-resizer-west-dragging, + .ui-layout-resizer-east-dragging { + border-width: 0 1px; + } + /* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */ + .ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */ + background: #E1A4A4; /* red */ + } + + .ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */ + background: #EBD5AA; + } + .ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */ + opacity: .10; /* show only a slight shadow */ + filter: alpha(opacity=10); + } + .ui-layout-resizer-sliding-hover { /* sliding resizer - hover */ + opacity: 1.00; /* on-hover, show the resizer-bar normally */ + filter: alpha(opacity=100); + } + /* sliding resizer - add 'outside-border' to resizer on-hover + * this sample illustrates how to target specific panes and states */ + .ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; } + .ui-layout-resizer-south-sliding-hover { border-top-width: 1px; } + .ui-layout-resizer-west-sliding-hover { border-right-width: 1px; } + .ui-layout-resizer-east-sliding-hover { border-left-width: 1px; } + +/* + * TOGGLER-BUTTONS + */ +.ui-layout-toggler { + border: 1px solid #BBB; /* match pane-border */ + background-color: #BBB; + } + .ui-layout-resizer-hover .ui-layout-toggler { + opacity: .60; + filter: alpha(opacity=60); + } + .ui-layout-toggler-hover , /* need when NOT resizable */ + .ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */ + background-color: #FC6; + opacity: 1.00; + filter: alpha(opacity=100); + } + .ui-layout-toggler-north , + .ui-layout-toggler-south { + border-width: 0 1px; /* left/right borders */ + } + .ui-layout-toggler-west , + .ui-layout-toggler-east { + border-width: 1px 0; /* top/bottom borders */ + } + /* hide the toggler-button when the pane is 'slid open' */ + .ui-layout-resizer-sliding .ui-layout-toggler { + display: none; + } + /* + * style the text we put INSIDE the togglers + */ + .ui-layout-toggler .content { + color: #666; + font-size: 12px; + font-weight: bold; + width: 100%; + padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */ + } + +/* + * PANE-MASKS + * these styles are hard-coded on mask elems, but are also + * included here as !important to ensure will overrides any generic styles + */ +.ui-layout-mask { + border: none !important; + padding: 0 !important; + margin: 0 !important; + overflow: hidden !important; + position: absolute !important; + opacity: 0 !important; + filter: Alpha(Opacity="0") !important; +} +.ui-layout-mask-inside-pane { /* masks always inside pane EXCEPT when pane is an iframe */ + top: 0 !important; + left: 0 !important; + width: 100% !important; + height: 100% !important; +} +div.ui-layout-mask {} /* standard mask for iframes */ +iframe.ui-layout-mask {} /* extra mask for objects/applets */ + +/* + * Default printing styles + */ +@media print { + /* + * Unless you want to print the layout as it appears onscreen, + * these html/body styles are needed to allow the content to 'flow' + */ + html { + height: auto !important; + overflow: visible !important; + } + body.ui-layout-container { + position: static !important; + top: auto !important; + bottom: auto !important; + left: auto !important; + right: auto !important; + /* only IE6 has container width & height set by Layout */ + _width: auto !important; + _height: auto !important; + } + .ui-layout-resizer, .ui-layout-toggler { + display: none !important; + } + /* + * Default pane print styles disables positioning, borders and backgrounds. + * You can modify these styles however it suit your needs. + */ + .ui-layout-pane { + border: none !important; + background: transparent !important; + position: relative !important; + top: auto !important; + bottom: auto !important; + left: auto !important; + right: auto !important; + width: auto !important; + height: auto !important; + overflow: visible !important; + } +} +/*! jQuery UI - v1.10.3 - 2013-09-02 +* http://jqueryui.com +* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css +* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=11px&cornerRadius=5px&bgColorHeader=%235c9ccc&bgTextureHeader=gloss_wave&bgImgOpacityHeader=55&borderColorHeader=%234297d7&fcHeader=%23ffffff&iconColorHeader=%23d8e7f3&bgColorContent=%23fcfdfd&bgTextureContent=inset_hard&bgImgOpacityContent=100&borderColorContent=%23a6c9e2&fcContent=%23222222&iconColorContent=%23469bdd&bgColorDefault=%23dfeffc&bgTextureDefault=glass&bgImgOpacityDefault=85&borderColorDefault=%23c5dbec&fcDefault=%232e6e9e&iconColorDefault=%236da8d5&bgColorHover=%23d0e5f5&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=%2379b7e7&fcHover=%231d5987&iconColorHover=%23217bc0&bgColorActive=%23f5f8f9&bgTextureActive=inset_hard&bgImgOpacityActive=100&borderColorActive=%2379b7e7&fcActive=%23e17009&iconColorActive=%23f9bd01&bgColorHighlight=%23fbec88&bgTextureHighlight=flat&bgImgOpacityHighlight=55&borderColorHighlight=%23fad42e&fcHighlight=%23363636&iconColorHighlight=%232e83ff&bgColorError=%23fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=%23cd0a0a&fcError=%23cd0a0a&iconColorError=%23cd0a0a&bgColorOverlay=%23aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=%23aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px +* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { + display: none; +} +.ui-helper-hidden-accessible { + border: 0; + clip: rect(0 0 0 0); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +.ui-helper-reset { + margin: 0; + padding: 0; + border: 0; + outline: 0; + line-height: 1.3; + text-decoration: none; + font-size: 100%; + list-style: none; +} +.ui-helper-clearfix:before, +.ui-helper-clearfix:after { + content: ""; + display: table; + border-collapse: collapse; +} +.ui-helper-clearfix:after { + clear: both; +} +.ui-helper-clearfix { + min-height: 0; /* support: IE7 */ +} +.ui-helper-zfix { + width: 100%; + height: 100%; + top: 0; + left: 0; + position: absolute; + opacity: 0; + filter:Alpha(Opacity=0); +} + +.ui-front { + z-index: 100; +} + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { + cursor: default !important; +} + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + display: block; + text-indent: -99999px; + overflow: hidden; + background-repeat: no-repeat; +} + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; +} +.ui-resizable { + position: relative; +} +.ui-resizable-handle { + position: absolute; + font-size: 0.1px; + display: block; +} +.ui-resizable-disabled .ui-resizable-handle, +.ui-resizable-autohide .ui-resizable-handle { + display: none; +} +.ui-resizable-n { + cursor: n-resize; + height: 7px; + width: 100%; + top: -5px; + left: 0; +} +.ui-resizable-s { + cursor: s-resize; + height: 7px; + width: 100%; + bottom: -5px; + left: 0; +} +.ui-resizable-e { + cursor: e-resize; + width: 7px; + right: -5px; + top: 0; + height: 100%; +} +.ui-resizable-w { + cursor: w-resize; + width: 7px; + left: -5px; + top: 0; + height: 100%; +} +.ui-resizable-se { + cursor: se-resize; + width: 12px; + height: 12px; + right: 1px; + bottom: 1px; +} +.ui-resizable-sw { + cursor: sw-resize; + width: 9px; + height: 9px; + left: -5px; + bottom: -5px; +} +.ui-resizable-nw { + cursor: nw-resize; + width: 9px; + height: 9px; + left: -5px; + top: -5px; +} +.ui-resizable-ne { + cursor: ne-resize; + width: 9px; + height: 9px; + right: -5px; + top: -5px; +} +.ui-selectable-helper { + position: absolute; + z-index: 100; + border: 1px dotted black; +} +.ui-accordion .ui-accordion-header { + display: block; + cursor: pointer; + position: relative; + margin-top: 2px; + padding: .5em .5em .5em .7em; + min-height: 0; /* support: IE7 */ +} +.ui-accordion .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-noicons { + padding-left: .7em; +} +.ui-accordion .ui-accordion-icons .ui-accordion-icons { + padding-left: 2.2em; +} +.ui-accordion .ui-accordion-header .ui-accordion-header-icon { + position: absolute; + left: .5em; + top: 50%; + margin-top: -8px; +} +.ui-accordion .ui-accordion-content { + padding: 1em 2.2em; + border-top: 0; + overflow: auto; +} +.ui-autocomplete { + position: absolute; + top: 0; + left: 0; + cursor: default; +} +.ui-button { + display: inline-block; + position: relative; + padding: 0; + line-height: normal; + margin-right: .1em; + cursor: pointer; + vertical-align: middle; + text-align: center; + overflow: visible; /* removes extra width in IE */ +} +.ui-button, +.ui-button:link, +.ui-button:visited, +.ui-button:hover, +.ui-button:active { + text-decoration: none; +} +/* to make room for the icon, a width needs to be set here */ +.ui-button-icon-only { + width: 2.2em; +} +/* button elements seem to need a little more width */ +button.ui-button-icon-only { + width: 2.4em; +} +.ui-button-icons-only { + width: 3.4em; +} +button.ui-button-icons-only { + width: 3.7em; +} + +/* button text element */ +.ui-button .ui-button-text { + display: block; + line-height: normal; +} +.ui-button-text-only .ui-button-text { + padding: .4em 1em; +} +.ui-button-icon-only .ui-button-text, +.ui-button-icons-only .ui-button-text { + padding: .4em; + text-indent: -9999999px; +} +.ui-button-text-icon-primary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 1em .4em 2.1em; +} +.ui-button-text-icon-secondary .ui-button-text, +.ui-button-text-icons .ui-button-text { + padding: .4em 2.1em .4em 1em; +} +.ui-button-text-icons .ui-button-text { + padding-left: 2.1em; + padding-right: 2.1em; +} +/* no icon support for input elements, provide padding by default */ +input.ui-button { + padding: .4em 1em; +} + +/* button icon element(s) */ +.ui-button-icon-only .ui-icon, +.ui-button-text-icon-primary .ui-icon, +.ui-button-text-icon-secondary .ui-icon, +.ui-button-text-icons .ui-icon, +.ui-button-icons-only .ui-icon { + position: absolute; + top: 50%; + margin-top: -8px; +} +.ui-button-icon-only .ui-icon { + left: 50%; + margin-left: -8px; +} +.ui-button-text-icon-primary .ui-button-icon-primary, +.ui-button-text-icons .ui-button-icon-primary, +.ui-button-icons-only .ui-button-icon-primary { + left: .5em; +} +.ui-button-text-icon-secondary .ui-button-icon-secondary, +.ui-button-text-icons .ui-button-icon-secondary, +.ui-button-icons-only .ui-button-icon-secondary { + right: .5em; +} + +/* button sets */ +.ui-buttonset { + margin-right: 7px; +} +.ui-buttonset .ui-button { + margin-left: 0; + margin-right: -.3em; +} + +/* workarounds */ +/* reset extra padding in Firefox, see h5bp.com/l */ +input.ui-button::-moz-focus-inner, +button.ui-button::-moz-focus-inner { + border: 0; + padding: 0; +} +.ui-datepicker { + width: 17em; + padding: .2em .2em 0; + display: none; +} +.ui-datepicker .ui-datepicker-header { + position: relative; + padding: .2em 0; +} +.ui-datepicker .ui-datepicker-prev, +.ui-datepicker .ui-datepicker-next { + position: absolute; + top: 2px; + width: 1.8em; + height: 1.8em; +} +.ui-datepicker .ui-datepicker-prev-hover, +.ui-datepicker .ui-datepicker-next-hover { + top: 1px; +} +.ui-datepicker .ui-datepicker-prev { + left: 2px; +} +.ui-datepicker .ui-datepicker-next { + right: 2px; +} +.ui-datepicker .ui-datepicker-prev-hover { + left: 1px; +} +.ui-datepicker .ui-datepicker-next-hover { + right: 1px; +} +.ui-datepicker .ui-datepicker-prev span, +.ui-datepicker .ui-datepicker-next span { + display: block; + position: absolute; + left: 50%; + margin-left: -8px; + top: 50%; + margin-top: -8px; +} +.ui-datepicker .ui-datepicker-title { + margin: 0 2.3em; + line-height: 1.8em; + text-align: center; +} +.ui-datepicker .ui-datepicker-title select { + font-size: 1em; + margin: 1px 0; +} +.ui-datepicker select.ui-datepicker-month-year { + width: 100%; +} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { + width: 49%; +} +.ui-datepicker table { + width: 100%; + font-size: .9em; + border-collapse: collapse; + margin: 0 0 .4em; +} +.ui-datepicker th { + padding: .7em .3em; + text-align: center; + font-weight: bold; + border: 0; +} +.ui-datepicker td { + border: 0; + padding: 1px; +} +.ui-datepicker td span, +.ui-datepicker td a { + display: block; + padding: .2em; + text-align: right; + text-decoration: none; +} +.ui-datepicker .ui-datepicker-buttonpane { + background-image: none; + margin: .7em 0 0 0; + padding: 0 .2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} +.ui-datepicker .ui-datepicker-buttonpane button { + float: right; + margin: .5em .2em .4em; + cursor: pointer; + padding: .2em .6em .3em .6em; + width: auto; + overflow: visible; +} +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { + float: left; +} + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { + width: auto; +} +.ui-datepicker-multi .ui-datepicker-group { + float: left; +} +.ui-datepicker-multi .ui-datepicker-group table { + width: 95%; + margin: 0 auto .4em; +} +.ui-datepicker-multi-2 .ui-datepicker-group { + width: 50%; +} +.ui-datepicker-multi-3 .ui-datepicker-group { + width: 33.3%; +} +.ui-datepicker-multi-4 .ui-datepicker-group { + width: 25%; +} +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { + border-left-width: 0; +} +.ui-datepicker-multi .ui-datepicker-buttonpane { + clear: left; +} +.ui-datepicker-row-break { + clear: both; + width: 100%; + font-size: 0; +} + +/* RTL support */ +.ui-datepicker-rtl { + direction: rtl; +} +.ui-datepicker-rtl .ui-datepicker-prev { + right: 2px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next { + left: 2px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-prev:hover { + right: 1px; + left: auto; +} +.ui-datepicker-rtl .ui-datepicker-next:hover { + left: 1px; + right: auto; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane { + clear: right; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button { + float: left; +} +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, +.ui-datepicker-rtl .ui-datepicker-group { + float: right; +} +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { + border-right-width: 0; + border-left-width: 1px; +} +.ui-dialog { + position: absolute; + top: 0; + left: 0; + padding: .2em; + outline: 0; +} +.ui-dialog .ui-dialog-titlebar { + padding: .4em 1em; + position: relative; +} +.ui-dialog .ui-dialog-title { + float: left; + margin: .1em 0; + white-space: nowrap; + width: 90%; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-dialog .ui-dialog-titlebar-close { + position: absolute; + right: .3em; + top: 50%; + width: 21px; + margin: -10px 0 0 0; + padding: 1px; + height: 20px; +} +.ui-dialog .ui-dialog-content { + position: relative; + border: 0; + padding: .5em 1em; + background: none; + overflow: auto; +} +.ui-dialog .ui-dialog-buttonpane { + text-align: left; + border-width: 1px 0 0 0; + background-image: none; + margin-top: .5em; + padding: .3em 1em .5em .4em; +} +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { + float: right; +} +.ui-dialog .ui-dialog-buttonpane button { + margin: .5em .4em .5em 0; + cursor: pointer; +} +.ui-dialog .ui-resizable-se { + width: 12px; + height: 12px; + right: -5px; + bottom: -5px; + background-position: 16px 16px; +} +.ui-draggable .ui-dialog-titlebar { + cursor: move; +} +.ui-menu { + list-style: none; + padding: 2px; + margin: 0; + display: block; + outline: none; +} +.ui-menu .ui-menu { + margin-top: -3px; + position: absolute; +} +.ui-menu .ui-menu-item { + margin: 0; + padding: 0; + width: 100%; + /* support: IE10, see #8844 */ + list-style-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7); +} +.ui-menu .ui-menu-divider { + margin: 5px -2px 5px -2px; + height: 0; + font-size: 0; + line-height: 0; + border-width: 1px 0 0 0; +} +.ui-menu .ui-menu-item a { + text-decoration: none; + display: block; + padding: 2px .4em; + line-height: 1.5; + min-height: 0; /* support: IE7 */ + font-weight: normal; +} +.ui-menu .ui-menu-item a.ui-state-focus, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} + +.ui-menu .ui-state-disabled { + font-weight: normal; + margin: .4em 0 .2em; + line-height: 1.5; +} +.ui-menu .ui-state-disabled a { + cursor: default; +} + +/* icon support */ +.ui-menu-icons { + position: relative; +} +.ui-menu-icons .ui-menu-item a { + position: relative; + padding-left: 2em; +} + +/* left-aligned */ +.ui-menu .ui-icon { + position: absolute; + top: .2em; + left: .2em; +} + +/* right-aligned */ +.ui-menu .ui-menu-icon { + position: static; + float: right; +} +.ui-progressbar { + height: 2em; + text-align: left; + overflow: hidden; +} +.ui-progressbar .ui-progressbar-value { + margin: -1px; + height: 100%; +} +.ui-progressbar .ui-progressbar-overlay { + background: url("images/animated-overlay.gif"); + height: 100%; + filter: alpha(opacity=25); + opacity: 0.25; +} +.ui-progressbar-indeterminate .ui-progressbar-value { + background-image: none; +} +.ui-slider { + position: relative; + text-align: left; +} +.ui-slider .ui-slider-handle { + position: absolute; + z-index: 2; + width: 1.2em; + height: 1.2em; + cursor: default; +} +.ui-slider .ui-slider-range { + position: absolute; + z-index: 1; + font-size: .7em; + display: block; + border: 0; + background-position: 0 0; +} + +/* For IE8 - See #6727 */ +.ui-slider.ui-state-disabled .ui-slider-handle, +.ui-slider.ui-state-disabled .ui-slider-range { + filter: inherit; +} + +.ui-slider-horizontal { + height: .8em; +} +.ui-slider-horizontal .ui-slider-handle { + top: -.3em; + margin-left: -.6em; +} +.ui-slider-horizontal .ui-slider-range { + top: 0; + height: 100%; +} +.ui-slider-horizontal .ui-slider-range-min { + left: 0; +} +.ui-slider-horizontal .ui-slider-range-max { + right: 0; +} + +.ui-slider-vertical { + width: .8em; + height: 100px; +} +.ui-slider-vertical .ui-slider-handle { + left: -.3em; + margin-left: 0; + margin-bottom: -.6em; +} +.ui-slider-vertical .ui-slider-range { + left: 0; + width: 100%; +} +.ui-slider-vertical .ui-slider-range-min { + bottom: 0; +} +.ui-slider-vertical .ui-slider-range-max { + top: 0; +} +.ui-spinner { + position: relative; + display: inline-block; + overflow: hidden; + padding: 0; + vertical-align: middle; +} +.ui-spinner-input { + border: none; + background: none; + color: inherit; + padding: 0; + margin: .2em 0; + vertical-align: middle; + margin-left: .4em; + margin-right: 22px; +} +.ui-spinner-button { + width: 16px; + height: 50%; + font-size: .5em; + padding: 0; + margin: 0; + text-align: center; + position: absolute; + cursor: default; + display: block; + overflow: hidden; + right: 0; +} +/* more specificity required here to overide default borders */ +.ui-spinner a.ui-spinner-button { + border-top: none; + border-bottom: none; + border-right: none; +} +/* vertical centre icon */ +.ui-spinner .ui-icon { + position: absolute; + margin-top: -8px; + top: 50%; + left: 0; +} +.ui-spinner-up { + top: 0; +} +.ui-spinner-down { + bottom: 0; +} + +/* TR overrides */ +.ui-spinner .ui-icon-triangle-1-s { + /* need to fix icons sprite */ + background-position: -65px -16px; +} +.ui-tabs { + position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ + padding: .2em; +} +.ui-tabs .ui-tabs-nav { + margin: 0; + padding: .2em .2em 0; +} +.ui-tabs .ui-tabs-nav li { + list-style: none; + float: left; + position: relative; + top: 0; + margin: 1px .2em 0 0; + border-bottom-width: 0; + padding: 0; + white-space: nowrap; +} +.ui-tabs .ui-tabs-nav li a { + float: left; + padding: .5em 1em; + text-decoration: none; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active { + margin-bottom: -1px; + padding-bottom: 1px; +} +.ui-tabs .ui-tabs-nav li.ui-tabs-active a, +.ui-tabs .ui-tabs-nav li.ui-state-disabled a, +.ui-tabs .ui-tabs-nav li.ui-tabs-loading a { + cursor: text; +} +.ui-tabs .ui-tabs-nav li a, /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { + cursor: pointer; +} +.ui-tabs .ui-tabs-panel { + display: block; + border-width: 0; + padding: 1em 1.4em; + background: none; +} +.ui-tooltip { + padding: 8px; + position: absolute; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; +} +body .ui-tooltip { + border-width: 2px; +} + +/* Component containers +----------------------------------*/ +.ui-widget { + font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; + font-size: 11px; +} +.ui-widget .ui-widget { + font-size: 1em; +} +.ui-widget input, +.ui-widget select, +.ui-widget textarea, +.ui-widget button { + font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; + font-size: 1em; +} +.ui-widget-content { + border-right: 1px solid #a6c9e2; + border-left: 1px solid #a6c9e2; + border-bottom: 1px solid #a6c9e2; + background: #fcfdfd url(images/ui-bg_inset-hard_100_fcfdfd_1x100.png) 50% bottom repeat-x; + color: #222222; +} +.ui-widget-content a { + color: #222222; +} +.ui-widget-header { + border: 1px solid #4297d7; + background: #5c9ccc url(images/ui-bg_gloss-wave_55_5c9ccc_500x100.png) 50% 50% repeat-x; + color: #ffffff; + font-weight: bold; + /*color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #49afcd; + *background-color: #2f96b4; + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); + background-repeat: repeat-x; + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);*/ +} +.ui-widget-header a { + color: #ffffff; +} + +/* Interaction states +----------------------------------*/ +.ui-state-default, +.ui-widget-content .ui-state-default, +.ui-widget-header .ui-state-default { + border: 1px solid #c5dbec; + background: #dfeffc url(images/ui-bg_glass_85_dfeffc_1x400.png) 50% 50% repeat-x; + font-weight: bold; + color: #2e6e9e; +} +.ui-state-default a, +.ui-state-default a:link, +.ui-state-default a:visited { + color: #2e6e9e; + text-decoration: none; +} +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover, +.ui-state-focus, +.ui-widget-content .ui-state-focus, +.ui-widget-header .ui-state-focus { + border: 1px solid #79b7e7; + background: #d0e5f5 url(images/ui-bg_glass_75_d0e5f5_1x400.png) 50% 50% repeat-x; + font-weight: bold; + color: #1d5987; +} +.ui-state-hover a, +.ui-state-hover a:hover, +.ui-state-hover a:link, +.ui-state-hover a:visited { + color: #1d5987; + text-decoration: none; +} +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #79b7e7; + background: #f5f8f9 url(images/ui-bg_inset-hard_100_f5f8f9_1x100.png) 50% 50% repeat-x; + font-weight: bold; + color: #e17009; +} +.ui-state-active a, +.ui-state-active a:link, +.ui-state-active a:visited { + color: #e17009; + text-decoration: none; +} + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, +.ui-widget-content .ui-state-highlight, +.ui-widget-header .ui-state-highlight { + border: 1px solid #fad42e; + background: #fbec88 url(images/ui-bg_flat_55_fbec88_40x100.png) 50% 50% repeat-x; + color: #363636; +} +.ui-state-highlight a, +.ui-widget-content .ui-state-highlight a, +.ui-widget-header .ui-state-highlight a { + color: #363636; +} +.ui-state-error, +.ui-widget-content .ui-state-error, +.ui-widget-header .ui-state-error { + border: 1px solid #cd0a0a; + background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; + color: #cd0a0a; +} +.ui-state-error a, +.ui-widget-content .ui-state-error a, +.ui-widget-header .ui-state-error a { + color: #cd0a0a; +} +.ui-state-error-text, +.ui-widget-content .ui-state-error-text, +.ui-widget-header .ui-state-error-text { + color: #cd0a0a; +} +.ui-priority-primary, +.ui-widget-content .ui-priority-primary, +.ui-widget-header .ui-priority-primary { + font-weight: bold; +} +.ui-priority-secondary, +.ui-widget-content .ui-priority-secondary, +.ui-widget-header .ui-priority-secondary { + opacity: .7; + filter:Alpha(Opacity=70); + font-weight: normal; +} +.ui-state-disabled, +.ui-widget-content .ui-state-disabled, +.ui-widget-header .ui-state-disabled { + opacity: .35; + filter:Alpha(Opacity=35); + background-image: none; +} +.ui-state-disabled .ui-icon { + filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ +} + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { + width: 16px; + height: 16px; +} +.ui-icon, +.ui-widget-content .ui-icon { + background-image: url(images/ui-icons_469bdd_256x240.png); +} +.ui-widget-header .ui-icon { + background-image: url(images/ui-icons_d8e7f3_256x240.png); +} +.ui-state-default .ui-icon { + background-image: url(images/ui-icons_6da8d5_256x240.png); +} +.ui-state-hover .ui-icon, +.ui-state-focus .ui-icon { + background-image: url(images/ui-icons_217bc0_256x240.png); +} +.ui-state-active .ui-icon { + background-image: url(images/ui-icons_f9bd01_256x240.png); +} +.ui-state-highlight .ui-icon { + background-image: url(images/ui-icons_2e83ff_256x240.png); +} +.ui-state-error .ui-icon, +.ui-state-error-text .ui-icon { + background-image: url(images/ui-icons_cd0a0a_256x240.png); +} + +/* positioning */ +.ui-icon-blank { background-position: 16px 16px; } +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-on { background-position: -96px -144px; } +.ui-icon-radio-off { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, +.ui-corner-top, +.ui-corner-left, +.ui-corner-tl { + border-top-left-radius: 5px; +} +.ui-corner-all, +.ui-corner-top, +.ui-corner-right, +.ui-corner-tr { + border-top-right-radius: 5px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-left, +.ui-corner-bl { + border-bottom-left-radius: 5px; +} +.ui-corner-all, +.ui-corner-bottom, +.ui-corner-right, +.ui-corner-br { + border-bottom-right-radius: 5px; +} + +/* Overlays */ +.ui-widget-overlay { + background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); +} +.ui-widget-shadow { + margin: -8px 0 0 -8px; + padding: 8px; + background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; + opacity: .3; + filter: Alpha(Opacity=30); + border-radius: 8px; +} +.introjs-overlay { + position: absolute; + z-index: 999999; + background-color: #000; + opacity: 0; + background: -moz-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -webkit-gradient(radial,center center,0px,center center,100%,color-stop(0%,rgba(0,0,0,0.4)),color-stop(100%,rgba(0,0,0,0.9))); + background: -webkit-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -o-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: -ms-radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + background: radial-gradient(center,ellipse cover,rgba(0,0,0,0.4) 0,rgba(0,0,0,0.9) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#66000000',endColorstr='#e6000000',GradientType=1); + -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; + filter: alpha(opacity=50); + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-fixParent { + z-index: auto !important; + opacity: 1.0 !important; + position: absolute !important; + -webkit-transform: none !important; + -moz-transform: none !important; + -ms-transform: none !important; + -o-transform: none !important; + transform: none !important; +} + +.introjs-showElement, +tr.introjs-showElement > td, +tr.introjs-showElement > th { + z-index: 9999999 !important; +} + +.introjs-disableInteraction { + z-index: 99999999 !important; + position: absolute; +} + +.introjs-relativePosition, +tr.introjs-showElement > td, +tr.introjs-showElement > th { + position: relative; +} + +.introjs-helperLayer { + position: fixed; + z-index: 9999998; + background-color: #FFF; + background-color: rgba(255,255,255,.9); + border: 1px solid #777; + border: 1px solid rgba(0,0,0,.5); + border-radius: 4px; + box-shadow: 0 2px 15px rgba(0,0,0,.4); + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-tooltipReferenceLayer { + position: fixed; + z-index: 10000000; + background-color: transparent; + -webkit-transition: all 0.3s ease-out; + -moz-transition: all 0.3s ease-out; + -ms-transition: all 0.3s ease-out; + -o-transition: all 0.3s ease-out; + transition: all 0.3s ease-out; +} + +.introjs-helperLayer *, +.introjs-helperLayer *:before, +.introjs-helperLayer *:after { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + -ms-box-sizing: content-box; + -o-box-sizing: content-box; + box-sizing: content-box; +} + +.introjs-helperNumberLayer { + position: absolute; + top: 5px; + /*left: -16px;*/ + left: 50%; + z-index: 9999999999 !important; + padding: 2px; + font-family: Arial, verdana, tahoma; + font-size: 13px; + font-weight: bold; + color: white; + text-align: center; + text-shadow: 1px 1px 1px rgba(0,0,0,.3); + background: #ff3019; /* Old browsers */ + background: -webkit-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Chrome10+,Safari5.1+ */ + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ff3019), color-stop(100%, #cf0404)); /* Chrome,Safari4+ */ + background: -moz-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* FF3.6+ */ + background: -ms-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* IE10+ */ + background: -o-linear-gradient(top, #ff3019 0%, #cf0404 100%); /* Opera 11.10+ */ + background: linear-gradient(to bottom, #ff3019 0%, #cf0404 100%); /* W3C */ + width: 20px; + height:20px; + line-height: 20px; + border: 3px solid white; + border-radius: 50%; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3019', endColorstr='#cf0404', GradientType=0); /* IE6-9 */ + filter: progid:DXImageTransform.Microsoft.Shadow(direction=135, strength=2, color=ff0000); /* IE10 text shadows */ + box-shadow: 0 2px 5px rgba(0,0,0,.4); +} + +.introjs-arrow { + border: 5px solid white; + content:''; + position: absolute; +} +.introjs-arrow.top { + top: -10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.top-right { + top: -10px; + right: 10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.top-middle { + top: -10px; + left: 50%; + margin-left: -5px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:white; + border-left-color:transparent; +} +.introjs-arrow.right { + right: -10px; + top: 10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:white; +} +.introjs-arrow.right-bottom { + bottom:10px; + right: -10px; + border-top-color:transparent; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:white; +} +.introjs-arrow.bottom { + bottom: -10px; + border-top-color:white; + border-right-color:transparent; + border-bottom-color:transparent; + border-left-color:transparent; +} +.introjs-arrow.left { + left: -10px; + top: 10px; + border-top-color:transparent; + border-right-color:white; + border-bottom-color:transparent; + border-left-color:transparent; +} +.introjs-arrow.left-bottom { + left: -10px; + bottom:10px; + border-top-color:transparent; + border-right-color:white; + border-bottom-color:transparent; + border-left-color:transparent; +} + +.introjs-tooltip { + position: absolute; + padding: 10px; + background-color: white; + min-width: 200px; + max-width: 600px; + border-radius: 3px; + box-shadow: 0 1px 10px rgba(0,0,0,.4); + -webkit-transition: opacity 0.1s ease-out; + -moz-transition: opacity 0.1s ease-out; + -ms-transition: opacity 0.1s ease-out; + -o-transition: opacity 0.1s ease-out; + transition: opacity 0.1s ease-out; +} + +.introjs-tooltipbuttons { + text-align: right; + white-space: nowrap; +} + +/* + Buttons style by http://nicolasgallagher.com/lab/css3-github-buttons/ + Changed by Afshin Mehrabani +*/ +.introjs-button { + position: relative; + overflow: visible; + display: inline-block; + padding: 0.3em 0.8em; + border: 1px solid #d4d4d4; + margin: 0; + text-decoration: none; + text-shadow: 1px 1px 0 #fff; + font: 11px/normal sans-serif; + color: #333; + white-space: nowrap; + cursor: pointer; + outline: none; + background-color: #ececec; + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f4f4f4), to(#ececec)); + background-image: -moz-linear-gradient(#f4f4f4, #ececec); + background-image: -o-linear-gradient(#f4f4f4, #ececec); + background-image: linear-gradient(#f4f4f4, #ececec); + -webkit-background-clip: padding; + -moz-background-clip: padding; + -o-background-clip: padding-box; + /*background-clip: padding-box;*/ /* commented out due to Opera 11.10 bug */ + -webkit-border-radius: 0.2em; + -moz-border-radius: 0.2em; + border-radius: 0.2em; + /* IE hacks */ + zoom: 1; + *display: inline; + margin-top: 10px; +} + +.introjs-button:hover { + border-color: #bcbcbc; + text-decoration: none; + box-shadow: 0px 1px 1px #e3e3e3; +} + +.introjs-button:focus, +.introjs-button:active { + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ececec), to(#f4f4f4)); + background-image: -moz-linear-gradient(#ececec, #f4f4f4); + background-image: -o-linear-gradient(#ececec, #f4f4f4); + background-image: linear-gradient(#ececec, #f4f4f4); +} + +/* overrides extra padding on button elements in Firefox */ +.introjs-button::-moz-focus-inner { + padding: 0; + border: 0; +} + +.introjs-skipbutton { + margin-right: 5px; + color: #7a7a7a; +} + +.introjs-prevbutton { + -webkit-border-radius: 0.2em 0 0 0.2em; + -moz-border-radius: 0.2em 0 0 0.2em; + border-radius: 0.2em 0 0 0.2em; + border-right: none; +} + +.introjs-nextbutton { + -webkit-border-radius: 0 0.2em 0.2em 0; + -moz-border-radius: 0 0.2em 0.2em 0; + border-radius: 0 0.2em 0.2em 0; +} + +.introjs-disabled, .introjs-disabled:hover, .introjs-disabled:focus { + color: #9a9a9a; + border-color: #d4d4d4; + box-shadow: none; + cursor: default; + background-color: #f4f4f4; + background-image: none; + text-decoration: none; +} + +.introjs-bullets { + text-align: center; +} +.introjs-bullets ul { + clear: both; + margin: 15px auto 0; + padding: 0; + display: inline-block; +} +.introjs-bullets ul li { + list-style: none; + float: left; + margin: 0 2px; +} +.introjs-bullets ul li a { + display: block; + width: 6px; + height: 6px; + background: #ccc; + border-radius: 10px; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + text-decoration: none; +} +.introjs-bullets ul li a:hover { + background: #999; +} +.introjs-bullets ul li a.active { + background: #999; +} + +.introjs-progress { + overflow: hidden; + height: 10px; + margin: 10px 0 5px 0; + border-radius: 4px; + background-color: #ecf0f1 +} +.introjs-progressbar { + float: left; + width: 0%; + height: 100%; + font-size: 10px; + line-height: 10px; + text-align: center; + background-color: #08c; +} + +.introjsFloatingElement { + position: absolute; + height: 0; + width: 0; + left: 50%; + top: 50%; +} + +table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}table.dataTable thead th,table.dataTable tfoot th{font-weight:bold}table.dataTable thead th,table.dataTable thead td{padding:10px 18px;border-bottom:1px solid #111}table.dataTable thead th:active,table.dataTable thead td:active{outline:none}table.dataTable tfoot th,table.dataTable tfoot td{padding:10px 18px 6px 18px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer;*cursor:hand}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url("../img/sort_both.png")}table.dataTable thead .sorting_asc{background-image:url("../img/sort_asc.png")}table.dataTable thead .sorting_desc{background-image:url("../img/sort_desc.png")}table.dataTable thead .sorting_asc_disabled{background-image:url("../img/sort_asc_disabled.png")}table.dataTable thead .sorting_desc_disabled{background-image:url("../img/sort_desc_disabled.png")}table.dataTable tbody tr{background-color:#fff}table.dataTable tbody tr.selected{background-color:#B0BED9}table.dataTable tbody th,table.dataTable tbody td{padding:8px 10px}table.dataTable.row-border tbody th,table.dataTable.row-border tbody td,table.dataTable.display tbody th,table.dataTable.display tbody td{border-top:1px solid #ddd}table.dataTable.row-border tbody tr:first-child th,table.dataTable.row-border tbody tr:first-child td,table.dataTable.display tbody tr:first-child th,table.dataTable.display tbody tr:first-child td{border-top:none}table.dataTable.cell-border tbody th,table.dataTable.cell-border tbody td{border-top:1px solid #ddd;border-right:1px solid #ddd}table.dataTable.cell-border tbody tr th:first-child,table.dataTable.cell-border tbody tr td:first-child{border-left:1px solid #ddd}table.dataTable.cell-border tbody tr:first-child th,table.dataTable.cell-border tbody tr:first-child td{border-top:none}table.dataTable.stripe tbody tr.odd,table.dataTable.display tbody tr.odd{background-color:#f9f9f9}table.dataTable.stripe tbody tr.odd.selected,table.dataTable.display tbody tr.odd.selected{background-color:#abb9d3}table.dataTable.hover tbody tr:hover,table.dataTable.display tbody tr:hover{background-color:#f5f5f5}table.dataTable.hover tbody tr:hover.selected,table.dataTable.display tbody tr:hover.selected{background-color:#a9b7d1}table.dataTable.order-column tbody tr>.sorting_1,table.dataTable.order-column tbody tr>.sorting_2,table.dataTable.order-column tbody tr>.sorting_3,table.dataTable.display tbody tr>.sorting_1,table.dataTable.display tbody tr>.sorting_2,table.dataTable.display tbody tr>.sorting_3{background-color:#f9f9f9}table.dataTable.order-column tbody tr.selected>.sorting_1,table.dataTable.order-column tbody tr.selected>.sorting_2,table.dataTable.order-column tbody tr.selected>.sorting_3,table.dataTable.display tbody tr.selected>.sorting_1,table.dataTable.display tbody tr.selected>.sorting_2,table.dataTable.display tbody tr.selected>.sorting_3{background-color:#acbad4}table.dataTable.display tbody tr.odd>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}table.dataTable.display tbody tr.odd>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}table.dataTable.display tbody tr.odd>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}table.dataTable.display tbody tr.odd.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}table.dataTable.display tbody tr.odd.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}table.dataTable.display tbody tr.odd.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}table.dataTable.display tbody tr.even>.sorting_1,table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}table.dataTable.display tbody tr.even>.sorting_2,table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}table.dataTable.display tbody tr.even>.sorting_3,table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}table.dataTable.display tbody tr.even.selected>.sorting_1,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}table.dataTable.display tbody tr.even.selected>.sorting_2,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}table.dataTable.display tbody tr.even.selected>.sorting_3,table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}table.dataTable.display tbody tr:hover>.sorting_1,table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}table.dataTable.display tbody tr:hover>.sorting_2,table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}table.dataTable.display tbody tr:hover>.sorting_3,table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}table.dataTable.display tbody tr:hover.selected>.sorting_1,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}table.dataTable.display tbody tr:hover.selected>.sorting_2,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}table.dataTable.display tbody tr:hover.selected>.sorting_3,table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}table.dataTable.no-footer{border-bottom:1px solid #111}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}table.dataTable.compact thead th,table.dataTable.compact thead td{padding:4px 17px 4px 4px}table.dataTable.compact tfoot th,table.dataTable.compact tfoot td{padding:4px}table.dataTable.compact tbody th,table.dataTable.compact tbody td{padding:4px}table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-center,table.dataTable td.dt-center,table.dataTable td.dataTables_empty{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}table.dataTable,table.dataTable th,table.dataTable td{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.dataTables_wrapper{position:relative;clear:both;*zoom:1;zoom:1}.dataTables_wrapper .dataTables_length{float:left}.dataTables_wrapper .dataTables_filter{float:right;text-align:right}.dataTables_wrapper .dataTables_filter input{margin-left:0.5em}.dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:0.755em}.dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:0.25em}.dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#333 !important;border:1px solid transparent}.dataTables_wrapper .dataTables_paginate .paginate_button.current,.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333 !important;border:1px solid #cacaca;background-color:#fff;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #fff), color-stop(100%, #dcdcdc));background:-webkit-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-moz-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-ms-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:-o-linear-gradient(top, #fff 0%, #dcdcdc 100%);background:linear-gradient(to bottom, #fff 0%, #dcdcdc 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover,.dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active{cursor:default;color:#666 !important;border:1px solid transparent;background:transparent;box-shadow:none}.dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:white !important;border:1px solid #111;background-color:#585858;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #585858), color-stop(100%, #111));background:-webkit-linear-gradient(top, #585858 0%, #111 100%);background:-moz-linear-gradient(top, #585858 0%, #111 100%);background:-ms-linear-gradient(top, #585858 0%, #111 100%);background:-o-linear-gradient(top, #585858 0%, #111 100%);background:linear-gradient(to bottom, #585858 0%, #111 100%)}.dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:none;background-color:#2b2b2b;background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #2b2b2b), color-stop(100%, #0c0c0c));background:-webkit-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-moz-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-ms-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:-o-linear-gradient(top, #2b2b2b 0%, #0c0c0c 100%);background:linear-gradient(to bottom, #2b2b2b 0%, #0c0c0c 100%);box-shadow:inset 0 0 3px #111}.dataTables_wrapper .dataTables_paginate .ellipsis{padding:0 1em}.dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background-color:white;background:-webkit-gradient(linear, left top, right top, color-stop(0%, rgba(255,255,255,0)), color-stop(25%, rgba(255,255,255,0.9)), color-stop(75%, rgba(255,255,255,0.9)), color-stop(100%, rgba(255,255,255,0)));background:-webkit-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:-o-linear-gradient(left, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%);background:linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.9) 25%, rgba(255,255,255,0.9) 75%, rgba(255,255,255,0) 100%)}.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter,.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_processing,.dataTables_wrapper .dataTables_paginate{color:#333}.dataTables_wrapper .dataTables_scroll{clear:both}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{*margin-top:-1px;-webkit-overflow-scrolling:touch}.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing,.dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing{height:0;overflow:hidden;margin:0 !important;padding:0 !important}.dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.dataTables_wrapper.no-footer div.dataTables_scrollHead table,.dataTables_wrapper.no-footer div.dataTables_scrollBody table{border-bottom:none}.dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width: 767px){.dataTables_wrapper .dataTables_info,.dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.dataTables_wrapper .dataTables_paginate{margin-top:0.5em}}@media screen and (max-width: 640px){.dataTables_wrapper .dataTables_length,.dataTables_wrapper .dataTables_filter{float:none;text-align:center}.dataTables_wrapper .dataTables_filter{margin-top:0.5em}} + +.pmui-pmlabelfield .pmui-textlabel { + background: #aaaaaa; +} + +/* +.pmui-gridpanel { + padding: 10px 20px; +}*/ +.pmui-gridpanel-pager .list-item-ajax a { + position: relative; + float: left; + padding: 6px 12px; + line-height: 1.42857143; + text-decoration: none; + color: #428bca; + background-color: #fff; + border: 1px solid #ddd; + margin: 0 0 0 -1px; + min-width: inherit; + font-size: 14px; + border-radius: 2px; +} + +.pmui-gridpanel-pager .list-item-ajax { + margin: 0px; +} + +.pmui-gridpanel-gotoPage { + padding: 6px 14px 6px 14px; + margin: 0px; + background-color: #f7f7f7; + text-align: left; + color: #555; + border-radius: 2px; +} + +.pmui-gridpanel-pager .list-item-ajax a:hover { + color: #2a6496; + background-color: #eee; + border-color: #ddd; +} + +/*@import "base"; + +.pmui-pmform { + margin-left: 20px; + margin-right: 20px; +} + + +.pmui-background { + background-color: $PMUI-FORM-BACKGROUND; +} + +.pmui-window-footer { + padding-left: 20px; + padding-right: 20px; +} + +.pmui-window-footer > button-solid { + margin-left: 5px; + margin-right: 5px; + margin-bottom: 5px; + +} + +div.pmui-window-footer > a.button-solid { + margin-left: 7px; + margin-top: 5px; + margin-bottom: 5px; + background: $MAFE-FORM-BUTTONS-BACKGROUND; + padding: 6px 15px; +} + +div.pmui-form-footer > a.button-solid { + margin-left: 7px; + margin-top: 5px; + margin-bottom: 5px; + background: $MAFE-FORM-BUTTONS-BACKGROUND; + padding: 6px 15px; +} + +.pmui-buttonpanel { + padding-right: 10px; + padding-left: 10px; + text-align: right; +}*/ + +body { + font-family: 'SourceSansProRegular', Arial, Tahoma, Verdana; + background: #fff; + margin: 0; + padding: 0; +} + +/*IE9*/ +/**::selection*/ +/*.content_control::selection +{ + background-color:transparent; +} +.content_control::-moz-selection +{ + background-color:transparent; +}*/ +* { + /*You just need this if you are only concerned with android and not desktop browsers.*/ + -webkit-tap-highlight-color: transparent; +} + +/* BPMN */ +#p-center-layout { + -webkit-user-select: none; + -moz-user-select: -moz-none; + user-select: none; +} + +/** +* Canvas +*/ +.pmui-pmcanvas { + background-image: url(../img/bg_designer.gif); +} + +/** +* ToolbarPanel +*/ +.mafe-toolbarpanel-btn { + text-decoration: none; + list-style: none; + text-align: center; +} + +.mafe-toolbarpanel-btn-span { + font-size: 10px; +} + +.mafe-toolbarpanel-btn-img { + width: 30px; + height: 30px; +} + +.mafe-toolbarpanel-tooltip { + font-size: 10px; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + -moz-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; + background-color: #6D87B7; + color: white; +} + +.mafe-email { + background: url(../img/email.png) no-repeat; +} + +/* +* For buttons that are on the north from the Layout +*/ +.ui-layout-north a { + margin-left: 2px; +} + +/** + * Shapes + */ +.mafe-shape-sprite { + background: url("../img/mafe_sprite.png") no-repeat; +} + +[class^="mafe-activity-task-"], +[class*=" mafe-activity-task-"], +[class^="mafe-event-"], +[class*=" mafe-event-"], +[class^="mafe-gateway-"], +[class*=" mafe-gateway-"], +[class^="PM-decorator_"], +[class*=" PM-decorator_"], +[class^="mafe-usertask-marker-"], +[class*=" mafe-usertask-marker-"], +[class^="mafe-sendtask-marker-"], +[class*=" mafe-sendtask-marker-"], +[class^="mafe-receivetask-marker-"], +[class*=" mafe-receivetask-marker-"], +[class^="mafe-usertask-marker-"], +[class*=" mafe-usertask-marker-"], +[class^="mafe-servicetask-marker-"], +[class*=" mafe-servicetask-marker-"], +[class^="mafe-scripttask-marker-"], +[class*=" mafe-scripttask-marker-"], +[class^="mafe-manualtask-marker-"], +[class*=" mafe-manualtask-marker-"], +[class^="mafe-businessrule-marker-"], +[class*=" mafe-businessrule-marker-"], +[class^="mafe-collapsed-marker-"], +[class*="mafe-parallel-marker-"], +[class*="mafe-sequential-marker-"], +[class*="mafe-loop-marker-"], +[class*="mafe-style-error-marker-"], +[class^="mafe-data"], +[class*=" mafe-data"], +[class^="mafe-message"], +[class*=" mafe-message"], +[class^="mafe-sequence"], +[class*=" mafe-sequence"], +[class^="mafe-association"], +[class*=" mafe-association"], +[class^="mafe-default"], +[class*=" mafe-default"] { + background-image: url("../img/mafe_sprite.png"); + background-repeat: no-repeat; + background-position: -565px -510px; +} + +.mafe-activity-task-red { + background-color: #BD0A17; + border: 1px solid #72020C; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-green { + background-color: #1B7909; + border: 1px solid #0F5502; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-orange { + background-color: #C57701; + border: 1px solid #965B02; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-activity-task-silver { + background-color: #AAA8A6; + border: 1px solid #6F6D6C; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); +} + +.mafe-artifact-group { + border: 1px dashed #995E06; +} + +.mafe-artifact-annotation { + /*background-color: #fbf1ce;*/ + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 3px; +} + +.mafe-artifact-annotation-close { + float: right; + background: url("../img/delete.png") no-repeat center; + width: 10px; + height: 10px; + cursor: pointer; +} + +.mafe-layer-line-vertical { + visibility: visible; + background-color: transparent; + border-left-width: 1px; + border-left-style: solid; + border-left-color: red; + border-top-width: 0px; + border-top-style: solid; + border-top-color: red; + overflow: hidden; +} + +.mafe-layer-line-horizontal { + background-color: transparent; + border-left-width: 0px; + border-left-style: solid; + border-left-color: red; + border-top-width: 1px; + border-top-style: solid; + border-top-color: red; + overflow: hidden; +} + +.mafe-participant { + background-color: white; + border: 2px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 6px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; +} + +.mafe-pool { + border: 2px solid #3b4753; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + -ms-border-radius: 3px; + -o-border-radius: 3px; + border-radius: 6px; + /*-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);*/ + box-sizing: border-box; + background-color: white; +} + +/*mafe sprite*/ +.mafe-association_100_target_bottom { + background-position: 0 -9162px; +} + +.mafe-association_100_target_left { + background-position: 0 -9184px; +} + +.mafe-association_100_target_right { + background-position: 0 -9251px; +} + +.mafe-association_100_target_top { + background-position: 0 -9173px; +} + +.mafe-association_125_target_bottom { + background-position: 0 -9048px; +} + +.mafe-association_125_target_left { + background-position: 0 -9136px; +} + +.mafe-association_125_target_right { + background-position: 0 -9149px; +} + +.mafe-association_125_target_top { + background-position: 0 -9093px; +} + +.mafe-association_150_target_bottom { + background-position: 0 -8993px; +} + +.mafe-association_150_target_left { + background-position: 0 -11416px; +} + +.mafe-association_150_target_right { + background-position: 0 -9106px; +} + +.mafe-association_150_target_top { + background-position: 0 -9018px; +} + +.mafe-association_50_target_bottom { + background-position: 0 -9791px; +} + +.mafe-association_50_target_left { + background-position: 0 -9797px; +} + +.mafe-association_50_target_right { + background-position: 0 -9893px; +} + +.mafe-association_50_target_top { + background-position: 0 -9824px; +} + +.mafe-association_75_target_bottom { + background-position: 0 -9506px; +} + +.mafe-association_75_target_left { + background-position: 0 -9525px; +} + +.mafe-association_75_target_right { + background-position: 0 -9569px; +} + +.mafe-association_75_target_top { + background-position: 0 -9533px; +} + +.mafe-businessrule-marker-10 { + background-position: 0 -11431px; +} + +.mafe-businessrule-marker-15 { + background-position: 0 -11360px; +} + +.mafe-businessrule-marker-21 { + background-position: 0 -11225px; +} + +.mafe-businessrule-marker-26 { + background-position: 0 -11334px; +} + +.mafe-businessrule-marker-31 { + background-position: 0 -11441px; +} + +.mafe-collapsed-marker-10 { + background-position: 0 -9008px; +} + +.mafe-collapsed-marker-15 { + background-position: 0 -8518px; +} + +.mafe-collapsed-marker-21 { + background-position: 0 -8357px; +} + +.mafe-collapsed-marker-26 { + background-position: 0 -8378px; +} + +.mafe-collapsed-marker-31 { + background-position: 0 -8947px; +} + +.mafe-datainput-marker-10 { + background-position: 0 -9322px; +} + +.mafe-datainput-marker-15 { + background-position: 0 -8978px; +} + +.mafe-datainput-marker-21 { + background-position: 0 -8616px; +} + +.mafe-datainput-marker-26 { + background-position: 0 -8548px; +} + +.mafe-datainput-marker-31 { + background-position: 0 -11179px; +} + +.mafe-dataobject-100 { + background-position: 0 -8010px; +} + +.mafe-dataobject-125 { + background-position: 0 -7886px; +} + +.mafe-dataobject-150 { + background-position: 0 -11000px; +} + +.mafe-dataobject-50 { + background-position: 0 -8650px; +} + +.mafe-dataobject-75 { + background-position: 0 -8242px; +} + +.mafe-dataoutput-marker-10 { + background-position: 0 -9433px; +} + +.mafe-dataoutput-marker-15 { + background-position: 0 -9033px; +} + +.mafe-dataoutput-marker-21 { + background-position: 0 -8906px; +} + +.mafe-dataoutput-marker-26 { + background-position: 0 -8870px; +} + +.mafe-dataoutput-marker-31 { + background-position: 0 -11385px; +} + +.mafe-datastore-20 { + background-position: 0 -7643px; +} + +.mafe-datastore-30 { + background-position: 0 -5709px; +} + +.mafe-datastore-41 { + background-position: 0 -3780px; +} + +.mafe-datastore-51 { + background-position: 0 -1972px; +} + +.mafe-datastore-61 { + background-position: 0 -4076px; +} + +.mafe-default_100_source_bottom { + background-position: 0 -9577px; +} + +.mafe-default_100_source_left { + background-position: 0 -9605px; +} + +.mafe-default_100_source_right { + background-position: 0 -9588px; +} + +.mafe-default_100_source_top { + background-position: 0 -9558px; +} + +.mafe-default_125_source_bottom { + background-position: 0 -9443px; +} + +.mafe-default_125_source_left { + background-position: 0 -9480px; +} + +.mafe-default_125_source_right { + background-position: 0 -9493px; +} + +.mafe-default_125_source_top { + background-position: 0 -9456px; +} + +.mafe-default_150_source_bottom { + background-position: 0 -9262px; +} + +.mafe-default_150_source_left { + background-position: 0 -9061px; +} + +.mafe-default_150_source_right { + background-position: 0 -9077px; +} + +.mafe-default_150_source_top { + background-position: 0 -9347px; +} + +.mafe-default_50_source_bottom { + background-position: 0 -9984px; +} + +.mafe-default_50_source_left { + background-position: 0 -9974px; +} + +.mafe-default_50_source_right { + background-position: 0 -9963px; +} + +.mafe-default_50_source_top { + background-position: 0 -9979px; +} + +.mafe-default_75_source_bottom { + background-position: 0 -9877px; +} + +.mafe-default_75_source_left { + background-position: 0 -9922px; +} + +.mafe-default_75_source_right { + background-position: 0 -9899px; +} + +.mafe-default_75_source_top { + background-position: 0 -9885px; +} + +.mafe-event-boundary-compensationthrow-16 { + background-position: 0 -7394px; +} + +.mafe-event-boundary-compensationthrow-24 { + background-position: 0 -5883px; +} + +.mafe-event-boundary-compensationthrow-33 { + background-position: 0 -3335px; +} + +.mafe-event-boundary-compensationthrow-41 { + background-position: 0 -1080px; +} + +.mafe-event-boundary-compensationthrow-49 { + background-position: 0 -198px; +} + +.mafe-event-boundary-conditional-16 { + background-position: 0 -8083px; +} + +.mafe-event-boundary-conditional-24 { + background-position: 0 -6889px; +} + +.mafe-event-boundary-conditional-33 { + background-position: 0 -5277px; +} + +.mafe-event-boundary-conditional-41 { + background-position: 0 -4137px; +} + +.mafe-event-boundary-conditional-49 { + background-position: 0 -3401px; +} + +.mafe-event-boundary-empty-16 { + background-position: 0 -7963px; +} + +.mafe-event-boundary-empty-24 { + background-position: 0 -6680px; +} + +.mafe-event-boundary-empty-33 { + background-position: 0 -4610px; +} + +.mafe-event-boundary-empty-41 { + background-position: 0 -2426px; +} + +.mafe-event-boundary-empty-49 { + background-position: 0 -1031px; +} + +.mafe-event-boundary-errorcatch-1 { + background-position: 0 -11375px; +} + +.mafe-event-boundary-errorcatch-16 { + background-position: 0 -10867px; +} + +.mafe-event-boundary-errorcatch-2 { + background-position: 0 -11061px; +} + +.mafe-event-boundary-errorcatch-24 { + background-position: 0 -10426px; +} + +.mafe-event-boundary-errorcatch-3 { + background-position: 0 -10664px; +} + +.mafe-event-boundary-errorcatch-33 { + background-position: 0 -9203px; +} + +.mafe-event-boundary-errorcatch-4 { + background-position: 0 -10328px; +} + +.mafe-event-boundary-errorcatch-41 { + background-position: 0 -7458px; +} + +.mafe-event-boundary-errorcatch-49 { + background-position: 0 -5931px; +} + +.mafe-event-boundary-errorcatch-5 { + background-position: 0 -10798px; +} + +.mafe-event-boundary-linkcatch-16 { + background-position: 0 -7555px; +} + +.mafe-event-boundary-linkcatch-24 { + background-position: 0 -5980px; +} + +.mafe-event-boundary-linkcatch-33 { + background-position: 0 -3673px; +} + +.mafe-event-boundary-linkcatch-41 { + background-position: 0 -1387px; +} + +.mafe-event-boundary-linkcatch-49 { + background-position: 0 -357px; +} + +.mafe-event-boundary-linkthrow-16 { + background-position: 0 -7499px; +} + +.mafe-event-boundary-linkthrow-24 { + background-position: 0 -6028px; +} + +.mafe-event-boundary-linkthrow-33 { + background-position: 0 -3887px; +} + +.mafe-event-boundary-linkthrow-41 { + background-position: 0 -1651px; +} + +.mafe-event-boundary-linkthrow-49 { + background-position: 0 -702px; +} + +.mafe-event-boundary-messagecatch-16 { + background-position: 0 -7742px; +} + +.mafe-event-boundary-messagecatch-24 { + background-position: 0 -6165px; +} + +.mafe-event-boundary-messagecatch-33 { + background-position: 0 -3994px; +} + +.mafe-event-boundary-messagecatch-41 { + background-position: 0 -2072px; +} + +.mafe-event-boundary-messagecatch-49 { + background-position: 0 -849px; +} + +.mafe-event-boundary-messagecatch-enabled-16 { + background-position: 0 -11246px; +} + +.mafe-event-boundary-messagecatch-enabled-24 { + background-position: 0 -10819px; +} + +.mafe-event-boundary-messagecatch-enabled-33 { + background-position: 0 -10565px; +} + +.mafe-event-boundary-messagecatch-enabled-41 { + background-position: 0 -10235px; +} + +.mafe-event-boundary-messagecatch-enabled-49 { + background-position: 0 -9616px; +} + +.mafe-event-boundary-messagethrow-16 { + background-position: 0 -11318px; +} + +.mafe-event-boundary-messagethrow-24 { + background-position: 0 -10940px; +} + +.mafe-event-boundary-messagethrow-33 { + background-position: 0 -10631px; +} + +.mafe-event-boundary-messagethrow-41 { + background-position: 0 -10359px; +} + +.mafe-event-boundary-messagethrow-49 { + background-position: 0 -10145px; +} + +.mafe-event-boundary-multiplecatch-16 { + background-position: 0 -7426px; +} + +.mafe-event-boundary-multiplecatch-24 { + background-position: 0 -5835px; +} + +.mafe-event-boundary-multiplecatch-33 { + background-position: 0 -3014px; +} + +.mafe-event-boundary-multiplecatch-41 { + background-position: 0 -949px; +} + +.mafe-event-boundary-multiplecatch-49 { + background-position: 0 0; +} + +.mafe-event-boundary-multiplethrow-16 { + background-position: 0 -7258px; +} + +.mafe-event-boundary-multiplethrow-24 { + background-position: 0 -5739px; +} + +.mafe-event-boundary-multiplethrow-33 { + background-position: 0 -3269px; +} + +.mafe-event-boundary-multiplethrow-41 { + background-position: 0 -1305px; +} + +.mafe-event-boundary-multiplethrow-49 { + background-position: 0 -604px; +} + +.mafe-event-boundary-parallelcatch-16 { + background-position: 0 -7338px; +} + +.mafe-event-boundary-parallelcatch-24 { + background-position: 0 -5787px; +} + +.mafe-event-boundary-parallelcatch-33 { + background-position: 0 -3047px; +} + +.mafe-event-boundary-parallelcatch-41 { + background-position: 0 -1223px; +} + +.mafe-event-boundary-parallelcatch-49 { + background-position: 0 -455px; +} + +.mafe-event-boundary-signalcatch-16 { + background-position: 0 -7587px; +} + +.mafe-event-boundary-signalcatch-24 { + background-position: 0 -6100px; +} + +.mafe-event-boundary-signalcatch-33 { + background-position: 0 -3821px; +} + +.mafe-event-boundary-signalcatch-41 { + background-position: 0 -1428px; +} + +.mafe-event-boundary-signalcatch-49 { + background-position: 0 -98px; +} + +.mafe-event-boundary-signalthrow-16 { + background-position: 0 -7603px; +} + +.mafe-event-boundary-signalthrow-24 { + background-position: 0 -6076px; +} + +.mafe-event-boundary-signalthrow-33 { + background-position: 0 -3854px; +} + +.mafe-event-boundary-signalthrow-41 { + background-position: 0 -1559px; +} + +.mafe-event-boundary-signalthrow-49 { + background-position: 0 -800px; +} + +.mafe-event-boundary-timer-16 { + background-position: 0 -7854px; +} + +.mafe-event-boundary-timer-24 { + background-position: 0 -6369px; +} + +.mafe-event-boundary-timer-33 { + background-position: 0 -4372px; +} + +.mafe-event-boundary-timer-41 { + background-position: 0 -2344px; +} + +.mafe-event-boundary-timer-49 { + background-position: 0 -1733px; +} + +.mafe-event-end-cancelthrow-16 { + background-position: 0 -7726px; +} + +.mafe-event-end-cancelthrow-24 { + background-position: 0 -6503px; +} + +.mafe-event-end-cancelthrow-33 { + background-position: 0 -4528px; +} + +.mafe-event-end-cancelthrow-41 { + background-position: 0 -2508px; +} + +.mafe-event-end-cancelthrow-49 { + background-position: 0 -1872px; +} + +.mafe-event-end-compensationthrow-16 { + background-position: 0 -7758px; +} + +.mafe-event-end-compensationthrow-24 { + background-position: 0 -6575px; +} + +.mafe-event-end-compensationthrow-33 { + background-position: 0 -4899px; +} + +.mafe-event-end-compensationthrow-41 { + background-position: 0 -3146px; +} + +.mafe-event-end-compensationthrow-49 { + background-position: 0 -2254px; +} + +.mafe-event-end-email-16 { + background-position: 0 -8288px; +} + +.mafe-event-end-email-24 { + background-position: 0 -7290px; +} + +.mafe-event-end-email-33 { + background-position: 0 -6823px; +} + +.mafe-event-end-email-41 { + background-position: 0 -6230px; +} + +.mafe-event-end-email-49 { + background-position: 0 -5458px; +} + +.mafe-event-end-empty-16 { + background-position: 0 -8481px; +} + +.mafe-event-end-empty-24 { + background-position: 0 -7515px; +} + +.mafe-event-end-empty-33 { + background-position: 0 -6704px; +} + +.mafe-event-end-empty-41 { + background-position: 0 -5589px; +} + +.mafe-event-end-empty-49 { + background-position: 0 -4479px; +} + +.mafe-event-end-errorthrow-16 { + background-position: 0 -8168px; +} + +.mafe-event-end-errorthrow-24 { + background-position: 0 -7186px; +} + +.mafe-event-end-errorthrow-33 { + background-position: 0 -6312px; +} + +.mafe-event-end-errorthrow-41 { + background-position: 0 -5195px; +} + +.mafe-event-end-errorthrow-49 { + background-position: 0 -4561px; +} + +.mafe-event-end-messagethrow-16 { + background-position: 0 -8304px; +} + +.mafe-event-end-messagethrow-24 { + background-position: 0 -7314px; +} + +.mafe-event-end-messagethrow-33 { + background-position: 0 -6856px; +} + +.mafe-event-end-messagethrow-41 { + background-position: 0 -6271px; +} + +.mafe-event-end-messagethrow-49 { + background-position: 0 -5507px; +} + +.mafe-event-end-multiplethrow-16 { + background-position: 0 -7710px; +} + +.mafe-event-end-multiplethrow-24 { + background-position: 0 -6551px; +} + +.mafe-event-end-multiplethrow-33 { + background-position: 0 -4866px; +} + +.mafe-event-end-multiplethrow-41 { + background-position: 0 -3550px; +} + +.mafe-event-end-multiplethrow-49 { + background-position: 0 -2639px; +} + +.mafe-event-end-signalthrow-16 { + background-position: 0 -8272px; +} + +.mafe-event-end-signalthrow-24 { + background-position: 0 -7370px; +} + +.mafe-event-end-signalthrow-33 { + background-position: 0 -6985px; +} + +.mafe-event-end-signalthrow-41 { + background-position: 0 -6441px; +} + +.mafe-event-end-signalthrow-49 { + background-position: 0 -5660px; +} + +.mafe-event-end-terminatethrow-16 { + background-position: 0 -8404px; +} + +.mafe-event-end-terminatethrow-24 { + background-position: 0 -7234px; +} + +.mafe-event-end-terminatethrow-33 { + background-position: 0 -6737px; +} + +.mafe-event-end-terminatethrow-41 { + background-position: 0 -6189px; +} + +.mafe-event-end-terminatethrow-49 { + background-position: 0 -5343px; +} + +.mafe-event-intermediate-compensationthrow-16 { + background-position: 0 -7410px; +} + +.mafe-event-intermediate-compensationthrow-24 { + background-position: 0 -5907px; +} + +.mafe-event-intermediate-compensationthrow-33 { + background-position: 0 -3368px; +} + +.mafe-event-intermediate-compensationthrow-41 { + background-position: 0 -1121px; +} + +.mafe-event-intermediate-compensationthrow-49 { + background-position: 0 -247px; +} + +.mafe-event-intermediate-conditional-16 { + background-position: 0 -8099px; +} + +.mafe-event-intermediate-conditional-24 { + background-position: 0 -6913px; +} + +.mafe-event-intermediate-conditional-33 { + background-position: 0 -5310px; +} + +.mafe-event-intermediate-conditional-41 { + background-position: 0 -4178px; +} + +.mafe-event-intermediate-conditional-49 { + background-position: 0 -3450px; +} + +.mafe-event-intermediate-email-16 { + background-position: 0 -8115px; +} + +.mafe-event-intermediate-email-24 { + background-position: 0 -7018px; +} + +.mafe-event-intermediate-email-33 { + background-position: 0 -5392px; +} + +.mafe-event-intermediate-email-41 { + background-position: 0 -4219px; +} + +.mafe-event-intermediate-email-49 { + background-position: 0 -2867px; +} + +.mafe-event-intermediate-linkcatch-16 { + background-position: 0 -7571px; +} + +.mafe-event-intermediate-linkcatch-24 { + background-position: 0 -6004px; +} + +.mafe-event-intermediate-linkcatch-33 { + background-position: 0 -3706px; +} + +.mafe-event-intermediate-linkcatch-41 { + background-position: 0 -1469px; +} + +.mafe-event-intermediate-linkcatch-49 { + background-position: 0 -406px; +} + +.mafe-event-intermediate-linkthrow-16 { + background-position: 0 -7539px; +} + +.mafe-event-intermediate-linkthrow-24 { + background-position: 0 -6052px; +} + +.mafe-event-intermediate-linkthrow-33 { + background-position: 0 -3920px; +} + +.mafe-event-intermediate-linkthrow-41 { + background-position: 0 -1692px; +} + +.mafe-event-intermediate-linkthrow-49 { + background-position: 0 -751px; +} + +.mafe-event-intermediate-messagecatch-16 { + background-position: 0 -11272px; +} + +.mafe-event-intermediate-messagecatch-24 { + background-position: 0 -10843px; +} + +.mafe-event-intermediate-messagecatch-33 { + background-position: 0 -10598px; +} + +.mafe-event-intermediate-messagecatch-41 { + background-position: 0 -2303px; +} + +.mafe-event-intermediate-messagecatch-419 { + background-position: 0 -10194px; +} + +.mafe-event-intermediate-messagecatch-49 { + background-position: 0 -10070px; +} + +.mafe-event-intermediate-messagethrow-16 { + background-position: 0 -8131px; +} + +.mafe-event-intermediate-messagethrow-24 { + background-position: 0 -7042px; +} + +.mafe-event-intermediate-messagethrow-33 { + background-position: 0 -5425px; +} + +.mafe-event-intermediate-messagethrow-41 { + background-position: 0 -4260px; +} + +.mafe-event-intermediate-messagethrow-49 { + background-position: 0 -2916px; +} + +.mafe-event-intermediate-multiplecatch-16 { + background-position: 0 -7442px; +} + +.mafe-event-intermediate-multiplecatch-24 { + background-position: 0 -5859px; +} + +.mafe-event-intermediate-multiplecatch-33 { + background-position: 0 -3080px; +} + +.mafe-event-intermediate-multiplecatch-41 { + background-position: 0 -990px; +} + +.mafe-event-intermediate-multiplecatch-49 { + background-position: 0 -49px; +} + +.mafe-event-intermediate-multiplethrow-16 { + background-position: 0 -7274px; +} + +.mafe-event-intermediate-multiplethrow-24 { + background-position: 0 -5763px; +} + +.mafe-event-intermediate-multiplethrow-33 { + background-position: 0 -3302px; +} + +.mafe-event-intermediate-multiplethrow-41 { + background-position: 0 -1346px; +} + +.mafe-event-intermediate-multiplethrow-49 { + background-position: 0 -653px; +} + +.mafe-event-intermediate-parallelcatch-16 { + background-position: 0 -7354px; +} + +.mafe-event-intermediate-parallelcatch-24 { + background-position: 0 -5811px; +} + +.mafe-event-intermediate-parallelcatch-33 { + background-position: 0 -3113px; +} + +.mafe-event-intermediate-parallelcatch-41 { + background-position: 0 -1264px; +} + +.mafe-event-intermediate-parallelcatch-49 { + background-position: 0 -504px; +} + +.mafe-event-intermediate-signalcatch-16 { + background-position: 0 -8051px; +} + +.mafe-event-intermediate-signalcatch-24 { + background-position: 0 -6937px; +} + +.mafe-event-intermediate-signalcatch-33 { + background-position: 0 -5162px; +} + +.mafe-event-intermediate-signalcatch-41 { + background-position: 0 -3953px; +} + +.mafe-event-intermediate-signalcatch-49 { + background-position: 0 -2205px; +} + +.mafe-event-intermediate-signalthrow-16 { + background-position: 0 -8067px; +} + +.mafe-event-intermediate-signalthrow-24 { + background-position: 0 -6961px; +} + +.mafe-event-intermediate-signalthrow-33 { + background-position: 0 -5556px; +} + +.mafe-event-intermediate-signalthrow-41 { + background-position: 0 -4301px; +} + +.mafe-event-intermediate-signalthrow-49 { + background-position: 0 -2965px; +} + +.mafe-event-intermediate-timer-16 { + background-position: 0 -7870px; +} + +.mafe-event-intermediate-timer-24 { + background-position: 0 -6393px; +} + +.mafe-event-intermediate-timer-33 { + background-position: 0 -4405px; +} + +.mafe-event-intermediate-timer-41 { + background-position: 0 -2385px; +} + +.mafe-event-intermediate-timer-49 { + background-position: 0 -1782px; +} + +.mafe-event-start-conditional-16 { + background-position: 0 -7838px; +} + +.mafe-event-start-conditional-24 { + background-position: 0 -6527px; +} + +.mafe-event-start-conditional-33 { + background-position: 0 -4737px; +} + +.mafe-event-start-conditional-41 { + background-position: 0 -3739px; +} + +.mafe-event-start-conditional-49 { + background-position: 0 -2818px; +} + +.mafe-event-start-empty-16 { + background-position: 0 -8226px; +} + +.mafe-event-start-empty-24 { + background-position: 0 -7619px; +} + +.mafe-event-start-empty-33 { + background-position: 0 -6623px; +} + +.mafe-event-start-empty-41 { + background-position: 0 -5236px; +} + +.mafe-event-start-empty-49 { + background-position: 0 -4027px; +} + +.mafe-event-start-messagecatch-16 { + background-position: 0 -8184px; +} + +.mafe-event-start-messagecatch-24 { + background-position: 0 -7210px; +} + +.mafe-event-start-messagecatch-33 { + background-position: 0 -6770px; +} + +.mafe-event-start-messagecatch-41 { + background-position: 0 -6124px; +} + +.mafe-event-start-messagecatch-49 { + background-position: 0 -5023px; +} + +.mafe-event-start-multiplecatch-16 { + background-position: 0 -7774px; +} + +.mafe-event-start-multiplecatch-24 { + background-position: 0 -6656px; +} + +.mafe-event-start-multiplecatch-33 { + background-position: 0 -4833px; +} + +.mafe-event-start-multiplecatch-41 { + background-position: 0 -2777px; +} + +.mafe-event-start-multiplecatch-49 { + background-position: 0 -2023px; +} + +.mafe-event-start-parallelcatch-16 { + background-position: 0 -7694px; +} + +.mafe-event-start-parallelcatch-24 { + background-position: 0 -6599px; +} + +.mafe-event-start-parallelcatch-33 { + background-position: 0 -4770px; +} + +.mafe-event-start-parallelcatch-41 { + background-position: 0 -3591px; +} + +.mafe-event-start-parallelcatch-49 { + background-position: 0 -2549px; +} + +.mafe-event-start-signalcatch-16 { + background-position: 0 -7806px; +} + +.mafe-event-start-signalcatch-24 { + background-position: 0 -6417px; +} + +.mafe-event-start-signalcatch-33 { + background-position: 0 -4643px; +} + +.mafe-event-start-signalcatch-41 { + background-position: 0 -3187px; +} + +.mafe-event-start-signalcatch-48 { + background-position: 0 -2688px; +} + +.mafe-event-start-signalcatch-49 { + background-position: 0 -7822px; +} + +.mafe-event-start-timer-16 { + background-position: 0 -7790px; +} + +.mafe-event-start-timer-24 { + background-position: 0 -6345px; +} + +.mafe-event-start-timer-33 { + background-position: 0 -10471px; +} + +.mafe-event-start-timer-41 { + background-position: 0 -2467px; +} + +.mafe-event-start-timer-49 { + background-position: 0 -1510px; +} + +.mafe-gateway-complex-20 { + background-position: 0 -7126px; +} + +.mafe-gateway-complex-30 { + background-position: 0 -5132px; +} + +.mafe-gateway-complex-41 { + background-position: 0 -3632px; +} + +.mafe-gateway-complex-51 { + background-position: 0 -2113px; +} + +.mafe-gateway-complex-61 { + background-position: 0 -4962px; +} + +.mafe-gateway-eventbased-20 { + background-position: 0 -7086px; +} + +.mafe-gateway-eventbased-30 { + background-position: 0 -4803px; +} + +.mafe-gateway-eventbased-41 { + background-position: 0 -2164px; +} + +.mafe-gateway-eventbased-51 { + background-position: 0 -553px; +} + +.mafe-gateway-eventbased-61 { + background-position: 0 -296px; +} + +.mafe-gateway-exclusive-20 { + background-position: 0 -7166px; +} + +.mafe-gateway-exclusive-30 { + background-position: 0 -5102px; +} + +.mafe-gateway-exclusive-41 { + background-position: 0 -3228px; +} + +.mafe-gateway-exclusive-51 { + background-position: 0 -1921px; +} + +.mafe-gateway-exclusive-61 { + background-position: 0 -10009px; +} + +.mafe-gateway-exclusiveeventbased-20 { + background-position: 0 -7106px; +} + +.mafe-gateway-exclusiveeventbased-30 { + background-position: 0 -4932px; +} + +.mafe-gateway-exclusiveeventbased-41 { + background-position: 0 -2598px; +} + +.mafe-gateway-exclusiveeventbased-51 { + background-position: 0 -898px; +} + +.mafe-gateway-exclusiveeventbased-61 { + background-position: 0 -1162px; +} + +.mafe-gateway-inclusive-20 { + background-position: 0 -7066px; +} + +.mafe-gateway-inclusive-30 { + background-position: 0 -5072px; +} + +.mafe-gateway-inclusive-41 { + background-position: 0 -2736px; +} + +.mafe-gateway-inclusive-51 { + background-position: 0 -1600px; +} + +.mafe-gateway-inclusive-61 { + background-position: 0 -8420px; +} + +.mafe-gateway-parallel-20 { + background-position: 0 -7146px; +} + +.mafe-gateway-parallel-30 { + background-position: 0 -5630px; +} + +.mafe-gateway-parallel-41 { + background-position: 0 -4438px; +} + +.mafe-gateway-parallel-51 { + background-position: 0 -3499px; +} + +.mafe-gateway-parallel-61 { + background-position: 0 -10504px; +} + +.mafe-gateway-paralleleventbased-20 { + background-position: 0 -6803px; +} + +.mafe-gateway-paralleleventbased-30 { + background-position: 0 -4342px; +} + +.mafe-gateway-paralleleventbased-41 { + background-position: 0 -1831px; +} + +.mafe-gateway-paralleleventbased-51 { + background-position: 0 -147px; +} + +.mafe-gateway-paralleleventbased-61 { + background-position: 0 -4676px; +} + +.mafe-loop-marker-10 { + background-position: 0 -8937px; +} + +.mafe-loop-marker-15 { + background-position: 0 -8588px; +} + +.mafe-loop-marker-21 { + background-position: 0 -8497px; +} + +.mafe-loop-marker-26 { + background-position: 0 -8200px; +} + +.mafe-loop-marker-31 { + background-position: 0 -7979px; +} + +.mafe-manualtask-marker-10 { + background-position: 0 -11288px; +} + +.mafe-manualtask-marker-15 { + background-position: 0 -10964px; +} + +.mafe-manualtask-marker-21 { + background-position: 0 -10777px; +} + +.mafe-manualtask-marker-26 { + background-position: 0 -10690px; +} + +.mafe-manualtask-marker-31 { + background-position: 0 -10716px; +} + +.mafe-message_100_source_bottom, +.mafe-message_100_source_top, +.mafe-message_100_source_left, +.mafe-message_100_source_right { + background-position: 0 -8859px; +} + +.mafe-message_100_target_bottom { + background-position: 0 -8806px; +} + +.mafe-message_100_target_left { + background-position: 0 -8795px; +} + +.mafe-message_100_target_right { + background-position: 0 -8784px; +} + +.mafe-message_100_target_top { + background-position: 0 -8817px; +} + +.mafe-message_125_source_bottom, +.mafe-message_125_source_top, +.mafe-message_125_source_left, +.mafe-message_125_source_right { + background-position: 0 -8726px; +} + +.mafe-message_125_target_bottom { + background-position: 0 -8637px; +} + +.mafe-message_125_target_left { + background-position: 0 -8685px; +} + +.mafe-message_125_target_right { + background-position: 0 -8698px; +} + +.mafe-message_125_target_top { + background-position: 0 -8603px; +} + +.mafe-message_150_source_bottom, +.mafe-message_150_source_top, +.mafe-message_150_source_left, +.mafe-message_150_source_right { + background-position: 0 -8739px; +} + +.mafe-message_150_target_bottom { + background-position: 0 -8769px; +} + +.mafe-message_150_target_left { + background-position: 0 -8754px; +} + +.mafe-message_150_target_right { + background-position: 0 -8711px; +} + +.mafe-message_150_target_top { + background-position: 0 -8670px; +} + +.mafe-message_50_source_bottom, +.mafe-message_50_source_top, +.mafe-message_50_source_left, +.mafe-message_50_source_right { + background-position: 0 -9725px; +} + +.mafe-message_50_target_bottom { + background-position: 0 -9599px; +} + +.mafe-message_50_target_left { + background-position: 0 -9402px; +} + +.mafe-message_50_target_right { + background-position: 0 -9408px; +} + +.mafe-message_50_target_top { + background-position: 0 -9541px; +} + +.mafe-message_75_source_bottom, +.mafe-message_75_source_top, +.mafe-message_75_source_left, +.mafe-message_75_source_right { + background-position: 0 -9414px; +} + +.mafe-message_75_target_bottom { + background-position: 0 -9278px; +} + +.mafe-message_75_target_left { + background-position: 0 -9128px; +} + +.mafe-message_75_target_right { + background-position: 0 -9195px; +} + +.mafe-message_75_target_top { + background-position: 0 -9286px; +} + +.mafe-parallel-marker-10 { + background-position: 0 -9989px; +} + +.mafe-parallel-marker-15 { + background-position: 0 -9907px; +} + +.mafe-parallel-marker-21 { + background-position: 0 -9803px; +} + +.mafe-parallel-marker-26 { + background-position: 0 -9691px; +} + +.mafe-parallel-marker-31 { + background-position: 0 -9846px; +} + +.mafe-receivetask-marker-10 { + background-position: 0 -11298px; +} + +.mafe-receivetask-marker-15 { + background-position: 0 -11133px; +} + +.mafe-receivetask-marker-21 { + background-position: 0 -10979px; +} + +.mafe-receivetask-marker-26 { + background-position: 0 -10914px; +} + +.mafe-receivetask-marker-31 { + background-position: 0 -10883px; +} + +.mafe-scripttask-marker-10 { + background-position: 0 -11262px; +} + +.mafe-scripttask-marker-15 { + background-position: 0 -10762px; +} + +.mafe-scripttask-marker-21 { + background-position: 0 -10450px; +} + +.mafe-scripttask-marker-26 { + background-position: 0 -10400px; +} + +.mafe-scripttask-marker-31 { + background-position: 0 -10297px; +} + +.mafe-sendtask-marker-10 { + background-position: 0 -11308px; +} + +.mafe-sendtask-marker-15 { + background-position: 0 -11210px; +} + +.mafe-sendtask-marker-21 { + background-position: 0 -11148px; +} + +.mafe-sendtask-marker-26 { + background-position: 0 -11076px; +} + +.mafe-sendtask-marker-31 { + background-position: 0 -11102px; +} + +.mafe-sequence_100_target_bottom { + background-position: 0 -9547px; +} + +.mafe-sequence_100_target_left { + background-position: 1px -9469px; +} + +.mafe-sequence_100_target_right { + background-position: -1px -9422px; +} + +.mafe-sequence_100_target_top { + background-position: 0 -9514px; +} + +.mafe-sequence_125_target_bottom { + background-position: 0 -9363px; +} + +.mafe-sequence_125_target_left { + background-position: 1px -9376px; +} + +.mafe-sequence_125_target_right { + background-position: 0 -9294px; +} + +.mafe-sequence_125_target_top { + background-position: 0 -9389px; +} + +.mafe-sequence_150_target_bottom { + background-position: 0 -9307px; +} + +.mafe-sequence_150_target_left { + background-position: 2px -11472px; +} + +.mafe-sequence_150_target_right { + background-position: -1px -9332px; +} + +.mafe-sequence_150_target_top { + background-position: 0 -9235px; +} + +.mafe-sequence_50_target_bottom { + background-position: 0 -9951px; +} + +.mafe-sequence_50_target_left { + background-position: 0 -9957px; +} + +.mafe-sequence_50_target_right { + background-position: 0 -9968px; +} + +.mafe-sequence_50_target_top { + background-position: 0 -9945px; +} + +.mafe-sequence_75_target_bottom { + background-position: 0 -9752px; +} + +.mafe-sequence_75_target_left { + background-position: 0 -9838px; +} + +.mafe-sequence_75_target_right { + background-position: 0 -9830px; +} + +.mafe-sequence_75_target_top { + background-position: 0 -9717px; +} + +.mafe-sequential-marker-10 { + background-position: 0 -9999px; +} + +.mafe-sequential-marker-15 { + background-position: 0 -9930px; +} + +.mafe-sequential-marker-21 { + background-position: 0 -9731px; +} + +.mafe-sequential-marker-26 { + background-position: 0 -9665px; +} + +.mafe-sequential-marker-31 { + background-position: 0 -9760px; +} + +.mafe-servicetask-marker-10 { + background-position: 0 -11169px; +} + +.mafe-servicetask-marker-15 { + background-position: 0 -10747px; +} + +.mafe-servicetask-marker-21 { + background-position: 0 -10276px; +} + +.mafe-servicetask-marker-26 { + background-position: 0 -10119px; +} + +.mafe-servicetask-marker-31 { + background-position: 0 -8828px; +} + +.mafe-usertask-marker-10 { + background-position: 0 -8927px; +} + +.mafe-usertask-marker-15 { + background-position: 0 -8533px; +} + +.mafe-usertask-marker-21 { + background-position: 0 -6482px; +} + +.mafe-usertask-marker-26 { + background-position: 0 -7937px; +} + +.mafe-usertask-marker-31 { + background-position: 0 -7663px; +} + +/*******end sprite***********/ +.mafe-toolbar-sprite { + background-image: url(../img/bpmn_sprite_with_zoom.png); + background-repeat: no-repeat; + width: 16px; + height: 16px; + display: inline-block; +} + +.mafe-toolbar-size { + width: 17px; + height: 17px; + display: block; + margin: 2px 0 2px 2px; +} + +.mafe-toolbar-container { + padding-left: 0; +} + +.mafe-toolbar-rectangle-size { + width: 17px; + height: 13px; + display: block; + margin: 2px 0 2px 2px; +} + +/** +* PMTask Menu +*/ +.mafe-menu-task-steps { + background: url(../img/steps.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-users-action { + background: url(../img/users.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-delete-rules-action { + background: url(../img/delete_rules.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-delete-action { + background: url(../img/delete.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-properties-action { + background: url(../img/dynaforms.gif) no-repeat; + background-size: 20px 20px; +} + +/** +* Tree Menu +*/ +.mafe-menu-tree-disable { + background: url(../img/deactivate.png) no-repeat; +} + +.mafe-menu-tree-enable { + background: url(../img/activate.png) no-repeat; +} + +/** +* Sub process Menu +*/ +.mafe-menu-rules-action { + background: url(../img/rules.png) no-repeat; + background-size: 20px 20px; +} + +/** +* Toolbar Menu +*/ +.mafe-menu-toolbar-blank-dynaform { + background: url(../img/form.gif) no-repeat; + background-size: 20px 20px; +} + +.mafe-menu-toolbar-copyimport-dynaform { + background: url(../img/edit-table.png) no-repeat; + background-size: 20px 20px; +} + +.mafe-label-annotation span { + color: black; +} + +/** +* Input Document +*/ +.mafe-inputDocument-newinput { + background-position: 0 -199px; + margin: 10px 0 10px 20px; +} + +/* BUTTON UID*/ +/*a.mafe-button-uid:link,a.mafe-button-uid:visited{ + display: block; + color: #e77e23; + font-size: 14px; + font-weight: 700; + line-height: 24px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #fdf8e2; + width: 90%; + height: 24px; + margin: 4px auto; + padding: 0 5px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} +a.mafe-button-uid:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} +.mafe-button-uid .pmui-button-label { + color: #e77e23; + font-weight:bold; +}*/ +/* BUTTON NEW*/ +/*a.mafe-button-new:link,a.mafe-button-new:visited{ + float: right; + display: block; + color: #fff; + line-height: 45px; + text-decoration: none; + background: #e77e23 url(../img/ico_mor2.png) no-repeat 5px center; + background-size : 25px; + padding: 6px 38px 6px 33px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + max-width: 80%; + height: auto; +} +a.mafe-button-new:hover{ + background: #e77e23 url(../img/ico_mor2.png) no-repeat 96% center; + background-size : 25px; + padding: 6px 38px 6px 33px; +} +.mafe-button-new .pmui-button-label { + text-transform:capitalize; +}*/ +/* BUTTON EDIT*/ +/*a.mafe-button-edit:link,a.mafe-button-edit:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #19bd9b; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-edit:hover{ + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +}*/ +/* BUTTON DELETE*/ +/*a.mafe-button-delete:link,a.mafe-button-delete:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #e84c3d; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-delete:hover { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +}*/ +/* BUTTON PROPERTIES*/ +/*a.mafe-button-properties:link,a.mafe-button-properties:visited { + display: block; + color: #fff; + font-size: 14px; + line-height: 32px; + text-align: center; + text-decoration: none; + text-transform: uppercase; + background: #3D78E5; + height: 32px; + margin: 0 3px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + filter: alpha(opacity=80); + -moz-opacity: 0.80; + -khtml-opacity: 0.80; + opacity: 0.80; +} +a.mafe-button-properties:hover { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} +a.mafe-button-img-delete { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-delete .pmui-button-icon { + background-image: url(../img/delete.png); + background-repeat: no-repeat; + display: inline-block; + width: 19px; + height: 18px; +} +a.mafe-button-img-delete .pmui-button-label { + display: none; +} +a.mafe-button-img-edit { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-edit .pmui-button-icon { + background-image: url(../img/edit.gif); + background-repeat: no-repeat; + display: inline-block; + width: 23px; + height: 20px; +} +a.mafe-button-img-edit .pmui-button-label { + display: none; +} + +a.mafe-button-img-properties { + background: #ffffff; + padding: 0px; + margin: 0px; +} +a.mafe-button-img-properties .pmui-button-icon { + background-image: url(../img/edit-table.png); + background-repeat: no-repeat; + display: inline-block; + width: 17px; + height: 16px; +} +a.mafe-button-img-properties .pmui-button-label { + display: none; +} + +.mafe-button-text{ + background-color :#FDFDFD; +} +.mafe-button-text .pmui-button-label{ + background-color :#FDFDFD; + color: black; + text-transform:capitalize; +} +*/ +/* ToolbarPanel */ +.mafe-toolbarpanel-btn { + text-decoration: none; + list-style: none; + text-align: center; +} + +.mafe-toolbarpanel-btn-span { + font-size: 10px; +} + +.mafe-toolbarpanel-btn-img { + width: 30px; + height: 30px; +} + +.mafe-toolbarpanel-tooltip { + font-size: 10px; + z-index: 9999; + max-width: 300px; + -webkit-box-shadow: 0 0 5px #aaa; + -moz-box-shadow: 0 0 5px #aaa; + box-shadow: 0 0 5px #aaa; + background-color: #6D87B7; + color: white; +} + +/** + * Styles for arrows + */ +.mafe-decorator_50_target_right { + border-bottom: 3px solid transparent; + border-top: 3px solid transparent; + border-right: 6px solid black; +} + +.mafe-decorator_75_target_right { + border-bottom: 4px solid transparent; + border-top: 4px solid transparent; + border-right: 8px solid black; +} + +.mafe-decorator_100_target_right { + border-bottom: 5px solid transparent; + border-top: 5px solid transparent; + border-right: 10px solid black; +} + +.mafe-decorator_125_target_right { + border-bottom: 6px solid transparent; + border-top: 6px solid transparent; + border-right: 12px solid black; +} + +.mafe-decorator_150_target_right { + border-bottom: 7px solid transparent; + border-top: 7px solid transparent; + border-right: 14px solid black; +} + +.mafe-decorator_50_target_bottom { + border-left: 3px solid transparent; + border-right: 3px solid transparent; + border-bottom: 6px solid black; +} + +.mafe-decorator_75_target_bottom { + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-bottom: 8px solid black; +} + +.mafe-decorator_100_target_bottom { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 10px solid black; +} + +.mafe-decorator_125_target_bottom { + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-bottom: 12px solid black; +} + +.mafe-decorator_150_target_bottom { + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-bottom: 14px solid black; +} + +.mafe-decorator_50_target_left { + border-bottom: 3px solid transparent; + border-top: 3px solid transparent; + border-left: 6px solid black; +} + +.mafe-decorator_75_target_left { + border-bottom: 4px solid transparent; + border-top: 4px solid transparent; + border-left: 8px solid black; +} + +.mafe-decorator_100_target_left { + border-bottom: 5px solid transparent; + border-top: 5px solid transparent; + border-left: 10px solid black; +} + +.mafe-decorator_125_target_left { + border-bottom: 6px solid transparent; + border-top: 6px solid transparent; + border-left: 12px solid black; +} + +.mafe-decorator_150_target_left { + border-bottom: 7px solid transparent; + border-top: 7px solid transparent; + border-left: 14px solid black; +} + +.mafe-decorator_50_target_top { + border-left: 3px solid transparent; + border-right: 3px solid transparent; + border-top: 6px solid black; +} + +.mafe-decorator_75_target_top { + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 8px solid black; +} + +.mafe-decorator_100_target_top { + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-top: 10px solid black; +} + +.mafe-decorator_125_target_top { + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-top: 12px solid black; +} + +.mafe-decorator_150_target_top { + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-top: 14px solid black; +} + +/* ---------------------------- NAV ---------------------------- */ +.navBar { + background: #3397e2; + color: #fff; + height: auto; + left: 0px; + position: fixed; + /*top: 1px;*/ + width: 97%; + z-index: 2; + padding: 0 1% 0 2%; + display: none; + border: 1px solid #2979b8; +} + +.navBar .head { + background-color: #3b4753; + cursor: move; + font-size: 12px; + height: 16px; + overflow: hidden; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; +} + +.navBar nav { + position: relative; + font-size: 11px; + height: 35px; + float: right; + font-weight: 600; +} + +.navBar nav ul { + position: relative; + list-style: none; + height: 35px; + margin: 0; + padding: 0; +} + +.navBar nav ul li { + float: right; + border-right: 1px solid #70b5ec; + border-left: 1px solid #70b5ec; + padding: 2px 5px; +} + +.navBar nav ul li:hover { + background-color: #2979b4; + border-right: 1px solid #2979b8; + border-left: 1px solid #2979b8; +} + +.navBar nav ul li:last-child { + border: 0; +} + +.navBar nav ul li a { + display: inline-block; + color: #fff; + line-height: 31px; + text-align: center; + text-decoration: none; + background-color: transparent; + height: 29px; + padding: 0 10px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + cursor: pointer; +} + +.navBar nav ul li b { + display: inline-block; + color: #fff; + line-height: 31px; + text-align: center; + text-decoration: none; + background-color: transparent; + height: 29px; + padding: 0 10px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; + cursor: pointer; +} + +.navBar nav ul li input { + height: 31px; + width: 58px; + padding: 5px; +} + +.navBar .processName { + width: 55%; + float: left; + /*border: 1px solid red; */ +} + +.navBar .buttonSection { + /*border: 1px solid green; */ + width: 40%; + /* don't want this */ + float: right; +} + +.navBar h2 { + /*float: left;*/ + text-align: left; + font-size: 12px; + font-weight: 700px; + line-height: 35px; + margin: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +a.mafe-button-save:link, a.mafe-button-save:visited { + width: 70px; +} + +.mafe-save-process { + color: white; + background: #19bd9b; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; + border-left: 1px solid lightgray !important; + border-right: 1px solid lightgray !important; + border-bottom: 1px solid lightgray !important; + padding-right: 25px !important; +} + +li.mafe-redo { + margin-top: -2px; +} + +li.mafe-undo { + margin-top: -2px; +} + +a.mafe-button-save:hover { + /*background: #16a085 !important;*/ + color: white; +} + +.mafe-dropdown-zoom { + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + font-size: 12px; +} + +.mafe-dropdown-zoom option { + font-size: 12px; +} + +a.mafe-button-fullscreen:link, a.mafe-button-fullscreen:visited { + float: left; + display: block; + outline: none; + text-indent: -9000px; + text-decoration: none; + background: url(../img/mafe-tools.png) no-repeat; + background-position: 0 -1036px; + width: 11px; + margin: 0 5px 0 5px; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; +} + +a.mafe-button-fullscreen:hover { + -ms-transform: scale(1); + -webkit-transform: scale(1); + -moz-transform: scale(1); + -o-transform: scale(1); + transform: scale(1); +} + +/* ---------------------------- NAV ---------------------------- */ +/* ---------------------------- PANELES ---------------------------- */ +.content { + /*position: relative; + background: url(../img/bg_designer.gif) repeat; + width: 100%; + height: 700px; + overflow: auto;*/ +} + +.bpmn_shapes { + /*right: 20px;*/ + border: 1px solid #d6d7d9; + background-color: #e9e9e9; + /*width: 88px;*/ + padding-top: 5px; + padding-bottom: 5px; + /*overflow: visible;*/ + z-index: 1; + position: fixed; + top: 35px; + left: 0px; + height: 31px; + width: 100%; + display: none; +} + +.bpmn_shapes .head { + background-color: #d5d8dd; + height: 16px; + cursor: move; +} + +.bpmn_shapes .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.bpmn_shapes .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.bpmn_shapes ul:nth-child(2) { + border-top: none; +} + +.bpmn_shapes ul:last-child { + border-bottom: 0; +} + +.bpmn_shapes ul { + position: relative; + overflow: hidden; + list-style: none; + width: 96%; + margin: 0 0%; + padding: 4px 0; + display: inline; +} + +.bpmn_shapes ul li { + display: inline-block; + margin-top: 2px; + margin: 0 4px; + margin-top: 2px; + padding: 0; +} + +.bpmn_shapes ul li a { + float: left; + display: inline-block; + color: #fff; + line-height: 10px; + text-align: center; + text-decoration: none; + padding: 3px 4px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls { + top: 90px; + right: 20px; + font-size: 11px; + border: 1px solid #d8dbdf; + background-color: #3397e2; + width: 200px; + z-index: 1; + position: fixed; + font-weight: 700; + display: none; +} + +.content_controls .head { + background-color: #3b4753; + height: 18px; + cursor: move; +} + +.content_controls .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.content_controls ul { + float: left; + position: relative; + overflow: hidden; + list-style: none; + width: 96%; + margin: 0 2%; + padding: 0; +} + +.content_controls ul li:first-child { + border-top: 0; +} + +.content_controls ul li:last-child { + border-bottom: 0; +} + +.content_controls ul li { + float: left; + display: inline-block; + border-bottom: 1px solid #20669D; + width: 100%; + margin: 0; + padding: 3px 0; +} + +.content_controls ul li:hover { + background-color: #2979b4; +} + +.content_controls ul li a { + float: left; + display: inline-block; + color: #fff; + line-height: 23px; + text-align: center; + text-decoration: none; + padding: 3px 3px; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.content_controls li { + position: relative; +} + +a.btn_create { + float: right; + position: absolute; + right: 0px; + top: 1px; +} + +a.btn_create:link, a.btn_create:visited { + float: right; + display: block; + color: #fff; + line-height: 23px; + text-decoration: none; + background: transparent url(../img/btn_create.png) no-repeat center !important; + width: 20px; + height: 23px; + padding: 3px 0; + filter: alpha(opacity=50); + -moz-opacity: 0.50; + -khtml-opacity: 0.50; + -webkit-transition: all .6s; + -moz-transition: all .6s; + -ms-transition: all .6s; + -o-transition: all .6s; + transition: all .6s; +} + +a.btn_create span { + filter: alpha(opacity=0); + -moz-opacity: 0.00; + -khtml-opacity: 0.00; + opacity: 0.00; +} + +a.btn_create:hover { + background: #20bb99 url(../img/btn_create.png) no-repeat 5px center !important; + width: 45px; + height: 23px; + padding: 3px 0 3px 18px; + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} + +a.btn_create:hover span { + filter: alpha(opacity=100); + -moz-opacity: 1.00; + -khtml-opacity: 1.00; + opacity: 1.00; +} + +.bpmn_shapes_legend { + /*top: 1px;*/ + /*right: 20px;*/ + border: 1px solid #d6d7d9; + background-color: #e9e9e9; + width: 250px; + padding-bottom: 2px; + overflow: visible; + z-index: 1; + position: fixed; + right: 20px; + top: 70px; + display: none; +} + +.bpmn_shapes_legend .head { + background-color: #d5d8dd; + height: 16px; + cursor: move; +} + +.bpmn_shapes_legend .head a { + float: right; + display: block; + width: 30px; + height: 16px; + -webkit-transition: all .4s; + -moz-transition: all .4s; + -ms-transition: all .4s; + -o-transition: all .4s; + transition: all .4s; +} + +.bpmn_shapes_legend .head a:hover { + filter: alpha(opacity=70); + -moz-opacity: 0.70; + -khtml-opacity: 0.70; + opacity: 0.70; +} + +.bpmn_shapes_legend .icon-legend { + height: 20px; + width: 50px; + margin: 5px; + display: inline-block; +} + +.bpmn_shapes_legend .text-legend { + font-size: small; + display: inline-block; + margin-top: 9px; +} + +/* ---------------------------- PANELES ---------------------------- */ +/* ---------------------------- ELEMENTOS BASE ---------------------------- */ +.bold { + font-weight: 700; +} + +.small { + font-size: 12px; +} + +.color2 { + color: #f46500; +} + +/* ---------------------------- ELEMENTOS BASE ---------------------------- */ +.mafe-shapes-toggle { + background-image: url("../img/shapes-toogle.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 16px; + margin-top: 2px; +} + +.mafe-shapes-plus { + background-image: url("../img/plus.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 16px; + margin-top: 2px; +} + +.mafe-shapes-refresh { + background-image: url("../img/shapes-refresh.png"); + background-repeat: no-repeat; + float: right; + cursor: pointer; + width: 16px; + height: 14px; + background-size: 10px; + margin-top: 4px; +} + +.mafe-process-object { + color: white; + margin-top: 3px; + margin-left: 7px; + float: left; +} + +/* + toolbar sprite +*/ +.mafe-sprite, .mafe-fullscream, .mafe-toolbar-annotation, .mafe-toolbar-blackbox, .mafe-toolbar-boundary, .mafe-toolbar-data-object, .mafe-toolbar-data-store, .mafe-toolbar-end-message, .mafe-toolbar-end, .mafe-toolbar-gateway-exclusive, .mafe-toolbar-gateway-inclusive, .mafe-toolbar-gateway-parallel, .mafe-toolbar-group, .mafe-toolbar-horizontal-line, .mafe-toolbar-horizontal-text, .mafe-toolbar-intermediate-receive-mesage, .mafe-toolbar-intermediate-send-mesage, .mafe-toolbar-lane, .mafe-toolbar-participant, .mafe-toolbar-pool, .mafe-toolbar-start-message, .mafe-toolbar-start-timer, .mafe-toolbar-start, .mafe-toolbar-subprocess, .mafe-toolbar-task, .mafe-toolbar-vertical-line, .mafe-toolbar-vertical-text, .mafe-button-redo, .mafe-button-undo, .mafe-button-close, .mafe-toolbar-lasso, .mafe-toolbar-help, .mafe-toolbar-end-email, .mafe-toolbar-intermediate-email, .mafe-toolbar-event-intermediate-timer, .mafe-toolbar-event-start-timer, .mafe-toolbar-validation, .mafe-validator-close, .mafe-icon-error, .mafe-icon-warning { + background: url("../img/mafe-tools.png") no-repeat; + width: 23px; + height: 23px; +} + +.mafe-button-close { + background-position: 0 -966px; +} + +.mafe-button-close:hover, .mafe-button-close.button-close_hover, .mafe-button-close.button-close-hover { + background-position: 0 -1156px; +} + +.mafe-button-redo { + background-position: 0 -888px; +} + +.mafe-button-redo:hover, .mafe-button-redo.button-redo_hover, .mafe-button-redo.button-redo-hover { + background-position: 0 -863px; +} + +.mafe-button-undo { + background-position: 0 -837px; +} + +.mafe-button-undo:hover, .mafe-button-undo.button-undo_hover, .mafe-button-undo.button-undo-hover { + background-position: 0 -913px; +} + +.mafe-fullscream { + background-position: 0 -1036px; +} + +.mafe-icon-error { + background-position: 0 -1256px; +} + +.mafe-icon-warning { + background-position: 0 -1271px; +} + +.mafe-plus { + background-position: 0 -790px; +} + +.mafe-shapes-refresh { + background-position: 0 -952px; +} + +.mafe-shapes-toogle { + background-position: 0 -938px; +} + +.mafe-toolbar-annotation { + background-position: 0 -730px; +} + +.mafe-toolbar-blackbox { + background-position: 0 -530px; +} + +.mafe-toolbar-boundary { + background-position: 0 -120px; +} + +.mafe-toolbar-data-object { + background-position: 0 -1066px; +} + +.mafe-toolbar-data-store { + background-position: 0 -300px; +} + +.mafe-toolbar-easy { + background-position: 0 -450px; +} + +.mafe-toolbar-end-email { + background-position: 0 -390px; +} + +.mafe-toolbar-end-message { + background-position: 0 -150px; +} + +.mafe-toolbar-end { + background-position: 0 -240px; +} + +.mafe-toolbar-event-intermediate-timer { + background-position: 0 -270px; +} + +.mafe-toolbar-event-start-timer { + background-position: 0 -620px; +} + +.mafe-toolbar-gateway-exclusive { + background-position: 0 -420px; +} + +.mafe-toolbar-gateway-inclusive { + background-position: 0 -360px; +} + +.mafe-toolbar-gateway-parallel { + background-position: 0 -470px; +} + +.mafe-toolbar-group { + background-position: 0 -560px; +} + +.mafe-toolbar-help { + background-position: 0 -680px; +} + +.mafe-toolbar-help:hover, .mafe-toolbar-help.toolbar-help_hover, .mafe-toolbar-help.toolbar-help-hover { + background-position: 0 -705px; +} + +.mafe-toolbar-horizontal-line { + background-position: 0 -1196px; +} + +.mafe-toolbar-horizontal-text { + background-position: 0 -807px; +} + +.mafe-toolbar-intermediate-email { + background-position: 0 -210px; +} + +.mafe-toolbar-intermediate-receive-mesage { + background-position: 0 0; +} + +.mafe-toolbar-intermediate-send-mesage { + background-position: 0 -30px; +} + +.mafe-toolbar-lane { + background-position: 0 -500px; +} + +.mafe-toolbar-lasso { + background-position: 0 -330px; +} + +.mafe-toolbar-participant { + background-position: 0 -1096px; +} + +.mafe-toolbar-pool { + background-position: 0 -590px; +} + +.mafe-toolbar-start-message { + background-position: 0 -60px; +} + +.mafe-toolbar-start-timer { + background-position: 0 -650px; +} + +.mafe-toolbar-start { + background-position: 0 -180px; +} + +.mafe-toolbar-subprocess { + background-position: 0 -1006px; +} + +.mafe-toolbar-task { + background-position: 0 -1126px; +} + +.mafe-toolbar-validation { + background-position: 0 -90px; +} + +.mafe-toolbar-vertical-line { + background-position: 0 -1226px; +} + +.mafe-toolbar-vertical-text { + background-position: 0 -760px; +} + +.mafe-validator-close { + background-position: 0 -1176px; +} + +.mafe-validator-close:hover, .mafe-validator-close.validator-close_hover, .mafe-validator-close.validator-close-hover { + background-position: 0 -986px; +} + +/*end toolbar sprite**/ +span.mafe-button-redo { + width: 22px; + height: 24px; + display: block; + margin-top: 4px; +} + +span.mafe-button-undo { + width: 22px; + height: 24px; + display: block; + margin-top: 4px; +} + +span.mafe-button-close { + width: 20px; + height: 20px; + display: block; + margin-top: 7px; +} + +span.mafe-validator-close { + width: 20px; + height: 20px; + display: block; + margin: 4px 8px 4px 4px; +} + +a.mafe-close { + margin: -1px; +} + +span.mafe-toolbar-help { + width: 23px; + height: 23px; + display: block; + margin-top: 2px; +} + +span.mafe-toolbar-validation { + width: 9px; + height: 20px; + display: block; + margin-top: 6px; +} + +/** + * Tooltip for actions + */ +.mafe-action-tooltip { + font-size: 10px; + background-color: #ECF0F1; +} + +/** + * Tooltip Black + */ +.ui-tooltip.mafe-action-tooltip-black { + background: black; + color: white; +} + +/** Rotate Label **/ +.rotateText { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -ms-transform: rotate(-90deg); + /* IE9+ */ + -moz-transform: rotate(-90deg); + /* Firefox */ + -o-transform: rotate(-90deg); + /* Opera */ + -webkit-transform: rotate(-90deg); + /* Safari & Chrome */ + transform: rotate(-90deg); + display: block; + float: center; + margin: 0 10px 0; +} + +.rotateControl { + filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); + -ms-transform: rotate(90deg); + /* IE9+ */ + -moz-transform: rotate(90deg); + /* Firefox */ + -o-transform: rotate(90deg); + /* Opera */ + -webkit-transform: rotate(90deg); + /* Safari & Chrome */ + transform: rotate(90deg); + display: block; + float: right; + margin: 0 10px 0; +} + +.mafe-textarea-resize .pmui-textareacontrol { + resize: vertical; +} + +.dropableClass { + background-color: #e2eae3; +} + +.loader { + position: fixed; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + z-index: 9999; + background: url("../img/loading.gif") 50% 50% no-repeat #f9f9f9; +} + +.screencast { + position: relative; + width: 480px; + height: 161px; + z-index: 9999; + background: url("../img/bpmnProcessmaker.gif") 50% 50% no-repeat #f9f9f9; +} + +.startcoronahelp { + position: relative; + height: 100px; + z-index: 9999; + background: url("../img/startcoronahelp.png") 50% 50% no-repeat; +} + +.mafe-button-menu { + display: inline-block; + vertical-align: top; + position: absolute; + top: 0px; + bottom: 2px; + padding-top: 5px; +} + +.mafe-button-menu img { + cursor: pointer; +} + +.mafe-button-menu-option { + padding: 7px; + color: black; + cursor: pointer; + position: absolute; + height: 14px; + width: 107px; + border: 1px solid lightgray; + background-color: #e8e8e8; + top: 2px; + left: -6px; +} + +.mafe-button-menu-option:hover { + background-color: lightgray; +} + +.mafe-button-menu-container { + position: relative; +} + +.mafe-can-connect-layer { + background-color: #9dee9d; + opacity: 0.4; +} + +.mafe-can-not-connect-layer { + background-color: #f590a5; + opacity: 0.4; +} + +.arrow_box { + position: absolute; + background: #ffffff; + border: 1px solid #BCBCBC; + padding-right: 5px; + font-size: smaller; + width: auto; + min-width: 27%; +} + +.arrow_box:after, .arrow_box:before { + right: 100%; + top: 10px; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none; +} + +.arrow_box:after { + border-color: rgba(255, 255, 255, 0); + border-right-color: #ffffff; + border-width: 7px; + margin-top: -7px; +} + +.arrow_box:before { + border-color: rgba(188, 188, 188, 0); + border-right-color: #BCBCBC; + border-width: 8px; + margin-top: -8px; +} + +.bpmn_validator { + /* background: #3397e2; */ + height: auto; + /* left: 0px; */ + /* position: fixed; */ + /* top: 68%; */ + width: 99.4%; + z-index: 2; + /* display: none; */ + border: 4px solid #E5E5E5; + visibility: hidden; + width: 100%; + position: fixed; + bottom: 0; + left: 0; +} + +.validator_header { + height: 28px; + background-color: #262A35; + color: #fff; +} + +.validator_body { + background-color: white; + font-size: smaller; +} + +.validator-close { + float: right; +} + +i.mafe-icon-error { + float: left; + height: 15px; + height: 15px; +} + +i.mafe-icon-warning { + float: left; + height: 15px; + height: 15px; +} + +.validator_header h2 { + text-align: left; + font-size: 12px; + line-height: 28px; + margin: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-left: 10px; + float: left; +} + +table.dataTable thead th, table.dataTable thead td { + padding: 10px 18px; + border-bottom: none; + background-color: #B6B6B6; + color: white; +} + +.dataTables_wrapper.no-footer .dataTables_scrollBody { + border-bottom: none; +} + +/* + * Sprite Validator Icons + */ +.mafe-sprite, .mafe-style-error-marker-10, .mafe-style-error-marker-14, .mafe-style-error-marker-17, .mafe-style-error-marker-21, .mafe-style-error-marker-7, .mafe-style-warning-marker-10, .mafe-style-warning-marker-14, .mafe-style-warning-marker-17, .mafe-style-warning-marker-21, .mafe-style-warning-marker-7 { + background-image: url("../img/mafe-validate.png"); + background-repeat: no-repeat; +} + +/* Icons for Errors */ +.mafe-style-error-marker-10 { + background-position: 0 0; +} + +.mafe-style-error-marker-14 { + background-position: 0 -10px; +} + +.mafe-style-error-marker-17 { + background-position: 0 -24px; +} + +.mafe-style-error-marker-21 { + background-position: 0 -41px; +} + +.mafe-style-error-marker-7 { + background-position: 0 -62px; +} + +/* Icons for Warning */ +.mafe-style-warning-marker-10 { + background-position: 0 -69px; +} + +.mafe-style-warning-marker-14 { + background-position: 0 -78px; +} + +.mafe-style-warning-marker-17 { + background-position: 0 -91px; +} + +.mafe-style-warning-marker-21 { + background-position: 0 -107px; +} + +.mafe-style-warning-marker-7 { + background-position: 0 -127px; +} + +.crown-container { + z-index: auto; + display: table; + padding-left: 4px; +} + +.crown-container .row { + display: table-row; +} + +.crown-container .row .item-crown { + display: table-cell; +} + +.mafe-corona-task { + background: url("../img/corona-task.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-task:hover { + background: url("../img/corona-task.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-gateway-exclusive { + background: url("../img/corona-gateway-exclusive.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-gateway-exclusive:hover { + background: url("../img/corona-gateway-exclusive.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-intermediate { + background: url("../img/corona-intermediate.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-intermediate:hover { + background: url("../img/corona-intermediate.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-end { + background: url("../img/corona-end.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-end:hover { + background: url("../img/corona-end.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-flow { + background: url("../img/corona-flow.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-flow:hover { + background: url("../img/corona-flow.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-settings { + background: url("../img/corona-settings.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-settings:hover { + background: url("../img/corona-settings.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-delete { + background: url("../img/corona-delete.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-delete:hover { + background: url("../img/corona-delete.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +.mafe-corona-textfield-rename { + background: url("../img/corona-textfield-rename.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #ffffff; + cursor: pointer; +} + +.mafe-corona-textfield-rename:hover { + background: url("../img/corona-textfield-rename.png") no-repeat center; + width: 22px; + height: 22px; + background-color: #87cbff; + cursor: pointer; + color: #666666; +} + +/*Dynaform Creation Buttons*/ +.pmui .mafeButton .pmMafeButtonsIconBlack { + background: #474747 url(../img/form.png) no-repeat center; + background-size: contain; + height: 55px; + width: 100px; + margin-top: 15px; +} + +.pmui .mafeButton .pmMafeButtonsIconPMTable { + background: #474747 url(../img/table.png) no-repeat center; + background-size: contain; + height: 55px; + width: 80px; + margin-top: 15px; +} + +.pmui .mafeButton .pmMafeButtonsIconCopy { + background: #474747 url(../img/copy_import.png) no-repeat center; + background-size: contain; + height: 55px; + width: 80px; + margin-top: 15px; +} + +.pmui.varButton-delete { + background: #e84c3d; + padding: 0 15px; +} + +.pmui.varButton-edit { + background: #19bd9b; + padding: 0 15px; +} + +/* AccordionItem */ +.pmui-accordion-item-header { + background-color: #DFE8F6; + border-top: 1px solid #ada9a9; + border-bottom: 1px solid #ada9a9; + cursor: pointer; + overflow-wrap: break-word; + padding: 2px; + text-align: left; +} + +/*.pmtrigger .newPmtrigger .pmui-treepanel-node-icon{ + background: grey; +}*/ +.pmcustomtrigger .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmcopytrigger .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmfunction .pmui-treepanel-node-father .pmui-treepanel-node-collapsed .pmui-treepanel-node-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +/*accordion*/ +.pmcustomtrigger { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -63px -250px; +} + +.pmcopytrigger { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -65px -271px; +} + +.pmFunctions { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -66px -120px; +} + +.pmTrSharepoint { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -79px -92px; +} + +.pmTrAlfresco { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -72px -223px; +} + +.pmZimbra { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -78px -15px; +} + +.pmSugar { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -68px -152px; +} + +.pmTalend { + background: url(../img/triggerWizard.png) no-repeat; + background-position: -85px -48px; +} + +.ui-tooltip { + overflow-wrap: break-word; +} + + +.mafe-designer-assigment-button { + background-color: #d7d9dd; + font-size: 10; + text-transform: none; +} + +.mafe-designer-assigment-grid .pmui-gridpanelcell { + text-align: left; +} + +.mafe-grid-button { + background-color: transparent; + height: 0; + padding: 0px 0px; +} + +.mafe-grid-button.button-icon-user .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: 1px -195px; + width: 14px; + height: 17px; + display: block; +} + +.mafe-grid-button.button-icon-group .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -2px -135px; + width: 22px; + height: 17px; + display: block; +} + +.mafe-grid-button .button-label { + display: none; +} + +.mafe-designer-assigment-grid .pmui-gridpanelcolumn { + background-color: #FFFFFF; + padding: 0px 10px; +} + +.mafe-designer-assigment-grid .mafe-assigment-panel { + padding: 0px 10px; +} + +/* PANEL */ +/* +.mafe-assigment-panel .pmui-panel { + background-color: transparent; +} + + +.mafe-assigment-panel-right{ + background-color:#eaebed; + padding-left: 10px; +} + +.mafe-assigment-panel-global { + background-color: transparent; + padding-left: 20px; + padding-right: 0px; +} */ +/* TEXT SEARCH */ +.pmui.pmui-textfield.mafe-assigment-search { + text-align: left; +} + +/* BUTTONS SEARCH */ +/* GRID ASSIGNES*/ +/*.mafe-designer-assigment-grid { + background-color: #FFFFFF; + text-align: left; + padding: 0px 0px; +} + +.mafe-designer-assigment-grid .pmui-gridpanel-table{ + min-height: 0em; +}*/ +.pmui-pmtooltipmessage .pmui-button-label { + color: #999999; + font-size: 10px; +} + +.pmui-pmtooltipmessage .mafe-tooltip-close { + background: transparent; + margin: 0px 0px; + padding: 0px 0px; + width: auto; + height: auto; + color: black; +} + +.pmui-pmtooltipmessage .mafe-tooltip-header { + background: #EEF1F6; + margin: 0px 7px; + padding: 4px 0px; + width: auto; + height: 6px; + color: black; +} + +.pmui-pmtooltipmessage .mafe-tooltip-body { + background: #EEF1F6; + padding: 10px; +} + +.pmui-pmtooltipmessage { + background: #FFFFFF; + font-size: 10; + border: 1px solid #e7e7e7; + -webkit-box-shadow: 2px 2px 5px 0px #999; + -moz-box-shadow: 2px 2px 5px 0px #999; + filter: shadow(color=#999999, direction=135, strength=2); +} + +#list-usersIngroup { + width: 175px; + max-height: 100px; + background: #eef1f6; +} + +#list-usersIngroup #list-usersIngroup-iem { + font-size: 13px; + text-overflow: ellipsis; + overflow: hidden; + display: block; + white-space: nowrap; + width: 175px; + color: #333333; +} + +#tooltipmessagecustombody { + float: left; + padding: 10px; +} + +#tooltipmessagecustom #header { + width: 100%; + padding: 2px; + height: 20px; + box-sizing: border-box; + background-color: #e7e7e7; +} + +#tooltipmessagecustom #header a { + float: right; + margin-right: 4px; + cursor: pointer; +} + +.pmui .mafe-button-img-properties .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -91px -270px; +} + +.pmui .mafe-button-img-edit .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -89px -292px; +} + +.pmui .mafe-button-img-delete .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmui .mafe-button-img-delete .button-icon, .pmui .mafe-button-img-edit .button-icon, .pmui .mafe-button-img-properties .button-icon { + width: 18px; + height: 18px; + display: inline-block; +} + +a.mafe-button-img-properties, a.mafe-button-img-delete, a.mafe-button-img-edit { + background-color: transparent; +} + +.pmui .mafe-button-img-properties .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -91px -270px; +} + +.pmui .mafe-button-img-edit .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -89px -292px; +} + +.pmui .mafe-button-img-delete .button-icon { + background: url(../img/mafe-sprite.png) no-repeat; + background-position: -62px -294px; +} + +.pmui .mafe-button-img-delete .button-icon, .pmui .mafe-button-img-edit .button-icon, .pmui .mafe-button-img-properties .button-icon { + width: 18px; + height: 18px; + display: inline-block; +} + +a.mafe-button-img-properties, a.mafe-button-img-delete, a.mafe-button-img-edit { + background-color: transparent; +} + +.itemsSteps .pmui-treepanel-node-father > .pmui-treepanel-node-title .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.itemsSteps .pmui-treepanel-node-leaf .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.treePanelTriggers .pmui-treepanel-node-father > .pmui-treepanel-node-title .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.treePanelTriggers .pmui-treepanel-node-leaf .pmui-treepanel-node-icon { + background-image: none; + background-size: contain; +} + +.itemsSteps { + border-radius: 7px; + background: white; + box-sizing: border-box; + border: 1px solid #ccc; +} + +.treePanelTriggers { + border-radius: '7px'; + border: 1px solid #ccc; + width: 216px; + overflow: auto; +} + +#accordionPanelTriggers .pmui-gridpanelcell-content { + padding: 0px; +} + +.mafe-step-arrow-up { + background: url(../img/arrow-up.png) no-repeat; + background-size: 20px 10px; + width: 20px; + height: 10px; + margin: 0px; + padding: 0px; +} + +.mafe-step-arrow-down { + background: url(../img/arrow-down.png) no-repeat; + background-size: 20px 10px; + width: 20px; + height: 10px; + margin: 0px; + padding: 0px; +} + +.steps-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + list-style: none; + height: 2em; + text-align: center; + color: #9b9b9b; +} + +.steps-placeholder .placeholder-index { + display: block; + padding: 7px; +} + +@charset "UTF-8"; +.mafe-col { + background: #676767; + /*background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod…EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #b0b1b3 0%, #939497 10%, #727375 91%, #595959 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b0b1b3), color-stop(10%,#939497), color-stop(91%,#727375), color-stop(100%,#595959)); + background: -webkit-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -o-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -ms-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: linear-gradient(to bottom, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b0b1b3', endColorstr='#595959',GradientType=0 );*/ + color: white; + font-size: 12px; + width: auto; + padding: 6px 15px; + font-weight: inherit; +} + +.mafe-body-properties { + font-size: 11px; +} + +.mafe-field-labelCell { + padding: 2px; + border-bottom: 1px solid #D6D6D6; +} + +.pmui-rowfield:hover { + background: #D6D6D6; +} + +.mafe-field-labelCell .pmui-textcontrol { + border: 1px solid white; +} + +.mafe-field-labelCell .pmui-textcontrol, .mafe-field-labelCell .pmui-dropdownlistcontrol { + font-size: 12px; +} + +.mafe-table-properties tr:nth-child(odd) { + background-color: #E5E5E5; +} + +.mafe-table-properties tr:nth-child(even) { + background-color: #F2F2F2; +} + +.mafe-field-labelCell .pmui-button { + color: #4e4d4d; + border-radius: 2px; + float: right; + border: 1px solid #b1b1b1; + background: -moz-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 91%, #bababa 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(10%, #eaeaea), color-stop(91%, #cfcfcf), color-stop(100%, #bababa)); + background: -webkit-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: -o-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: -ms-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + background: linear-gradient(to bottom, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); +} + +.pmui-rowfield .error { + outline: 1px solid #ecc3c2; + border: 1px solid white; +} + +.pmui-rowfield.error { + color: red; +} + +.pmui-pmformgrid { + padding: 1em 0 1em 1em; + box-sizing: border-box; + background: #f1f1f1; +} + +.pmdesigner-initialrow { + height: 10em !important; +} + +.pmdesigner-formgrid-head, +.pmdesigner-formgrid-headrow, +.pmdesigner-formgrid-headcell { + padding: 0; + height: 0; +} + +.pmdesigner-textMessageContent { + color: #777f8b; +} + +/*.pmdesigner-mainpanel-slec, +.pmdesigner-formgrid, +.pmdesigner-formgrid-bodyrow, +.pmdesigner-formgrid-bodycell { + box-sizing: border-box; + border-collapse: collapse; + border: 1px dotted #c0c0c0; +}*/ +.pmdesigner-formgrid-bodyrow { + background: white; +} + +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell { + background: #F0F0F0; +} + +.pmdesigner-rowhandler { + box-sizing: border-box; + background: url("../img/moveUpDown.png") no-repeat center rgba(224, 222, 222, 0.8); + display: inline-block; + padding: 0.3em; + position: absolute; + top: 0; + left: 0; + color: white; + cursor: move; +} + +.pmui-window.pmdesigner-dropdownconfig .pmui-window-body { + padding: 0 1em; +} + +.pmui-gridfieldcell.gridfieldcell-bodycell.pmui-containeritembehavior-hover, +.pmdesigner-formgrid-bodycell.pmui-containeritembehavior-hover { + border-style: dashed; + background: #FCF8D6; + border-color: #e9ca27; + border-width: 2px; + color: orange; +} + +.pmdesigner-formgrid-bodycell { + min-height: 2em; + background: white; +} + +.unique-cell { + text-align: center; + font-size: 30px; + color: #aaa8a8; + height: 5em; +} + +/* +.pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell.pmdesigner-active +{ + background: #ECECE9; + background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod?EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #ffffff 0%, #eaeaea 10%, #cfcfcf 91%, #bababa 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(10%,#eaeaea), color-stop(91%,#cfcfcf), color-stop(100%,#bababa)); + background: -webkit-linear-gradient(top, #ffffff 0%,#F1F3CA 10%,#cfcfcf 91%,#bababa 100%); + background: -o-linear-gradient(top, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + background: -ms-linear-gradient(top, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + background: linear-gradient(to bottom, #ffffff 0%,#eaeaea 10%,#cfcfcf 91%,#bababa 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eaeaea', endColorstr='#cfcfcf',GradientType=0 ); +} +*/ +.pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmdesigner-formgrid-bodyrow:hover .pmdesigner-formgrid-bodycell.pmdesigner-active, +.pmui-gridfieldcell.gridfieldcell-bodycell.pmdesigner-active { + background: #C0C0C0; + color: white; +} + +.pmdesigner-formgrid-bodycell .pmui-field-label { + color: inherit; +} + +.pmdesigner-formgrid-headcell { + width: 8.333333333333%; + box-sizing: border-box; +} + +#pmdesigner-mainpanel .pmui-contextmenu-target { + background: #F0F0F0; +} + +.pmdesigner-formpanel { + display: block; + border: 1px solid #e0e0e0; +} + +.pmdesigner-formpanel:hover { + background: #e0e0e0; +} + +.pmui.ui-layout-pane.right-layout-panel { + padding: 0px; +} + +.pmui.pmui-panel.pmdesigner-layout-eastpanel { + overflow-x: hidden; +} + +.toolbox-title { + display: block; + padding: 5px; + background: linear-gradient(to bottom, #ffffff 0%, #eaeaea 10%, #cfcfcf 90%, #bababa 100%); + font-size: 14px; +} + +/*.pmui-accordion-item-header { + background: #b0b1b3; + background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJod?EiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+); + background: -moz-linear-gradient(top, #b0b1b3 0%, #939497 10%, #727375 91%, #595959 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#b0b1b3), color-stop(10%,#939497), color-stop(91%,#727375), color-stop(100%,#595959)); + background: -webkit-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -o-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: -ms-linear-gradient(top, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + background: linear-gradient(to bottom, #b0b1b3 0%,#939497 10%,#727375 91%,#595959 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b0b1b3', endColorstr='#595959',GradientType=0 ); + color: #F0F0F0; + border-color: #888; +}*/ +.pmui-containeritembehavior-placeholder { + visibility: visible; + background: rgba(128, 128, 128, 0.3); + border: 2px #888 dashed; + list-style: none; + height: 2em; +} + +/* +.pmui.pmui-listpanel.components-list { + border: none; +} +*/ +.toolbox-title { + display: block; + padding: 0.5em; + font-size: 15px; + background: #2d3e50; + color: white; +} + +.pmui.pmui-listpanel.components-list .pmui-listitem { + background: none; + border: none; +} + +.pmui.pmui-listpanel.components-list .pmui-listitem:hover { + background: #e0e0e0; +} + +.pmdesigner-controlslist .pmui-listitem .pmui-listitem-icon, .otherControlsList-list .pmui-listitem .pmui-listitem-icon { + background-image: url(../img/cmp-icons.png); + width: 16px; + height: 16px; +} + +.pmui-listitem.cmp-text .pmui-listitem-icon { + background-position: 0 -128px; +} + +.pmui-listitem.cmp-dropdown .pmui-listitem-icon { + background-position: 0 -144px; +} + +.pmui-listitem.cmp-checkbox .pmui-listitem-icon { + background-position: 0 -32px; +} + +.pmui-listitem.cmp-radio .pmui-listitem-icon { + background-position: 0 0; +} + +.pmui-listitem.cmp-label .pmui-listitem-icon { + background-position: 0 -64px; +} + +.pmui-listitem.cmp-datetime .pmui-listitem-icon { + background-position: 0 -16px; +} + +.pmui-listitem.cmp-fieldset .pmui-listitem-icon { + background-position: 0 -80px; +} + +.pmui-listitem.cmp-formpanel .pmui-listitem-icon { + background-position: 0 -48px; +} + +.pmui-listitem.cmp-textarea .pmui-listitem-icon { + background-position: 0 -96px; +} + +.pmui-listitem.controls-submit .pmui-listitem-icon { + background: url("../img/submit.png") no-repeat; + width: 33px; + height: 20px; +} + +.pmui-listitem.controls-button .pmui-listitem-icon { + background: url("../img/button.png") no-repeat; + width: 33px; + height: 20px; +} + +.pmui-listitem.grid-field .pmui-listitem-icon { + background: url("../img/icon_grid.png") no-repeat; + width: 33px; + height: 30px; +} + +.pmui-listitem.label-field .pmui-listitem-icon { + background: url("../img/label.png") no-repeat; + width: 33px; + height: 30px; + background-size: contain; +} + +.pmui-listitem.subForm-field .pmui-listitem-icon { + background: url("../img/subform.png") no-repeat; + width: 33px; + height: 30px; + background-size: contain; +} + +.pmui-listitem.fiel-field .pmui-listitem-icon { + background: url("../img/file2.png") no-repeat; + width: 24px; + height: 25px; +} + +.subFormList-list .pmdesigner-subform .pmui-listitem-icon { + background: url("../img/subform.png") no-repeat; + width: 20px; + height: 20px; + background-size: contain; +} + +.pmui-listitem.image-field .pmui-listitem-icon { + background: url("../img/image.png") no-repeat; + width: 24px; + height: 25px; + background-size: contain; +} + +.pmui-listitem.link-field .pmui-listitem-icon { + background: url("../img/link.png") no-repeat; + width: 24px; + height: 25px; + background-size: contain; +} + +.pmui-listitem.controls-title .pmui-listitem-icon { + background-position: 0 -112px; +} + +.pmui-window.pmdesigner-controlselector .pmui-window-body { + padding: 1em; +} + +.pmui-window.pmdesigner-dependencyFieldWindow .pmui-window-body { + padding: 1em; +} + +.pm-titleListFields { + margin-left: 40px; + font-weight: bold; + font-size: 20px; +} + +.pm-titleListDependent { + margin-left: 14px; + font-weight: bold; + font-size: 20px; +} + +.pm-dependentFieldsGrid .pmui-button { + background: #e84c3d; +} + +.pm-listFieldGrid .pmui-button { + background: #19bd9b; +} + +.pmdesigner-dependencyFieldWindow .pmui-window-body { + background: #faf8f8; +} + +.pm_labelfield .pmui-textcontrol { + border: 1px white; +} + +.pm-listFieldGrid .pmui-gridpanelcell-content { + padding: 2px; +} + +.pm-dependentFieldsGrid .pmui-gridpanelcell-content { + padding: 2px; +} + +.pm-listFieldGrid .pmui-gridpanel-toolbar { + height: 30px; +} + +.pm-dependentFieldsGrid .pmui-gridpanel-toolbar { + height: 30px; +} + +.pmdesigner-formgrid { + /*background: rgb(150, 150, 150);*/ + width: 99%; +} + +.pmdesigner-formgrid .emptyform { + width: 100%; + height: 10em; +} + +/*.pmdesigner-formgrid-bodyrow.my_row{ + border-left: 3px solid #c0c0c0; + border-bottom: 3px solid #c0c0c0; +}*/ +.pmdesigner-formgrid-bodycell.pmui-textcontrol { + width: 100%; +} + +.pmdesigner-formgrid-bodycell .pmui-buttonfield .pmui-field-control { + width: auto; +} + +.pmdesigner-formgrid-bodycell .pmui-datetimefield .icon-field { + background: url("../img/calendar.png") no-repeat; + display: inline-block; + padding: 0.6em; +} + +.pmui-pmsuggestfield .icon-field { + background: url("../img/suggest.png") no-repeat; + display: inline-block; + padding: 0.6em; + background-size: contain; +} + +/*.pmdesigner-formgrid-bodycell .pmui-field-textLabel{ + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; + position: relative; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + width: inherit; +}*/ +.pmdesigner-formgrid-bodycell .pmui-field-label { + padding: 6px 3px 6px 10px; +} + +.pmdesigner-formgrid-bodycell .pmui-field-textLabel { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; +} + +.pmdesigner-formgrid-bodycell.colspan_12-11 .pmui-field-control { + width: 73%; +} + +.pmdesigner-formgrid-bodycell.colspan_10-9 .pmui-field-control { + width: 72%; +} + +.pmdesigner-formgrid-bodycell.colspan_8-7 .pmui-field-control { + width: 70%; +} + +.pmdesigner-formgrid-bodycell.colspan_6 .pmui-field-control { + width: 69%; +} + +.pmdesigner-formgrid-bodycell.colspan_5 .pmui-field-control { + width: 68%; +} + +.pmdesigner-formgrid-bodycell.colspan_4 .pmui-field-control { + width: 65%; +} + +.pmdesigner-formgrid-bodycell.colspan_3 .pmui-field-control { + width: 61%; +} + +.pmdesigner-formgrid-bodycell.colspan_2 .pmui-field-control { + width: 53%; +} + +.pmdesigner-formgrid-bodycell.colspan_1 .pmui-field-control { + width: 26%; +} + +.pmdesigner-formgrid-bodycell .pmui-buttonfield .pmui-field-control { + text-align: center; +} + +/*custom styles formdesigner*/ +/*/////////////////////////////////////////////////////// +/ +/ +/ +/ + + +/ +/ +/ +/*/ +#designer-body .pmui-accordion-item-body { + background: #FFFFFF; + padding: 0 5px 0 5px; + background: #e0e0e0; +} + +.pmdesigner-mainlayout, #designer-body .right-layout-panel, .pmdesigner-layout-eastpanel { + background: #f1f1f1; +} + +#designer-body .pmui-accordion-item-body .pmui-listitem { + padding: 3px; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem { + color: white; + border-bottom: 2px solid #d6d6d6; + background: white; + cursor: move; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem:hover { + color: black; + background: #e0e0e0; +} + +#designer-body .pmListItem-buttonEdit { + background: white; + color: white; + border: none; +} + +#designer-body .pmui.pmui-listpanel.components-list .pmui-listitem:hover .pmListItem-buttonEdit { + background-color: #19bd9b; +} + +#designer-body .pmui-accordion-item-header { + font-size: 13px; +} + +#designer-body .pmui-accordion-item-container { + border-left: 1px solid white; + border-right: 1px solid white; +} + +#designer-body .pmui-accordion-item-header .pmui-textcontrol { + outline: none; + margin-left: 10px; +} + +#designer-body .right-layout-panel .pmui-listpanel-toolbar { + display: none; +} + +#designer-body .pmui-accordion-item-header { + background: #676E7C; + color: white; + border-color: #d8dbdf; + padding: 3px 0 6px 0; +} + +#designer-body .otherControlsList-list { + background: white; +} + +#designer-body .otherControlsList-list .pmui-listitem { + background: white; + color: black; + border-style: none; +} + +#designer-body .otherControlsList-list .pmui-listitem:hover { + background: #e0e0e0; + color: black; +} + +#designer-body .ui-layout-pane { + overflow: initial; +} + +#designer-body { + background: #c0c0c0; +} + +#designer-body .label-other-controls { + padding-left: 5px; + font-size: 13px; +} + +#designer-body .pmdesigner-formgrid-tableContainer { + overflow: auto; + width: 100%; + height: 97%; + border: 1px solid #C0C0C0; +} + +#otherControlsList-firstItem .pmui-listitem-text, #otherControlsList-secondItem .pmui-listitem-text { + /*display: none;*/ +} + +#idOtherControlsList .pmui-listitem-text { + margin-left: 20px; + position: absolute; + left: 50px; + top: 10px; +} + +#designer-body .formGrid-freeCell { + width: 98%; + height: 36px; + border: 3px dotted #888888; + background: #c0c0c0; +} + +.pmui-propertiestable { + background: white; + padding: 0 2px 0 2px; +} + +.pmui-field.formview-view .pmui-textcontrol, +.pmui-field.formview-view .pmui-dropdownlistcontrol, +.pmui-field.formview-view .pmui-textareacontrol, +.pmui-field.formview-view .pmui-passwordcontrol, +.pmui-field.formview-view .pmui-uploadcontrol, +.pmui-field.formview-view .pmui-datetimecontrol { + border: 1px solid white; + background: #ECECEC; + font-style: italic; +} + +.pmui-field.formview-disabled .pmui-textcontrol, +.pmui-field.formview-disabled .pmui-dropdownlistcontrol, +.pmui-field.formview-disabled .pmui-textareacontrol, +.pmui-field.formview-disabled .pmui-passwordcontrol, +.pmui-field.formview-disabled .pmui-uploadcontrol, +.pmui-field.formview-disabled .pmui-datetimecontrol { + color: #757575; + background: #ECECEC; +} + +#designer-body .pmui-accordion-panel-container #first-item .pmui-accordion-item-body { + height: 200px; +} + +#third-item .pmui-accordion-item-body { + height: 850px; +} + +.pmTextContainer1 { + width: 60px; + display: inline-block; + font-size: 12px; + margin: 1px; + color: #ee710f; +} + +.pmTextContainer1 span, .pmNameContent { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: inline-block; +} + +.pmTextContainer2 { + width: auto; + display: inline-block; + font-size: 12px; + color: #21366d; +} + +.pmNameContent { + width: 130px; +} + +.pmdesigner-formgrid-bodycell .pmui-pmsub-titlefield h5 { + background-color: #9FA1AA; + color: white; + margin: 0.5em 0 0.5em 0; + padding: 8px; +} + +.pmdesigner-formgrid-bodycell.pmdesigner-active .pmui-pmsub-titlefield h5 { + background: none; +} + +.pmdesigner-formgrid-bodycell .pmui-pmtitlefield h4 { + background-color: #383D41; + color: white; + font-size: 18px; + padding: 10px; + margin: 0.5em 0 0.5em 0; +} + +.pmdesigner-formgrid-bodycell.pmdesigner-active .pmui-pmtitlefield h4 { + background: none; +} + +.pmdesigner-itemcontrol-x { + margin-left: 5px; + vertical-align: super; + cursor: pointer; + color: #e7e7e7; +} + +.pmdesigner-itemcontrol-x:hover { + color: #8b8888; +} + +.pmdesigner-itemcontrol-itemselected, +.pmdesigner-itemcontrol-optselected, +.pmdesigner-itemcontrol-bracketsselected { + position: relative; + display: inline-block; +} + +.pmdesigner-itemcontrol-itemselected > a { + background: #f5f2f2; + padding: 5px; + margin: 1px; +} + +.pmdesigner-itemcontrol-itemselected > a:hover { + background: #e7e7e7; +} + +.pmdesigner-itemcontrol-bracketsselected > a { + color: red; + padding: 1px; + background: #f5f2f2; +} + +.pmdesigner-itemcontrol-optselected > a { + color: blue; + padding: 1px; + background: #f5f2f2; +} + +/* areacontrol*/ +.pmdesigner-areacontrol { + background: white; + height: auto; +} + +.pmdesigner-suggestcontrol { + height: 20%; + padding: 5px; +} + +.pmdesigner-suggestcontrol input { + height: 20px; + width: 90%; +} + +.pmdesigner-suggestfields { + position: absolute; + width: 52%; + z-index: 5; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); + -webkit-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); + -moz-box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.5); +} + +.pmdesigner-suggestfields ul { + list-style-type: none; + padding: 0; + margin: 0; +} + +.pmdesigner-suggestfields a { + display: block; + background: #DFDFDF; + color: #2d3e50; + text-decoration: none; + padding: 0.4em 0.6em; +} + +.pmdesigner-suggestfields li { + left: 0px; + top: 0px; + width: auto; + height: auto; + position: relative; + z-index: auto; +} + +.pmdesigner-suggestfields a:hover { + background: #838486; + color: white; + cursor: pointer; +} + +.pmdesigner-areacontrol-operations { + height: 10%; +} + +.pmdesigner-areacontrol-operationsitem { + background: #c4c9ca; + height: 12px; + padding: 3px 9px; + margin: 0 2px; + text-align: center; + cursor: pointer; + border-radius: 3px; + opacity: 0.5; +} + +.pmdesigner-areacontrol-operationsitem:hover { + opacity: 1; +} + +.pmdesigner-areacontrol-areaformula { + height: auto; + margin: 2px; + background: #f5f2f2; + padding: 10px 2px; +} + +.GridFieldItem .pmui-field-label { + background: #888888; + color: white; + font-size: 12px; + padding: 2px; + display: inline-block; + margin: initial; +} + +.GridFieldItem .pmui-field-control { + padding: 3%; +} + +.GridFieldItem { + padding: initial; +} + +.gridfielditem-header { + border-bottom: 1px solid #c0c0c0; +} + +.GridFieldItem-textarea .pmui-textareacontrol { + resize: vertical; +} + +.GridFieldItem-configFieldIcon { + background: url("../img/config.png") no-repeat white; + display: inline-block; + width: 20%; + background-size: contain; + vertical-align: top; + height: 20px; +} + +.GridFieldItem-suggest .icon-field { + background: url("../img/suggest.png") no-repeat; + display: inline-block; + padding: 0.7em; + background-size: contain; + vertical-align: top; + float: right; +} + +.GridFieldItem-datetime .icon-field { + background: url("../img/datetime.png") no-repeat; + display: inline-block; + padding: 0.7em; + background-size: contain; + vertical-align: top; + float: right; +} + +.pmui-gridfield .gridfieldcell-bodycell { + vertical-align: top; + float: left; + background: white; + border-left: 1px solid #c0c0c0; +} + +.pmui-gridfield .GridField-list { + padding: 1px; + margin: 0px; + background: #c0c0c0; +} + +/*GridField-black-cell-contain +GridField-black-cell-icon +GridField-black-cell-message +*/ +.gridfieldcell-bodycell .GridField-black-cell-icon { + background: url(../img/addControl.png) no-repeat; + width: 100%; + height: 50%; + margin-left: 20%; + display: block; + background-size: contain; +} + +.gridfieldcell-bodycell .GridField-black-cell-contain { + text-align: center; + text-align: center; + color: black; + font-size: 14px; +} + +/*.pmui-gridfield { + box-sizing : border-box; + border : 2px solid #c0c0c0; + padding : 5px 5px 5px 8px; +}*/ +.GridFieldItem.GridFieldItem-text .GridFieldItem-iconControl { + background: url(../img/inputext.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-textarea .GridFieldItem-iconControl { + background: url(../img/textarea.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-dropdown .GridFieldItem-iconControl { + background: url(../img/select.png) no-repeat; + background-size: contain; + width: 89%; + padding: 7px 0px 7px 0; + margin: 2% 0 0 4%; +} + +.GridFieldItem.GridFieldItem-checkbox .GridFieldItem-iconControl { + background: url(../img/checkbox.png) no-repeat; + background-size: cover; + width: 47%; + height: 14px; + /* padding: 25px 75px 1px 1px; */ + margin: 3% 0 0 25%; +} + +.GridFieldItem.GridFieldItem-radio .GridFieldItem-iconControl { + background: url(../img/radio.png) no-repeat; + background-size: cover; + width: 47%; + height: 14px; + /* padding: 25px 75px 1px 1px; */ + margin: 3% 0 0 25%; +} + +.GridFieldItem.GridFieldItem-suggest .GridFieldItem-iconControl { + background: url(../img/inputext.png) no-repeat; + width: 80%; + height: 1.7em; + background-size: contain; + margin: 2% 1% 1% 11%; +} + +.GridField-listContainer { + overflow: auto; + height: inherit; + padding-left: 9px; +} + +.pmimagefield-imageContainer { + background: url(../img/image.png) no-repeat center #e7e7e7; + padding: 15px; + background-size: contain; + opacity: 0.5; +} + +.pmimagefield-commentContainer { + font-size: 12px; + font-style: italic; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-link { + background: url("../img/link_web.png") no-repeat center; + background-size: contain; + height: 30px; + width: 100%; + display: block; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-linkContainer { + text-align: center; + background-color: #F5F5F5; + border: 1px solid #DFDDDD; + height: 30px; + width: 100%; +} + +.pmui-pmlinkfield .PMLinkField-linkContainer { + padding-top: 8px; +} + +.pmui-pmlinkfield .PMLinkField-linkContainer .PMLinkField-link { + text-decoration: underline; + color: #53539e; + font-style: italic; +} + +.pmui-pmlinkfield.PMLinkField-noUrl .PMLinkField-linkContainer { + padding-top: initial; +} + +.pmui-pm-textlabelfield .pmui-textlabel-field { + margin-left: 10px; +} + +.pmui-pmformfield .pmFormField-formContainer { + text-align: center; + background-color: #F5F5F5; + border: 1px solid #DFDDDD; + height: 30px; + width: 100%; + padding-bottom: 2px; + padding-top: 2px; +} + +.pmui-pmformfield .pmFormField-formIcon { + background: url("../img/subform.png") no-repeat; + width: 28px; + height: 28px; + display: inline-block; + background-size: contain; +} + +.pmui-pmformfield .pmui-field-label { + background: #d3d0d0; + color: white; +} + +.pmui-pmformfield .pmFormField-editIcon { + background: url("../img/edit.png") no-repeat; + width: 18px; + height: 18px; + display: inline-block; + background-size: contain; + float: right; +} + +@font-face { + font-family: "SourceSansPro"; + src: url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot'); + src: url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.ttf') format('truetype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.eot') format('embedded-opentype'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.woff') format('woff'), url('../fonts/SourceSansPro-Regular/SourceSansPro-Regular-webfont.svg') format('svg'); +} +@font-face { + font-family: "SourceSansProBold"; + src: url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot'); + src: url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.ttf') format('truetype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.eot') format('embedded-opentype'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.woff') format('woff'), url('../fonts/SourceSansPro-Bold/SourceSansPro-Bold-webfont.svg') format('svg'); +} +body { + font-family: 'SourceSansProRegular', Arial, Tahoma, Verdana; + background: #fff; + margin: 0; + padding: 0; +} +.fd-list { + /*list-style: none;*/ + border-color: #bbb; + border-style: solid; + border-width: 0 0 1px 0; + background: #f8f8f8; + font-size:11px; + padding: 0.3em; + cursor: pointer; +} +.fd-list:nth-child(odd) { + background: #eaebed; +} +.fd-list:hover { + background: #e0e0e0; +} +.fd-list-responsive { + position: relative; + font-size: 11px; + width: 54px; + height: 54px; + float: left; + text-align: center; + background: white; + margin: 4px; + padding: 2px; + border: 1px solid darkgray; +} +.fd-button-panel{ + text-align: right; + border-top: 1px solid #e5e5e5; + position: absolute; + right: 0; + bottom: 0; + left: 0; + padding: 10px; +} +.fd-button { + font-family: "SourceSansPro", Arial, Tahoma, Verdana; + font-size: 14px; + display: inline-block; + text-decoration: none; + background-color: #1e91d1; + text-align: center; + transition: all .5s; + box-sizing: border-box; + border-radius: 2px; + margin: 0px 0px 0px 10px; + padding: 7px 20px; +} +.fd-button:hover { + opacity: 1; + opacity: 0.8; +} +.fd-button-success { + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; +} +.fd-button-link { + color: #383838; + text-decoration: underline; + background: none; + padding: initial; +} +.fd-button-create { + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; + background: #1fbc99 url(../img/ico_mor2.png) no-repeat 5px center; +} +.fd-button-yes{ + color: #fff !important; + background-color: #1fbc99; + border: 1px solid #1ba385; + font-size: 16px; +} +.fd-button-no{ + color: #fff !important; + background-color: #e4655f; + border: 1px solid #e14333; + font-size: 16px; +} +.fd-table tr:nth-child(odd) { + background-color: #E5E5E5; +} +.fd-table tr:nth-child(even) { + background-color: #F2F2F2; +} +.fd-tbody { + font-size: 11px; +} +.fd-table-th { + background: #3397e1; + color : white; + font-size: 11px; + padding: 6px 15px; + font-weight: inherit; +} +.fd-table-td { + padding: 2px; + border-bottom: 1px solid #D6D6D6; +} +.fd-table-td-error { + border: 1px solid red; +} +.fd-gridForm-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + height: 40px; + width: 100%; + margin-top:6px; +} +.fd-gridForm-grid { + list-style-type: none; + border:1px solid #C0C0C0; + height:84px; + overflow: hidden; + margin:20px 6px 6px 6px; + padding:6px; + white-space:nowrap; + /*overflow-x: scroll; + width: 600px;*/ +} +.fd-gridForm-grid > * { + padding: 1px 1px 1px 1px; + display: inline-block; + width: 130px; + text-align: left; + overflow: hidden; + vertical-align: top; + border:1px solid #C0C0C0; + margin-right:1px; + margin-top:20px; +} +.fd-gridForm-grid-placeholder { + background: rgba(128, 128, 128, 0.3); + border: 1px dashed #888; + height: 59px; + margin-top: 20px; +} +.grid-item-field{ + margin:20px 6px 6px 6px; + padding:4px; + position:relative; + border:1px solid white; + height: 30px; +} +.fd-gridForm-field-label{ + position: absolute; + top: 20px; + width: 60px; + overflow: hidden; +} +.fd-gridForm-grid-contentRequired { + position: absolute; + top: 20px; + left: 65px; + color:red; + display:none; +} +.fd-gridForm-grid-text { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-textarea { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-dropdown { + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-checkbox { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-checkgroup { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-radio { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + height: 18px; + border: 1px solid #e7e7e7; + overflow: hidden; +} +.fd-gridForm-grid-datetime { + height: 17px; + border: 1px solid #c0c0c0; + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-suggest { + height: 17px; + border: 1px solid #c0c0c0; + position: absolute; + left: 70px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-suggest-placeholder{ + color: gray; +} +.fd-gridForm-grid-hidden { + height: 17px; + border: 1px dashed #c0c0c0; + position: absolute; + left: 1px; + right: 1px; + top: 18px; +} +.fd-gridForm-grid-title { + padding: 4px; + font-family: "Montserrat",sans-serif; + font-size: 20px; + border-radius: 3px; + background: white; + color: #555151; + position: absolute; + left: 1px; + right: 1px; + overflow: hidden; +} +.fd-gridForm-grid-subtitle { + padding: 3px; + font-family: "Montserrat",sans-serif; + font-size: 15px; + border-radius: 3px; + background: white; + color: #555151; + position: absolute; + left: 1px; + right: 1px; + overflow: hidden; +} +.fd-gridForm-grid-annotation { + position: absolute; + left: 1px; + right: 1px; + top:18px; + overflow: hidden; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-link { + position: absolute; + left: 70px; + right: 1px; + top:18px; + overflow: hidden; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-image { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-file { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; + overflow: hidden; +} +.fd-gridForm-grid-submit { + position: absolute; + left: 1px; + right: 1px; + top: 18px; + overflow: hidden; +} +.fd-gridForm-grid-button { + position: absolute; + left: 1px; + right: 1px; + top: 18px; + overflow: hidden; +} +.fd-gridForm-grid-panel{ + border: 1px solid #DADADA; + background-color: #F6F5F3; + font-weight: bold; + position: absolute; + left: 1px; + right: 1px; + top: 1px; + overflow: hidden; + height: 34px; +} +.fd-gridForm-grid-msgpanel{ + border: 1px solid #DADADA; + background-color: #F6F5F3; + font-weight: bold; + position: absolute; + left: 1px; + right: 1px; + top: 1px; + overflow: hidden; + height: 34px; + color: red; +} +.fd-gridForm-grid-geomap { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-qrcode { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-signature { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-imagem { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-audiom { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-videom { + position: absolute; + left: 70px; + right: 1px; + top: 18px; + border: 1px solid #e7e7e7; + height: 18px; +} +.fd-gridForm-grid-griditem-gridtitle{ + position:absolute; + border:none; + margin:0px; + font-weight:bold; + left:6px; + width:auto; +} +.fd-gridForm-grid-griditem-gridplaceholder{ + position:absolute; + border:none; + margin:25px 0px 0px 0px; + color:gray; + left:6px; + width:auto; +} +.fd-gridForm-grid-griditem-columnRequired { + color: red; + display: none; +} +.fd-gridForm-grid-text-column { + box-sizing: border-box; + width: 100%; +} +.fd-gridForm-grid-textarea-column { + box-sizing: border-box; + width: 100%; + resize: vertical; +} +.fd-gridForm-grid-dropdown-column { + box-sizing: border-box; + width: 100%; +} +.fd-gridForm-grid-link-column { + margin-bottom: 2px; + color: blue; + text-decoration: underline; +} +.fd-designer-button{ + display:inline-block; + border-left:1px solid #70b5ec; + padding: 5px 6px; + cursor:pointer; + width:24px; + height:24px; +} +.fd-designer-button:hover{ + background: #2481c5; + color: #fff; +} +.fd-drag-drop{ + vertical-align:top; + cursor: move; +} +.fd-drag-drop-placeholder{ + background: rgba(128, 128, 128, 0.3); + border: 2px dashed #888; + height: 31px; +} +.fd-tooltip-date-format>div{ + overflow-x: hidden; + overflow-y: scroll; + height: 400px; + width: 309px; +} +.fd-tooltip{ + padding:3px; + border-radius: 0px; +} +.fd-message-error{ + color: #fff; + background: #F5736D; + padding: 4px 10px; + display: inline-block; +} + +ul.CodeMirror-hints { + z-index: 10000; +} +.ui-accordion-header { + color:white; + background:#3397e1; + border-top: 1px solid #3397e1; + border-bottom:1px solid #262932; + border-left:1px solid #262932; + border-right:1px solid #262932; + border-radius:initial; + font-size:12px; + text-align:center; +} +.ui-accordion-header.ui-state-active { + background: white; + color:#3397e1; +} +.ui-layout-pane-north{ + border:1px solid #2979b8; +} +.ui-layout-pane-center{ + border-top: none; + border-right: none; + border-bottom: none; +} +.ui-layout-toggler-west div { + width: 8px; + height: 35px; +} +.ui-datepicker { + border: 1px solid #DADADA; + background: #fcfdfd; + color: #222222; +} +.ui-datepicker-header { + border: 1px solid #fcfdfd; + background: white; + color: black; + font-weight: bold; +} +.ui-datepicker .ui-state-default:not(.ui-state-active):not(.ui-state-highlight) { + border: 1px solid #DADADA; + background: #fcfdfd; + font-weight: bold; + color: #2e6e9e; +} + +/* -- begin PMPopOver -- */ + +.mafe-popover { + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + padding: 1px; + background-color: #fff; + background-clip: padding-box; + border: 1px solid rgba(0,0,0,.2); + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2); + box-shadow: 0 5px 10px rgba(0,0,0,.2); + white-space: normal; + text-align: center; + max-width: 300px; + opacity: 0; + -webkit-transition: opacity .15s linear; + transition: opacity .15s linear; +} + +.mafe-popover.in { + opacity: 1; +} + +.mafe-popover-content { + padding: 9px 14px; +} + +.mafe-popover>.arrow, .mafe-popover>.arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} + +.mafe-popover>.arrow:after { + border-width: 10px; + content: ""; +} + +.mafe-popover.right>.arrow:after { + content: " "; + left: 1px; + bottom: -10px; + border-left-width: 0; + border-right-color: #fff; +} + +.mafe-popover.left>.arrow:after { + content: " "; + right: 1px; + bottom: -10px; + border-right-width: 0; + border-left-color: #fff; +} + +.mafe-popover.top>.arrow:after { + content: " "; + bottom: 1px; + right: -10px; + border-bottom-width: 0; + border-top-color: #fff; +} + +.mafe-popover.bottom>.arrow:after { + content: " "; + top: 1px; + right: -10px; + border-top-width: 0; + border-bottom-color: #fff; +} + +.mafe-popover>.arrow { + border-width: 11px; +} + +.mafe-popover.right>.arrow { + top: 50%; + left: -11px; + margin-top: -11px; + border-left-width: 0; + border-right-color: rgba(0,0,0,.25); +} + +.mafe-popover.left>.arrow { + top: 50%; + right: -11px; + margin-top: -11px; + border-right-width: 0; + border-left-color: rgba(0,0,0,.25); +} + +.mafe-popover.top>.arrow { + right: 50%; + bottom: -11px; + margin-right: -11px; + border-bottom-width: 0; + border-top-color: rgba(0,0,0,.25); +} + +.mafe-popover.bottom>.arrow { + right: 50%; + top: -11px; + margin-right: -11px; + border-top-width: 0; + border-bottom-color: rgba(0,0,0,.25); +} + +.mafe-popover :before, .mafe-popover :after { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +/* -- end PMPopOver -- */ + +.mafe-deprecated-control { + line-height: 1; + position: absolute; + top: 0; + right: 0; +} + +.mafe-deprecated-control::before { + font-family: FontAwesome; + content: "\f12a"; + color: white; + font-size: 10px; + width: 1.2em; + cursor: pointer; + height: 1.2em; + background: red; + display: inline-block; + text-align: center; + line-height: 1.2em; + border-radius: 100%; +} + +.mafe-popover.deprecated { + font-size: 11px; +} + +.mafe-deprecated-title { + font-size: 12px; + color: #B65858; + backgroud: none; + text-align: center; + font-weight: bold; +} + +.deprecated-ok-btn { + display: inline-block; + margin-bottom: 0; + font-weight: 400; + text-align: center; + vertical-align: middle; + cursor: pointer; + background-image: none; + border: 1px solid transparent; + white-space: nowrap; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + color: #fff; + background-color: #5cb85c; + border-color: #4cae4c; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} + +.grid-item-field .mafe-deprecated-control { + left: 0; + width: 1.2em; + display: inline-block; +} + +.mafe-alert { + font-size: 12px; + text-align: left; + font-weight: normal; + padding: 15px 30px 15px 15px; + border: 1px solid #ebccd1; + color: #a94442; + background-color: #f2dede; + border-radius: 4px; +} + +.mafe-alert .button-close { + background: none; + border: none; + color: inherit; + position: relative; + right: -22px; + float: right; + outline: none; + cursor: pointer; +} + +.pm-mafe-grid-item .mafe-deprecated-control { + float: left; + position: relative; +} + +.datetime-gadget-class { + position: absolute; +} diff --git a/workflow/public_html/lib/mafe/mafe.min.js b/workflow/public_html/lib/mafe/mafe.min.js new file mode 100644 index 000000000..6f1caa6da --- /dev/null +++ b/workflow/public_html/lib/mafe/mafe.min.js @@ -0,0 +1,45813 @@ +/** + * configure and extend classes and prototypes similar to inheritance in + * another languages. The method detects if we trying to extend a method of an object + * or a function inserted into a prototype. + * @param {String|Object} classObj contains the value of the class that we want to take an method for modifying + * @param {Sting} method the name of the function that we will be modified or overwritten + * @param {function} additionalFunc contains a function with the new code or the additional code + * for modified the original function. + * + * @return {[type]} [returns the value of the function modified, with the new functionality in this context.] + */ + +var PMExtend = function (classObj, method, additionalFunc) { + var originalFunc; + if (classObj.prototype !== undefined) { + originalFunc = classObj.prototype[method]; + if (originalFunc !== undefined && typeof originalFunc === 'function') { + return function () { + var returnVal = originalFunc.apply(this, arguments); + if (returnVal) { + returnVal = additionalFunc.apply(this, [returnVal].concat(arguments)); + } else { + additionalFunc.apply(this, arguments); + } + return returnVal; + }; + + } else { + //You need to implement a catch on a higher level or at the plugin + throw new Error("Cannot extend method " + method + " in Class " + classObj.name); + } + } else { + originalFunc = classObj[method]; + if (originalFunc !== undefined && typeof originalFunc === 'function') { + return function () { + var res; + res = originalFunc.apply(this, arguments); + res = additionalFunc.apply(this, [res].concat(arguments)); + return res; + }; + } else { + //You need to implement a catch on a higher level or at the plugin + throw new Error("Cannot extend method " + method + " in Class " + classObj.name); + } + } +}; +/** + * @license + * Lo-Dash 2.4.1 (Custom Build) + * Build: `lodash modern -o ./dist/lodash.js` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre ES5 environments */ + var undefined; + + /** Used to pool arrays and objects used internally */ + var arrayPool = [], + objectPool = []; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ + var keyPrefix = +new Date + ''; + + /** Used as the size when optimizations are enabled for large arrays */ + var largeArraySize = 75; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; + + /** Used to detect and test whitespace */ + var whitespace = ( + // whitespace + ' \t\x0B\f\xA0\ufeff' + + + // line terminators + '\n\r\u2028\u2029' + + + // unicode category "Zs" space separators + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detected named functions */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match leading whitespace and zeros to be removed */ + var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to detect functions containing a `this` reference */ + var reThis = /\bthis\b/; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to assign default `context` object properties */ + var contextProps = [ + 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', + 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', + 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used as an internal `_.debounce` options object */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used as the property descriptor for `__bindData__` */ + var descriptor = { + 'configurable': false, + 'enumerable': false, + 'value': null, + 'writable': false + }; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports` */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.indexOf` without support for binary searches + * or `fromIndex` constraints. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * An implementation of `_.contains` for cache objects that mimics the return + * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache object to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var type = typeof value; + cache = cache.cache; + + if (type == 'boolean' || value == null) { + return cache[value] ? 0 : -1; + } + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value; + cache = (cache = cache[type]) && cache[key]; + + return type == 'object' + ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) + : (cache ? 0 : -1); + } + + /** + * Adds a given value to the corresponding cache object. + * + * @private + * @param {*} value The value to add to the cache. + */ + function cachePush(value) { + var cache = this.cache, + type = typeof value; + + if (type == 'boolean' || value == null) { + cache[value] = true; + } else { + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value, + typeCache = cache[type] || (cache[type] = {}); + + if (type == 'object') { + (typeCache[key] || (typeCache[key] = [])).push(value); + } else { + typeCache[key] = true; + } + } + } + + /** + * Used by `_.max` and `_.min` as the default callback when a given + * collection is a string value. + * + * @private + * @param {string} value The character to inspect. + * @returns {number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` elements, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ac = a.criteria, + bc = b.criteria, + index = -1, + length = ac.length; + + while (++index < length) { + var value = ac[index], + other = bc[index]; + + if (value !== other) { + if (value > other || typeof value == 'undefined') { + return 1; + } + if (value < other || typeof other == 'undefined') { + return -1; + } + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to return the same value for + // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 + // + // This also ensures a stable sort in V8 and other engines. + // See http://code.google.com/p/v8/issues/detail?id=90 + return a.index - b.index; + } + + /** + * Creates a cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [array=[]] The array to search. + * @returns {null|Object} Returns the cache object or `null` if caching should not be used. + */ + function createCache(array) { + var index = -1, + length = array.length, + first = array[0], + mid = array[(length / 2) | 0], + last = array[length - 1]; + + if (first && typeof first == 'object' && + mid && typeof mid == 'object' && last && typeof last == 'object') { + return false; + } + var cache = getObject(); + cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; + + var result = getObject(); + result.array = array; + result.cache = cache; + result.push = cachePush; + + while (++index < length) { + result.push(array[index]); + } + return result; + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Gets an object from the object pool or creates a new one if the pool is empty. + * + * @private + * @returns {Object} The object from the pool. + */ + function getObject() { + return objectPool.pop() || { + 'array': null, + 'cache': null, + 'criteria': null, + 'false': false, + 'index': 0, + 'null': false, + 'number': null, + 'object': null, + 'push': null, + 'string': null, + 'true': false, + 'undefined': false, + 'value': null + }; + } + + /** + * Releases the given array back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Releases the given object back to the object pool. + * + * @private + * @param {Object} [object] The object to release. + */ + function releaseObject(object) { + var cache = object.cache; + if (cache) { + releaseObject(cache); + } + object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; + if (objectPool.length < maxPoolSize) { + objectPool.push(object); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used instead of `Array#slice` to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|string} collection The collection to slice. + * @param {number} start The start index. + * @param {number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new `lodash` function using the given context object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} [context=root] The context object. + * @returns {Function} Returns the `lodash` function. + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See http://es5.github.io/#x11.1.5. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references */ + var Array = context.Array, + Boolean = context.Boolean, + Date = context.Date, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var objectProto = Object.prototype; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = context._; + + /** Used to resolve the internal [[Class]] of values */ + var toString = objectProto.toString; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + /** Native method shortcuts */ + var ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + fnToString = Function.prototype.toString, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectProto.hasOwnProperty, + push = arrayRef.push, + setTimeout = context.setTimeout, + splice = arrayRef.splice, + unshift = arrayRef.unshift; + + /** Used to set meta data on functions */ + var defineProperty = (function() { + // IE 8 only accepts DOM elements + try { + var o = {}, + func = isNative(func = Object.defineProperty) && func, + result = func(o, o, o) && func; + } catch(e) { } + return result; + }()); + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = context.isFinite, + nativeIsNaN = context.isNaN, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps the given value to enable intuitive + * method chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * Chaining is supported in custom builds as long as the `value` method is + * implicitly or explicitly included in the build. + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, + * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, + * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, + * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, + * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, + * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, + * and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, + * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, + * `template`, `unescape`, `uniqueId`, and `value` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * provided, otherwise they return unwrapped values. + * + * Explicit chaining can be enabled by using the `_.chain` method. + * + * @name _ + * @constructor + * @category Chaining + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(num) { + * return num * num; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor + return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) + ? value + : new lodashWrapper(value); + } + + /** + * A fast path for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap in a `lodash` instance. + * @param {boolean} chainAll A flag to enable chaining for all methods + * @returns {Object} Returns a `lodash` instance. + */ + function lodashWrapper(value, chainAll) { + this.__chain__ = !!chainAll; + this.__wrapped__ = value; + } + // ensure `new lodashWrapper` is an instance of `lodash` + lodashWrapper.prototype = lodash.prototype; + + /** + * An object used to flag environments features. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.bind` that creates the bound function and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new bound function. + */ + function baseBind(bindData) { + var func = bindData[0], + partialArgs = bindData[2], + thisArg = bindData[4]; + + function bound() { + // `Function#bind` spec + // http://es5.github.io/#x15.3.4.5 + if (partialArgs) { + // avoid `arguments` object deoptimizations by using `slice` instead + // of `Array.prototype.slice.call` and not assigning `arguments` to a + // variable as a ternary expression + var args = slice(partialArgs); + push.apply(args, arguments); + } + // mimic the constructor's `return` behavior + // http://es5.github.io/#x13.2.2 + if (this instanceof bound) { + // ensure `new bound` is an instance of `func` + var thisBinding = baseCreate(func.prototype), + result = func.apply(thisBinding, args || arguments); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisArg, args || arguments); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.clone` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, callback, stackA, stackB) { + if (callback) { + var result = callback(value); + if (typeof result != 'undefined') { + return result; + } + } + // inspect [[Class]] + var isObj = isObject(value); + if (isObj) { + var className = toString.call(value); + if (!cloneableClasses[className]) { + return value; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return new ctor(+value); + + case numberClass: + case stringClass: + return new ctor(value); + + case regexpClass: + result = ctor(value.source, reFlags.exec(value)); + result.lastIndex = value.lastIndex; + return result; + } + } else { + return value; + } + var isArr = isArray(value); + if (isDeep) { + // check for circular references and return corresponding clone + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + result = isArr ? ctor(value.length) : {}; + } + else { + result = isArr ? slice(value) : assign({}, value); + } + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } + // exit for shallow clone + if (!isDeep) { + return result; + } + // add the source value to the stack of traversed objects + // and associate it with its clone + stackA.push(value); + stackB.push(result); + + // recursively populate clone (susceptible to call stack limits) + (isArr ? forEach : forOwn)(value, function(objValue, key) { + result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); + }); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(prototype, properties) { + return isObject(prototype) ? nativeCreate(prototype) : {}; + } + // fallback for browsers without `Object.create` + if (!nativeCreate) { + baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + } + + /** + * The base implementation of `_.createCallback` without support for creating + * "_.pluck" or "_.where" style callbacks. + * + * @private + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + */ + function baseCreateCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + // exit early for no `thisArg` or already bound by `Function#bind` + if (typeof thisArg == 'undefined' || !('prototype' in func)) { + return func; + } + var bindData = func.__bindData__; + if (typeof bindData == 'undefined') { + if (support.funcNames) { + bindData = !func.name; + } + bindData = bindData || !support.funcDecomp; + if (!bindData) { + var source = fnToString.call(func); + if (!support.funcNames) { + bindData = !reFuncName.test(source); + } + if (!bindData) { + // checks if `func` references the `this` keyword and stores the result + bindData = reThis.test(source); + setBindData(func, bindData); + } + } + } + // exit early if there are no `this` references or `func` is bound + if (bindData === false || (bindData !== true && bindData[1] & 1)) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 2: return function(a, b) { + return func.call(thisArg, a, b); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + } + return bind(func, thisArg); + } + + /** + * The base implementation of `createWrapper` that creates the wrapper and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new function. + */ + function baseCreateWrapper(bindData) { + var func = bindData[0], + bitmask = bindData[1], + partialArgs = bindData[2], + partialRightArgs = bindData[3], + thisArg = bindData[4], + arity = bindData[5]; + + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + key = func; + + function bound() { + var thisBinding = isBind ? thisArg : this; + if (partialArgs) { + var args = slice(partialArgs); + push.apply(args, arguments); + } + if (partialRightArgs || isCurry) { + args || (args = slice(arguments)); + if (partialRightArgs) { + push.apply(args, partialRightArgs); + } + if (isCurry && args.length < arity) { + bitmask |= 16 & ~32; + return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); + } + } + args || (args = arguments); + if (isBindKey) { + func = thisBinding[key]; + } + if (this instanceof bound) { + thisBinding = baseCreate(func.prototype); + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.difference` that accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to process. + * @param {Array} [values] The array of values to exclude. + * @returns {Array} Returns a new array of filtered values. + */ + function baseDifference(array, values) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + isLarge = length >= largeArraySize && indexOf === baseIndexOf, + result = []; + + if (isLarge) { + var cache = createCache(values); + if (cache) { + indexOf = cacheIndexOf; + values = cache; + } else { + isLarge = false; + } + } + while (++index < length) { + var value = array[index]; + if (indexOf(values, value) < 0) { + result.push(value); + } + } + if (isLarge) { + releaseObject(values); + } + return result; + } + + /** + * The base implementation of `_.flatten` without support for callback + * shorthands or `thisArg` binding. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. + * @param {number} [fromIndex=0] The index to start from. + * @returns {Array} Returns a new flattened array. + */ + function baseFlatten(array, isShallow, isStrict, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (value && typeof value == 'object' && typeof value.length == 'number' + && (isArray(value) || isArguments(value))) { + // recursively flatten arrays (susceptible to call stack limits) + if (!isShallow) { + value = baseFlatten(value, isShallow, isStrict); + } + var valIndex = -1, + valLength = value.length, + resIndex = result.length; + + result.length += valLength; + while (++valIndex < valLength) { + result[resIndex++] = value[valIndex]; + } + } else if (!isStrict) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.isEqual`, without support for `thisArg` binding, + * that allows partial "_.where" style comparisons. + * + * @private + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `a` objects. + * @param {Array} [stackB=[]] Tracks traversed `b` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { + // used to indicate that when comparing objects, `a` has at least the properties of `b` + if (callback) { + var result = callback(a, b); + if (typeof result != 'undefined') { + return !!result; + } + } + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + var type = typeof a, + otherType = typeof b; + + // exit early for unlike primitive values + if (a === a && + !(a && objectTypes[type]) && + !(b && objectTypes[otherType])) { + return false; + } + // exit early for `null` and `undefined` avoiding ES3's Function#call behavior + // http://es5.github.io/#x15.3.4.4 + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherClass = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherClass == argsClass) { + otherClass = objectClass; + } + if (className != otherClass) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return (a != +a) + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == String(b); + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + var aWrapped = hasOwnProperty.call(a, '__wrapped__'), + bWrapped = hasOwnProperty.call(b, '__wrapped__'); + + if (aWrapped || bWrapped) { + return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); + } + // exit for functions and DOM nodes + if (className != objectClass) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = a.constructor, + ctorB = b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && + !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && + ('constructor' in a && 'constructor' in b) + ) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var size = 0; + result = true; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + // compare lengths to determine if a deep comparison is necessary + length = a.length; + size = b.length; + result = size == length; + + if (result || isWhere) { + // deep compare the contents, ignoring non-numeric properties + while (size--) { + var index = length, + value = b[size]; + + if (isWhere) { + while (index--) { + if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } + } + else { + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); + } + }); + + if (result && !isWhere) { + // ensure both objects have the same number of properties + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // `size` will be `-1` if `a` has more properties than `b` + return (result = --size > -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.merge` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [callback] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + */ + function baseMerge(object, source, callback, stackA, stackB) { + (isArray(source) ? forEach : forOwn)(source, function(source, key) { + var found, + isArr, + result = source, + value = object[key]; + + if (source && ((isArr = isArray(source)) || isPlainObject(source))) { + // avoid merging previously merged cyclic sources + var stackLength = stackA.length; + while (stackLength--) { + if ((found = stackA[stackLength] == source)) { + value = stackB[stackLength]; + break; + } + } + if (!found) { + var isShallow; + if (callback) { + result = callback(value, source); + if ((isShallow = typeof result != 'undefined')) { + value = result; + } + } + if (!isShallow) { + value = isArr + ? (isArray(value) ? value : []) + : (isPlainObject(value) ? value : {}); + } + // add `source` and associated `value` to the stack of traversed objects + stackA.push(source); + stackB.push(value); + + // recursively merge objects and arrays (susceptible to call stack limits) + if (!isShallow) { + baseMerge(value, source, callback, stackA, stackB); + } + } + } + else { + if (callback) { + result = callback(value, source); + if (typeof result == 'undefined') { + result = source; + } + } + if (typeof result != 'undefined') { + value = result; + } + } + object[key] = value; + }); + } + + /** + * The base implementation of `_.random` without argument juggling or support + * for returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns a random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * or `thisArg` binding. + * + * @private + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function} [callback] The function called per iteration. + * @returns {Array} Returns a duplicate-value-free array. + */ + function baseUniq(array, isSorted, callback) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + result = []; + + var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, + seen = (callback || isLarge) ? getArray() : result; + + if (isLarge) { + var cache = createCache(seen); + indexOf = cacheIndexOf; + seen = cache; + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : indexOf(seen, computed) < 0 + ) { + if (callback || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + if (isLarge) { + releaseArray(seen.array); + releaseObject(seen); + } else if (callback) { + releaseArray(seen); + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an object composed + * of keys generated from the results of running each element of the collection + * through a callback. The given `setter` function sets the keys and values + * of the composed object. + * + * @private + * @param {Function} setter The setter function. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter) { + return function(collection, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + setter(result, value, callback(value, index, collection), collection); + } + } else { + forOwn(collection, function(value, key, collection) { + setter(result, value, callback(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that, when called, either curries or invokes `func` + * with an optional `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of method flags to compose. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` + * 8 - `_.curry` (bound) + * 16 - `_.partial` + * 32 - `_.partialRight` + * @param {Array} [partialArgs] An array of arguments to prepend to those + * provided to the new function. + * @param {Array} [partialRightArgs] An array of arguments to append to those + * provided to the new function. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new function. + */ + function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + isPartial = bitmask & 16, + isPartialRight = bitmask & 32; + + if (!isBindKey && !isFunction(func)) { + throw new TypeError; + } + if (isPartial && !partialArgs.length) { + bitmask &= ~16; + isPartial = partialArgs = false; + } + if (isPartialRight && !partialRightArgs.length) { + bitmask &= ~32; + isPartialRight = partialRightArgs = false; + } + var bindData = func && func.__bindData__; + if (bindData && bindData !== true) { + // clone `bindData` + bindData = slice(bindData); + if (bindData[2]) { + bindData[2] = slice(bindData[2]); + } + if (bindData[3]) { + bindData[3] = slice(bindData[3]); + } + // set `thisBinding` is not previously bound + if (isBind && !(bindData[1] & 1)) { + bindData[4] = thisArg; + } + // set if previously bound but not currently (subsequent curried functions) + if (!isBind && bindData[1] & 1) { + bitmask |= 8; + } + // set curried arity if not yet set + if (isCurry && !(bindData[1] & 4)) { + bindData[5] = arity; + } + // append partial left arguments + if (isPartial) { + push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + // append partial right arguments + if (isPartialRight) { + unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + // merge flags + bindData[1] |= bitmask; + return createWrapper.apply(null, bindData); + } + // fast path for `_.bind` + var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; + return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized, this method returns the custom method, otherwise it returns + * the `baseIndexOf` function. + * + * @private + * @returns {Function} Returns the "indexOf" function. + */ + function getIndexOf() { + var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; + return result; + } + + /** + * Checks if `value` is a native function. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. + */ + function isNative(value) { + return typeof value == 'function' && reNative.test(value); + } + + /** + * Sets `this` binding data on a given function. + * + * @private + * @param {Function} func The function to set data on. + * @param {Array} value The data array to set. + */ + var setBindData = !defineProperty ? noop : function(func, value) { + descriptor.value = value; + defineProperty(func, '__bindData__', descriptor); + }; + + /** + * A fallback implementation of `isPlainObject` which checks if a given value + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var ctor, + result; + + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { + return false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {string} match The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == argsClass || false; + } + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == arrayClass || false; + }; + + /** + * A fallback implementation of `Object.keys` which produces an array of the + * given object's own enumerable property names. + * + * @private + * @type Function + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + */ + var shimKeys = function(object) { + var index, iterable = object, result = []; + if (!iterable) return result; + if (!(objectTypes[typeof object])) return result; + for (index in iterable) { + if (hasOwnProperty.call(iterable, index)) { + result.push(index); + } + } + return result + }; + + /** + * Creates an array composed of the own enumerable property names of an object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + return nativeKeys(object); + }; + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /** Used to match HTML entities and HTML characters */ + var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), + reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite property assignments of previous + * sources. If a callback is provided it will be executed to produce the + * assigned values. The callback is bound to `thisArg` and invoked with two + * arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); + * // => { 'name': 'fred', 'employer': 'slate' } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var object = { 'name': 'barney' }; + * defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var assign = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { + var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); + } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { + callback = args[--argsLength]; + } + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; + } + } + } + return result + }; + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects will also + * be cloned, otherwise they will be assigned by reference. If a callback + * is provided it will be executed to produce the cloned values. If the + * callback returns `undefined` cloning will be handled by the method instead. + * The callback is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var shallow = _.clone(characters); + * shallow[0] === characters[0]; + * // => true + * + * var deep = _.clone(characters, true); + * deep[0] === characters[0]; + * // => false + * + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, callback, thisArg) { + // allows working with "Collections" methods without using their `index` + // and `collection` arguments for `isDeep` and `callback` + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = callback; + callback = isDeep; + isDeep = false; + } + return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates a deep clone of `value`. If a callback is provided it will be + * executed to produce the cloned values. If the callback returns `undefined` + * cloning will be handled by the method instead. The callback is bound to + * `thisArg` and invoked with one argument; (value). + * + * Note: This method is loosely based on the structured clone algorithm. Functions + * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and + * objects created by constructors other than `Object` are cloned to plain `Object` objects. + * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var deep = _.cloneDeep(characters); + * deep[0] === characters[0]; + * // => false + * + * var view = { + * 'label': 'docs', + * 'node': element + * }; + * + * var clone = _.cloneDeep(view, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : undefined; + * }); + * + * clone.node == view.node; + * // => false + */ + function cloneDeep(value, callback, thisArg) { + return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property will be ignored. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param- {Object} [guard] Allows working with `_.reduce` without using its + * `key` and `object` arguments as sources. + * @returns {Object} Returns the destination object. + * @example + * + * var object = { 'name': 'barney' }; + * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var defaults = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (typeof result[index] == 'undefined') result[index] = iterable[index]; + } + } + } + return result + }; + + /** + * This method is like `_.findIndex` except that it returns the key of the + * first element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': false }, + * 'fred': { 'age': 40, 'blocked': true }, + * 'pebbles': { 'age': 1, 'blocked': false } + * }; + * + * _.findKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (property order is not guaranteed across environments) + * + * // using "_.where" callback shorthand + * _.findKey(characters, { 'age': 1 }); + * // => 'pebbles' + * + * // using "_.pluck" callback shorthand + * _.findKey(characters, 'blocked'); + * // => 'fred' + */ + function findKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwn(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.findKey` except that it iterates over elements + * of a `collection` in the opposite order. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': true }, + * 'fred': { 'age': 40, 'blocked': false }, + * 'pebbles': { 'age': 1, 'blocked': true } + * }; + * + * _.findLastKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles`, assuming `_.findKey` returns `barney` + * + * // using "_.where" callback shorthand + * _.findLastKey(characters, { 'age': 40 }); + * // => 'fred' + * + * // using "_.pluck" callback shorthand + * _.findLastKey(characters, 'blocked'); + * // => 'pebbles' + */ + function findLastKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwnRight(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * Iterates over own and inherited enumerable properties of an object, + * executing the callback for each property. The callback is bound to `thisArg` + * and invoked with three arguments; (value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forIn(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) + */ + var forIn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + for (index in iterable) { + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forIn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forInRight(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' + */ + function forInRight(object, callback, thisArg) { + var pairs = []; + + forIn(object, function(value, key) { + pairs.push(key, value); + }); + + var length = pairs.length; + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + if (callback(pairs[length--], pairs[length], object) === false) { + break; + } + } + return object; + } + + /** + * Iterates over own enumerable properties of an object, executing the callback + * for each property. The callback is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) + */ + var forOwn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forOwn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' + */ + function forOwnRight(object, callback, thisArg) { + var props = keys(object), + length = props.length; + + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + var key = props[length]; + if (callback(object[key], key, object) === false) { + break; + } + } + return object; + } + + /** + * Creates a sorted array of property names of all enumerable properties, + * own and inherited, of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified property name exists as a direct property of `object`, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to check. + * @returns {boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, key) { + return object ? hasOwnProperty.call(object, key) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'fred', 'second': 'barney' }); + * // => { 'fred': 'first', 'barney': 'second' } + */ + function invert(object) { + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + result[object[key]] = key; + } + return result; + } + + /** + * Checks if `value` is a boolean value. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + value && typeof value == 'object' && toString.call(value) == boolClass || false; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return value && typeof value == 'object' && toString.call(value) == dateClass || false; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value && value.nodeType === 1 || false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + var result = true; + if (!value) { + return result; + } + var className = toString.call(value), + length = value.length; + + if ((className == arrayClass || className == stringClass || className == argsClass ) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; + } + forOwn(value, function() { + return (result = false); + }); + return result; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. If a callback is provided it will be executed + * to compare values. If the callback returns `undefined` comparisons will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (a, b). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'name': 'fred' }; + * var copy = { 'name': 'fred' }; + * + * object == copy; + * // => false + * + * _.isEqual(object, copy); + * // => true + * + * var words = ['hello', 'goodbye']; + * var otherWords = ['hi', 'goodbye']; + * + * _.isEqual(words, otherWords, function(a, b) { + * var reGreet = /^(?:hello|hi)$/i, + * aGreet = _.isString(a) && reGreet.test(a), + * bGreet = _.isString(b) && reGreet.test(b); + * + * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; + * }); + * // => true + */ + function isEqual(a, b, callback, thisArg) { + return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite` which will return true for + * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is finite, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); + } + + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.io/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return !!(value && objectTypes[typeof value]); + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN` which will return `true` for + * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || + value && typeof value == 'object' && toString.call(value) == numberClass || false; + } + + /** + * Checks if `value` is an object created by the `Object` constructor. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * _.isPlainObject(new Shape); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && toString.call(value) == objectClass)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/fred/); + * // => true + */ + function isRegExp(value) { + return value && typeof value == 'object' && toString.call(value) == regexpClass || false; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('fred'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || + value && typeof value == 'object' && toString.call(value) == stringClass || false; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new object with values of the results of each `callback` execution. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + * + * var characters = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // using "_.pluck" callback shorthand + * _.mapValues(characters, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } + */ + function mapValues(object, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + forOwn(object, function(value, key, object) { + result[key] = callback(value, key, object); + }); + return result; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * will overwrite property assignments of previous sources. If a callback is + * provided it will be executed to produce the merged values of the destination + * and source properties. If the callback returns `undefined` merging will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'characters': [ + * { 'name': 'barney' }, + * { 'name': 'fred' } + * ] + * }; + * + * var ages = { + * 'characters': [ + * { 'age': 36 }, + * { 'age': 40 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object) { + var args = arguments, + length = 2; + + if (!isObject(object)) { + return object; + } + // allows working with `_.reduce` and `_.reduceRight` without using + // their `index` and `collection` arguments + if (typeof args[2] != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + var callback = baseCreateCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + var sources = slice(arguments, 1, length), + index = -1, + stackA = getArray(), + stackB = getArray(); + + while (++index < length) { + baseMerge(object, sources[index], callback, stackA, stackB); + } + releaseArray(stackA); + releaseArray(stackB); + return object; + } + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` omitting the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The properties to omit or the + * function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); + * // => { 'name': 'fred' } + * + * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { + * return typeof value == 'number'; + * }); + * // => { 'name': 'fred' } + */ + function omit(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var props = []; + forIn(object, function(value, key) { + props.push(key); + }); + props = baseDifference(props, baseFlatten(arguments, true, false, 1)); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + result[key] = object[key]; + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (!callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * Creates a two dimensional array of an object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` picking the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The function called per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); + * // => { 'name': 'fred' } + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'fred' } + */ + function pick(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var index = -1, + props = baseFlatten(arguments, true, false, 1), + length = isObject(object) ? props.length : 0; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * An alternative to `_.reduce` this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable properties through a callback, with each callback execution + * potentially mutating the `accumulator` object. The callback is bound to + * `thisArg` and invoked with four arguments; (accumulator, value, key, object). + * Callbacks may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { + * num *= num; + * if (num % 2) { + * return result.push(num) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, callback, accumulator, thisArg) { + var isArr = isArray(object); + if (accumulator == null) { + if (isArr) { + accumulator = []; + } else { + var ctor = object && object.constructor, + proto = ctor && ctor.prototype; + + accumulator = baseCreate(proto); + } + } + if (callback) { + callback = lodash.createCallback(callback, thisArg, 4); + (isArr ? forEach : forOwn)(object, function(value, index, object) { + return callback(accumulator, value, index, object); + }); + } + return accumulator; + } + + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] (property order is not guaranteed across environments) + */ + function values(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array of elements from the specified indexes, or keys, of the + * `collection`. Indexes may be specified as individual arguments or as arrays + * of indexes. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` + * to retrieve, specified as individual indexes or arrays of indexes. + * @returns {Array} Returns a new array of elements corresponding to the + * provided indexes. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['fred', 'barney', 'pebbles'], 0, 2); + * // => ['fred', 'pebbles'] + */ + function at(collection) { + var args = arguments, + index = -1, + props = baseFlatten(args, true, false, 1), + length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, + result = Array(length); + + while(++index < length) { + result[index] = collection[props[index]]; + } + return result; + } + + /** + * Checks if a given value is present in a collection using strict equality + * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the + * offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {*} target The value to check for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.contains('pebbles', 'eb'); + * // => true + */ + function contains(collection, target, fromIndex) { + var index = -1, + indexOf = getIndexOf(), + length = collection ? collection.length : 0, + result = false; + + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; + if (isArray(collection)) { + result = indexOf(collection, target, fromIndex) > -1; + } else if (typeof length == 'number') { + result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; + } else { + forOwn(collection, function(value) { + if (++index >= fromIndex) { + return !(result = value === target); + } + }); + } + return result; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through the callback. The corresponding value + * of each key is the number of times the key was returned by the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + + /** + * Checks if the given callback returns truey value for **all** elements of + * a collection. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if all elements passed the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes']); + * // => false + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.every(characters, 'age'); + * // => true + * + * // using "_.where" callback shorthand + * _.every(characters, { 'age': 36 }); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return (result = !!callback(value, index, collection)); + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning an array of all elements + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.filter(characters, 'blocked'); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + * + * // using "_.where" callback shorthand + * _.filter(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning the first element that + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias detect, findWhere + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.find(characters, function(chr) { + * return chr.age < 40; + * }); + * // => { 'name': 'barney', 'age': 36, 'blocked': false } + * + * // using "_.where" callback shorthand + * _.find(characters, { 'age': 1 }); + * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } + * + * // using "_.pluck" callback shorthand + * _.find(characters, 'blocked'); + * // => { 'name': 'fred', 'age': 40, 'blocked': true } + */ + function find(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + return value; + } + } + } else { + var result; + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + } + + /** + * This method is like `_.find` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(num) { + * return num % 2 == 1; + * }); + * // => 3 + */ + function findLast(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forEachRight(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + + /** + * Iterates over elements of a collection, executing the callback for each + * element. The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * Note: As with other "Collections" methods, objects with a `length` property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); + * // => logs each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + * // => logs each number and returns the object (property order is not guaranteed across environments) + */ + function forEach(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + forOwn(collection, callback); + } + return collection; + } + + /** + * This method is like `_.forEach` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); + * // => logs each number from right to left and returns '3,2,1' + */ + function forEachRight(collection, callback, thisArg) { + var length = collection ? collection.length : 0; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (length--) { + if (callback(collection[length], length, collection) === false) { + break; + } + } + } else { + var props = keys(collection); + length = props.length; + forOwn(collection, function(value, key, collection) { + key = props ? props[--length] : --length; + return callback(collection[key], key, collection); + }); + } + return collection; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of a collection through the callback. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false` + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using "_.pluck" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of the collection through the given callback. The corresponding + * value of each key is the last element responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keys = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keys, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method named by `methodName` on each element in the `collection` + * returning an array of the results of each invoked method. Additional arguments + * will be provided to each invoked method. If `methodName` is a function it + * will be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {...*} [arg] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); + }); + return result; + } + + /** + * Creates an array of values by running each element in the collection + * through the callback. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (property order is not guaranteed across environments) + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(characters, 'name'); + * // => ['barney', 'fred'] + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + if (typeof length == 'number') { + var result = Array(length); + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + result = []; + forOwn(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of a collection. If the collection is empty or + * falsey `-Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.max(characters, function(chr) { return chr.age; }); + * // => { 'name': 'fred', 'age': 40 }; + * + * // using "_.pluck" callback shorthand + * _.max(characters, 'age'); + * // => { 'name': 'fred', 'age': 40 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value > result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the minimum value of a collection. If the collection is empty or + * falsey `Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.min(characters, function(chr) { return chr.age; }); + * // => { 'name': 'barney', 'age': 36 }; + * + * // using "_.pluck" callback shorthand + * _.min(characters, 'age'); + * // => { 'name': 'barney', 'age': 36 }; + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value < result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in the collection. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {string} property The name of the property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.pluck(characters, 'name'); + * // => ['barney', 'fred'] + */ + var pluck = map; + + /** + * Reduces a collection to a value which is the accumulated result of running + * each element in the collection through the callback, where each successive + * callback execution consumes the return value of the previous execution. If + * `accumulator` is not provided the first element of the collection will be + * used as the initial `accumulator` value. The callback is bound to `thisArg` + * and invoked with four arguments; (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function reduce(collection, callback, accumulator, thisArg) { + if (!collection) return accumulator; + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + + var index = -1, + length = collection.length; + + if (typeof length == 'number') { + if (noaccum) { + accumulator = collection[++index]; + } + while (++index < length) { + accumulator = callback(accumulator, collection[index], index, collection); + } + } else { + forOwn(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection) + }); + } + return accumulator; + } + + /** + * This method is like `_.reduce` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + forEachRight(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter` this method returns the elements of a + * collection that the callback does **not** return truey for. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that failed the callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.reject(characters, 'blocked'); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + * + * // using "_.where" callback shorthand + * _.reject(characters, { 'age': 36 }); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + */ + function reject(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Retrieves a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Allows working with functions like `_.map` + * without using their `index` arguments as `n`. + * @returns {Array} Returns the random sample(s) of `collection`. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (collection && typeof collection.length != 'number') { + collection = values(collection); + } + if (n == null || guard) { + return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(nativeMax(0, n), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates + * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + var rand = baseRandom(0, ++index); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the callback returns a truey value for **any** element of a + * collection. The function returns as soon as it finds a passing value and + * does not iterate over the entire collection. The callback is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if any element passed the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.some(characters, 'blocked'); + * // => true + * + * // using "_.where" callback shorthand + * _.some(characters, { 'age': 1 }); + * // => false + */ + function some(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return !(result = callback(value, index, collection)); + }); + } + return !!result; + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through the callback. This method + * performs a stable sort, that is, it will preserve the original sort order + * of equal elements. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an array of property names is provided for `callback` the collection + * will be sorted by each property value. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 26 }, + * { 'name': 'fred', 'age': 30 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(_.sortBy(characters, 'age'), _.values); + * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] + * + * // sorting by multiple properties + * _.map(_.sortBy(characters, ['name', 'age']), _.values); + * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + */ + function sortBy(collection, callback, thisArg) { + var index = -1, + isArr = isArray(callback), + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + if (!isArr) { + callback = lodash.createCallback(callback, thisArg, 3); + } + forEach(collection, function(value, key, collection) { + var object = result[++index] = getObject(); + if (isArr) { + object.criteria = map(callback, function(key) { return value[key]; }); + } else { + (object.criteria = getArray())[0] = callback(value, key, collection); + } + object.index = index; + object.value = value; + }); + + length = result.length; + result.sort(compareAscending); + while (length--) { + var object = result[length]; + result[length] = object.value; + if (!isArr) { + releaseArray(object.criteria); + } + releaseObject(object); + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + if (collection && typeof collection.length == 'number') { + return slice(collection); + } + return values(collection); + } + + /** + * Performs a deep comparison of each element in a `collection` to the given + * `properties` object, returning an array of all elements that have equivalent + * property values. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Object} props The object of property values to filter by. + * @returns {Array} Returns a new array of elements that have the given properties. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.where(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] + * + * _.where(characters, { 'pets': ['dino'] }); + * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] + */ + var where = filter; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using strict + * equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + return baseDifference(array, baseFlatten(arguments, true, true, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.findIndex(characters, function(chr) { + * return chr.age < 20; + * }); + * // => 2 + * + * // using "_.where" callback shorthand + * _.findIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findIndex(characters, 'blocked'); + * // => 1 + */ + function findIndex(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + if (callback(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of a `collection` from right to left. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': true }, + * { 'name': 'fred', 'age': 40, 'blocked': false }, + * { 'name': 'pebbles', 'age': 1, 'blocked': true } + * ]; + * + * _.findLastIndex(characters, function(chr) { + * return chr.age > 30; + * }); + * // => 1 + * + * // using "_.where" callback shorthand + * _.findLastIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findLastIndex(characters, 'blocked'); + * // => 2 + */ + function findLastIndex(array, callback, thisArg) { + var length = array ? array.length : 0; + callback = lodash.createCallback(callback, thisArg, 3); + while (length--) { + if (callback(array[length], length, array)) { + return length; + } + } + return -1; + } + + /** + * Gets the first element or first `n` elements of an array. If a callback + * is provided elements at the beginning of the array are returned as long + * as the callback returns truey. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the first element(s) of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([1, 2, 3], 2); + * // => [1, 2] + * + * _.first([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [1, 2] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.first(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); + * // => ['barney', 'fred'] + */ + function first(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = -1; + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[0] : undefined; + } + } + return slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truey, the array will only be flattened a single level. If a callback + * is provided each element of the array is passed through the callback before + * flattening. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + * + * var characters = [ + * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(characters, 'pets'); + * // => ['hoppy', 'baby puss', 'dino'] + */ + function flatten(array, isShallow, callback, thisArg) { + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; + isShallow = false; + } + if (callback != null) { + array = map(array, callback, thisArg); + } + return baseFlatten(array, isShallow); + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the array is already sorted + * providing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + if (typeof fromIndex == 'number') { + var length = array ? array.length : 0; + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); + } else if (fromIndex) { + var index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + return baseIndexOf(array, value, fromIndex); + } + + /** + * Gets all but the last element or last `n` elements of an array. If a + * callback is provided elements at the end of the array are excluded from + * the result as long as the callback returns truey. The callback is bound + * to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + * + * _.initial([1, 2, 3], 2); + * // => [1] + * + * _.initial([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [1] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.initial(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); + * // => ['barney', 'fred'] + */ + function initial(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : callback || n; + } + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Creates an array of unique values present in all provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of shared values. + * @example + * + * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = getArray(), + indexOf = getIndexOf(), + trustIndexOf = indexOf === baseIndexOf, + seen = getArray(); + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArray(value) || isArguments(value)) { + args.push(value); + caches.push(trustIndexOf && value.length >= largeArraySize && + createCache(argsIndex ? args[argsIndex] : seen)); + } + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + result = []; + + outer: + while (++index < length) { + var cache = caches[0]; + value = array[index]; + + if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { + argsIndex = argsLength; + (cache || seen).push(value); + while (--argsIndex) { + cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { + continue outer; + } + } + result.push(value); + } + } + while (argsLength--) { + cache = caches[argsLength]; + if (cache) { + releaseObject(cache); + } + } + releaseArray(caches); + releaseArray(seen); + return result; + } + + /** + * Gets the last element or last `n` elements of an array. If a callback is + * provided elements at the end of the array are returned as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the last element(s) of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + * + * _.last([1, 2, 3], 2); + * // => [2, 3] + * + * _.last([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [2, 3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.last(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.last(characters, { 'employer': 'na' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function last(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[length - 1] : undefined; + } + } + return slice(array, nativeMax(0, length - n)); + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from the given array using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {...*} [value] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull(array) { + var args = arguments, + argsIndex = 0, + argsLength = args.length, + length = array ? array.length : 0; + + while (++argsIndex < argsLength) { + var index = -1, + value = args[argsIndex]; + while (++index < length) { + if (array[index] === value) { + splice.call(array, index--, 1); + length--; + } + } + } + return array; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `end`. If `start` is less than `stop` a + * zero-length range is created unless a negative `step` is specified. + * + * @static + * @memberOf _ + * @category Arrays + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = typeof step == 'number' ? step : (+step || 1); + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so engines like Chakra and V8 avoid slower modes + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / (step || 1))), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * Removes all elements from an array that the callback returns truey for + * and returns an array of removed elements. The callback is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4, 5, 6]; + * var evens = _.remove(array, function(num) { return num % 2 == 0; }); + * + * console.log(array); + * // => [1, 3, 5] + * + * console.log(evens); + * // => [2, 4, 6] + */ + function remove(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = []; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (callback(value, index, array)) { + result.push(value); + splice.call(array, index--, 1); + length--; + } + } + return result; + } + + /** + * The opposite of `_.initial` this method gets all but the first element or + * first `n` elements of an array. If a callback function is provided elements + * at the beginning of the array are excluded from the result as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + * + * _.rest([1, 2, 3], 2); + * // => [3] + * + * _.rest([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.rest(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.rest(characters, { 'employer': 'slate' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function rest(array, callback, thisArg) { + if (typeof callback != 'number' && callback != null) { + var n = 0, + index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); + } + return slice(array, n); + } + + /** + * Uses a binary search to determine the smallest index at which a value + * should be inserted into a given sorted array in order to maintain the sort + * order of the array. If a callback is provided it will be executed for + * `value` and each element of `array` to compute their sort ranking. The + * callback is bound to `thisArg` and invoked with one argument; (value). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * // using "_.pluck" callback shorthand + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better inlining in Firefox + callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; + value = callback(value); + + while (low < high) { + var mid = (low + high) >>> 1; + (callback(array[mid]) < value) + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of combined values. + * @example + * + * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2, 3, 5, 4] + */ + function union() { + return baseUniq(baseFlatten(arguments, true, true)); + } + + /** + * Creates a duplicate-value-free version of an array using strict equality + * for comparisons, i.e. `===`. If the array is sorted, providing + * `true` for `isSorted` will use a faster algorithm. If a callback is provided + * each element of `array` is passed through the callback before uniqueness + * is computed. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); + * // => ['A', 'b', 'C'] + * + * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2.5, 3] + * + * // using "_.pluck" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, callback, thisArg) { + // juggle arguments + if (typeof isSorted != 'boolean' && isSorted != null) { + thisArg = callback; + callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; + isSorted = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg, 3); + } + return baseUniq(array, isSorted, callback); + } + + /** + * Creates an array excluding all provided values using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {...*} [value] The values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + return baseDifference(array, slice(arguments, 1)); + } + + /** + * Creates an array that is the symmetric difference of the provided arrays. + * See http://en.wikipedia.org/wiki/Symmetric_difference. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of values. + * @example + * + * _.xor([1, 2, 3], [5, 2, 1, 4]); + * // => [3, 5, 4] + * + * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); + * // => [1, 4, 5] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArray(array) || isArguments(array)) { + var result = result + ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) + : array; + } + } + return result || []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second + * elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @alias unzip + * @category Arrays + * @param {...Array} [array] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + function zip() { + var array = arguments.length > 1 ? arguments : arguments[0], + index = -1, + length = array ? max(pluck(array, 'length')) : 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = pluck(array, index); + } + return result; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Provide + * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` + * or two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @alias object + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + if (!values && length && !isArray(keys[0])) { + values = []; + } + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that executes `func`, with the `this` binding and + * arguments of the created function, only after being called `n` times. + * + * @static + * @memberOf _ + * @category Functions + * @param {number} n The number of times the function must be called before + * `func` is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('Done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'Done saving!', after all saves have completed + */ + function after(n, func) { + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * provided to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'fred' }, 'hi'); + * func(); + * // => 'hi fred' + */ + function bind(func, thisArg) { + return arguments.length > 2 + ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) + : createWrapper(func, 1, null, null, thisArg); + } + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all the function properties + * of `object` will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...string} [methodName] The object method names to + * bind, specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { console.log('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs', when the button is clicked + */ + function bindAll(object) { + var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), + index = -1, + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = createWrapper(object[key], 1, null, null, object); + } + return object; + } + + /** + * Creates a function that, when called, invokes the method at `object[key]` + * and prepends any additional `bindKey` arguments to those provided to the bound + * function. This method differs from `_.bind` by allowing bound functions to + * reference methods that will be redefined or don't yet exist. + * See http://michaux.ca/articles/lazy-function-definition-pattern. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'name': 'fred', + * 'greet': function(greeting) { + * return greeting + ' ' + this.name; + * } + * }; + * + * var func = _.bindKey(object, 'greet', 'hi'); + * func(); + * // => 'hi fred' + * + * object.greet = function(greeting) { + * return greeting + 'ya ' + this.name + '!'; + * }; + * + * func(); + * // => 'hiya fred!' + */ + function bindKey(object, key) { + return arguments.length > 2 + ? createWrapper(key, 19, slice(arguments, 2), null, object) + : createWrapper(key, 3, null, null, object); + } + + /** + * Creates a function that is the composition of the provided functions, + * where each function consumes the return value of the function that follows. + * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {...Function} [func] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var realNameMap = { + * 'pebbles': 'penelope' + * }; + * + * var format = function(name) { + * name = realNameMap[name.toLowerCase()] || name; + * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); + * }; + * + * var greet = function(formatted) { + * return 'Hiya ' + formatted + '!'; + * }; + * + * var welcome = _.compose(greet, format); + * welcome('pebbles'); + * // => 'Hiya Penelope!' + */ + function compose() { + var funcs = arguments, + length = funcs.length; + + while (length--) { + if (!isFunction(funcs[length])) { + throw new TypeError; + } + } + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function which accepts one or more arguments of `func` that when + * invoked either executes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` can be specified + * if `func.length` is not sufficient. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @returns {Function} Returns the new curried function. + * @example + * + * var curried = _.curry(function(a, b, c) { + * console.log(a + b + c); + * }); + * + * curried(1)(2)(3); + * // => 6 + * + * curried(1, 2)(3); + * // => 6 + * + * curried(1, 2, 3); + * // => 6 + */ + function curry(func, arity) { + arity = typeof arity == 'number' ? arity : (+arity || func.length); + return createWrapper(func, 4, null, null, null, arity); + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. + * Provide an options object to indicate that `func` should be invoked on + * the leading and/or trailing edge of the `wait` timeout. Subsequent calls + * to the debounced function will return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {number} wait The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * var lazyLayout = _.debounce(calculateLayout, 150); + * jQuery(window).on('resize', lazyLayout); + * + * // execute `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * }); + * + * // ensure `batchLog` is executed once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * source.addEventListener('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * }, false); + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + wait = nativeMax(0, wait) || 0; + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); + trailing = 'trailing' in options ? options.trailing : trailing; + } + var delayed = function() { + var remaining = wait - (now() - stamp); + if (remaining <= 0) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + }; + + var maxDelayed = function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + }; + + return function() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + }; + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { console.log(text); }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + function defer(func) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay execution. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { console.log(text); }, 1000, 'later'); + * // => logs 'later' after one second + */ + function delay(func, wait) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it will be used to determine the cache key for storing the result + * based on the arguments provided to the memoized function. By default, the + * first argument provided to the memoized function is used as the cache key. + * The `func` is executed with the `this` binding of the memoized function. + * The result cache is exposed as the `cache` property on the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + * + * fibonacci(9) + * // => 34 + * + * var data = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // modifying the result cache + * var get = _.memoize(function(name) { return data[name]; }, _.identity); + * get('pebbles'); + * // => { 'name': 'pebbles', 'age': 1 } + * + * get.cache.pebbles.name = 'penelope'; + * get('pebbles'); + * // => { 'name': 'penelope', 'age': 1 } + */ + function memoize(func, resolver) { + if (!isFunction(func)) { + throw new TypeError; + } + var memoized = function() { + var cache = memoized.cache, + key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; + + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + } + memoized.cache = {}; + return memoized; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` executes `createApplication` once + */ + function once(func) { + var ran, + result; + + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when called, invokes `func` with any additional + * `partial` arguments prepended to those provided to the new function. This + * method is similar to `_.bind` except it does **not** alter the `this` binding. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { return greeting + ' ' + name; }; + * var hi = _.partial(greet, 'hi'); + * hi('fred'); + * // => 'hi fred' + */ + function partial(func) { + return createWrapper(func, 16, slice(arguments, 1)); + } + + /** + * This method is like `_.partial` except that `partial` arguments are + * appended to those provided to the new function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var defaultsDeep = _.partialRight(_.merge, _.defaults); + * + * var options = { + * 'variable': 'data', + * 'imports': { 'jq': $ } + * }; + * + * defaultsDeep(options, _.templateSettings); + * + * options.variable + * // => 'data' + * + * options.imports + * // => { '_': _, 'jq': $ } + */ + function partialRight(func) { + return createWrapper(func, 32, null, slice(arguments, 1)); + } + + /** + * Creates a function that, when executed, will only call the `func` function + * at most once per every `wait` milliseconds. Provide an options object to + * indicate that `func` should be invoked on the leading and/or trailing edge + * of the `wait` timeout. Subsequent calls to the throttled function will + * return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {number} wait The number of milliseconds to throttle executions to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + * + * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? options.leading : leading; + trailing = 'trailing' in options ? options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = wait; + debounceOptions.trailing = trailing; + + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Additional arguments provided to the function are appended + * to those provided to the wrapper function. The wrapper is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('Fred, Wilma, & Pebbles'); + * // => '

Fred, Wilma, & Pebbles

' + */ + function wrap(value, wrapper) { + return createWrapper(wrapper, 16, [value]); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new function. + * @example + * + * var object = { 'name': 'fred' }; + * var getter = _.constant(object); + * getter() === object; + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * Produces a callback bound to an optional `thisArg`. If `func` is a property + * name the created callback will return the property value for a given element. + * If `func` is an object the created callback will return `true` for elements + * that contain the equivalent object properties, otherwise it will return `false`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // wrap to create custom callback shorthands + * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { + * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); + * return !match ? func(callback, thisArg) : function(object) { + * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; + * }; + * }); + * + * _.filter(characters, 'age__gt38'); + * // => [{ 'name': 'fred', 'age': 40 }] + */ + function createCallback(func, thisArg, argCount) { + var type = typeof func; + if (func == null || type == 'function') { + return baseCreateCallback(func, thisArg, argCount); + } + // handle "_.pluck" style callback shorthands + if (type != 'object') { + return property(func); + } + var props = keys(func), + key = props[0], + a = func[key]; + + // handle "_.where" style callback shorthands + if (props.length == 1 && a === a && !isObject(a)) { + // fast path the common case of providing an object with a single + // property containing a primitive value + return function(object) { + var b = object[key]; + return a === b && (a !== 0 || (1 / a == 1 / b)); + }; + } + return function(object) { + var length = props.length, + result = false; + + while (length--) { + if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { + break; + } + } + return result; + }; + } + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} string The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('Fred, Wilma, & Pebbles'); + * // => 'Fred, Wilma, & Pebbles' + */ + function escape(string) { + return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'name': 'fred' }; + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds function properties of a source object to the destination object. + * If `object` is a function methods will be added to its prototype as well. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Function|Object} [object=lodash] object The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options] The options object. + * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. + * @example + * + * function capitalize(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * + * _.mixin({ 'capitalize': capitalize }); + * _.capitalize('fred'); + * // => 'Fred' + * + * _('fred').capitalize().value(); + * // => 'Fred' + * + * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); + * _('fred').capitalize(); + * // => 'Fred' + */ + function mixin(object, source, options) { + var chain = true, + methodNames = source && functions(source); + + if (!source || (!options && !methodNames.length)) { + if (options == null) { + options = source; + } + ctor = lodashWrapper; + source = object; + object = lodash; + methodNames = functions(source); + } + if (options === false) { + chain = false; + } else if (isObject(options) && 'chain' in options) { + chain = options.chain; + } + var ctor = object, + isFunc = isFunction(ctor); + + forEach(methodNames, function(methodName) { + var func = object[methodName] = source[methodName]; + if (isFunc) { + ctor.prototype[methodName] = function() { + var chainAll = this.__chain__, + value = this.__wrapped__, + args = [value]; + + push.apply(args, arguments); + var result = func.apply(object, args); + if (chain || chainAll) { + if (value === result && isObject(result)) { + return this; + } + result = new ctor(result); + result.__chain__ = chainAll; + } + return result; + }; + } + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + context._ = oldDash; + return this; + } + + /** + * A no-operation function. + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var object = { 'name': 'fred' }; + * _.noop(object) === undefined; + * // => true + */ + function noop() { + // no operation performed + } + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var stamp = _.now(); + * _.defer(function() { console.log(_.now() - stamp); }); + * // => logs the number of milliseconds it took for the deferred function to be called + */ + var now = isNative(now = Date.now) && now || function() { + return new Date().getTime(); + }; + + /** + * Converts the given value into an integer of the specified radix. + * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the + * `value` is a hexadecimal, in which case a `radix` of `16` is used. + * + * Note: This method avoids differences in native ES3 and ES5 `parseInt` + * implementations. See http://es5.github.io/#E. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} value The value to parse. + * @param {number} [radix] The radix used to interpret the value to parse. + * @returns {number} Returns the new integer value. + * @example + * + * _.parseInt('08'); + * // => 8 + */ + var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { + // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` + return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); + }; + + /** + * Creates a "_.pluck" style function, which returns the `key` value of a + * given object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} key The name of the property to retrieve. + * @returns {Function} Returns the new function. + * @example + * + * var characters = [ + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 36 } + * ]; + * + * var getName = _.property('name'); + * + * _.map(characters, getName); + * // => ['barney', 'fred'] + * + * _.sortBy(characters, getName); + * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] + */ + function property(key) { + return function(object) { + return object[key]; + }; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number will be + * returned. If `floating` is truey or either `min` or `max` are floats a + * floating-point number will be returned instead of an integer. + * + * @static + * @memberOf _ + * @category Utilities + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating=false] Specify returning a floating-point number. + * @returns {number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (typeof min == 'boolean' && noMax) { + floating = min; + min = 1; + } + else if (!noMax && typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); + } + return baseRandom(min, max); + } + + /** + * Resolves the value of property `key` on `object`. If `key` is a function + * it will be invoked with the `this` binding of `object` and its result returned, + * else the property value is returned. If `object` is falsey then `undefined` + * is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to resolve. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, key) { + if (object) { + var value = object[key]; + return isFunction(value) ? object[key]() : value; + } + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build, `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * For more information on precompiling templates see: + * http://lodash.com/custom-builds + * + * For more information on Chrome extension sandboxes see: + * http://developer.chrome.com/stable/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} text The template text. + * @param {Object} data The data object used to populate the text. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as local variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [sourceURL] The sourceURL of the template's compiled source. + * @param {string} [variable] The data object variable name. + * @returns {Function|string} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'fred' }); + * // => 'hello fred' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': ' + + + + + + + + + + + + + + +

EXAMPLE OF EXECUTION PMDYNAFORM

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

ProcessMaker - PMDynaform

+ Please enter a valid json. (This json can be obtained from the form editor ProcessMaker). More examples in pmDynaform/data
+
+ +
+
+
© Copyright 2000 - 2015 Colosa, Inc. www.colosa.com
+
+
+ + + + +
+
+
+
    + + diff --git a/workflow/public_html/lib/pmdynaform/build/form2.html b/workflow/public_html/lib/pmdynaform/build/form2.html new file mode 100644 index 000000000..aa343cf30 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/form2.html @@ -0,0 +1,2047 @@ + + + + PMDynaform + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    ProcessMaker - PMDynaform

    + Please enter a valid json. (This json can be obtained from the form editor ProcessMaker). More examples in pmDynaform/data
    +
    + +
    +
    +
    © Copyright 2000 - 2015 Colosa, Inc. www.colosa.com
    +
    +
    + + + +
    +
    +
    + + diff --git a/workflow/public_html/lib/pmdynaform/build/formRest.html b/workflow/public_html/lib/pmdynaform/build/formRest.html new file mode 100644 index 000000000..d06e17f26 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/formRest.html @@ -0,0 +1,2144 @@ + + + + PMDynaform + + + + + + + + + + + + + + + + + +
    + +
    +

    Information for RestClient

    +

    Inputs workpace, project, server and tokens forRestClient

    + +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/workflow/public_html/lib/pmdynaform/build/gridRest.html b/workflow/public_html/lib/pmdynaform/build/gridRest.html new file mode 100644 index 000000000..b557a60e5 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/gridRest.html @@ -0,0 +1,2154 @@ + + + + PMDynaform + + + + + + + + + + + + + + + + + +
    + +
    +

    Information for RestClient

    +

    Inputs workpace, project, server and tokens forRestClient

    + +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/workflow/public_html/lib/pmdynaform/build/img/add-row.png b/workflow/public_html/lib/pmdynaform/build/img/add-row.png new file mode 100644 index 000000000..79ec67e2c Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/add-row.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/audio.png b/workflow/public_html/lib/pmdynaform/build/img/audio.png new file mode 100644 index 000000000..1132a738f Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/audio.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/compress.png b/workflow/public_html/lib/pmdynaform/build/img/compress.png new file mode 100644 index 000000000..5b7d3fde6 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/compress.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/doc.png b/workflow/public_html/lib/pmdynaform/build/img/doc.png new file mode 100644 index 000000000..7427fc3df Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/doc.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/file.png b/workflow/public_html/lib/pmdynaform/build/img/file.png new file mode 100644 index 000000000..53e52c617 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/file.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/geoMap.jpg b/workflow/public_html/lib/pmdynaform/build/img/geoMap.jpg new file mode 100644 index 000000000..eae476926 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/geoMap.jpg differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/image.png b/workflow/public_html/lib/pmdynaform/build/img/image.png new file mode 100644 index 000000000..80f807c3d Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/image.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/loading.gif b/workflow/public_html/lib/pmdynaform/build/img/loading.gif new file mode 100644 index 000000000..20efc1283 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/loading.gif differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/logow.png b/workflow/public_html/lib/pmdynaform/build/img/logow.png new file mode 100644 index 000000000..f8981bd46 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/logow.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/pdf.png b/workflow/public_html/lib/pmdynaform/build/img/pdf.png new file mode 100644 index 000000000..7ed6877b1 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/pdf.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/ppt.png b/workflow/public_html/lib/pmdynaform/build/img/ppt.png new file mode 100644 index 000000000..561b0e763 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/ppt.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/print-icon.png b/workflow/public_html/lib/pmdynaform/build/img/print-icon.png new file mode 100644 index 000000000..71f014fe6 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/print-icon.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/trash.png b/workflow/public_html/lib/pmdynaform/build/img/trash.png new file mode 100644 index 000000000..db0f67d74 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/trash.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/txt.png b/workflow/public_html/lib/pmdynaform/build/img/txt.png new file mode 100644 index 000000000..b904145e1 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/txt.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/up.png b/workflow/public_html/lib/pmdynaform/build/img/up.png new file mode 100644 index 000000000..ce1f88a26 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/up.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/video.png b/workflow/public_html/lib/pmdynaform/build/img/video.png new file mode 100644 index 000000000..6d4b0ac01 Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/video.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/img/xls.png b/workflow/public_html/lib/pmdynaform/build/img/xls.png new file mode 100644 index 000000000..c5f44c7bd Binary files /dev/null and b/workflow/public_html/lib/pmdynaform/build/img/xls.png differ diff --git a/workflow/public_html/lib/pmdynaform/build/index.html b/workflow/public_html/lib/pmdynaform/build/index.html new file mode 100644 index 000000000..4b7d297a8 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/index.html @@ -0,0 +1,66 @@ + + + + PMDynaform + + + + + + + + +
    + + + +
    + +
    + +
    + + + + + diff --git a/workflow/public_html/lib/pmdynaform/build/js/PMDynaform.js b/workflow/public_html/lib/pmdynaform/build/js/PMDynaform.js new file mode 100644 index 000000000..f8e7b84b2 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/js/PMDynaform.js @@ -0,0 +1,29653 @@ +/** + * @class PMDynaform + * Base class PMDynaform + * @singleton + */ + +/** + * @feature support for ie8 + * functions + */ + +function getScrollTop() { + if (typeof pageYOffset != 'undefined') { + //most browsers except IE before #9 + return pageYOffset; + } else { + var B = document.body; //IE 'quirks' + var D = document.documentElement; //IE with doctype + D = (D.clientHeight) ? D : B; + return D.scrollTop; + } +}; +//.trim to support ie8 +if (!Array.prototype.filter) { + Array.prototype.filter = function (fun/*, thisArg*/) { + 'use strict'; + + if (this === void 0 || this === null) { + throw new TypeError(); + } + + var t = Object(this); + var len = t.length >>> 0; + if (typeof fun !== 'function') { + throw new TypeError(); + } + + var res = []; + var thisArg = arguments.length >= 2 ? arguments[1] : void 0; + for (var i = 0; i < len; i++) { + if (i in t) { + var val = t[i]; + + // NOTA: Tecnicamente este Object.defineProperty deben en + // el indice siguiente, como push puede ser + // afectado por la propiedad en object.prototype y + // Array.prototype. + // Pero estos metodos nuevos, y colisiones deben ser + // raro, así que la alternativas mas compatible. + if (fun.call(thisArg, val, i, t)) { + res.push(val); + } + } + } + + return res; + }; +} + +if (!String.prototype.trim) { + (function () { + // Make sure we trim BOM and NBSP + var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; + String.prototype.trim = function () { + return this.replace(rtrim, ''); + }; + })(); +} + +if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (elt /*, from*/) { + var len = this.length >>> 0; + + var from = Number(arguments[1]) || 0; + from = (from < 0) + ? Math.ceil(from) + : Math.floor(from); + if (from < 0) + from += len; + + for (; from < len; from++) { + if (from in this && + this[from] === elt) + return from; + } + return -1; + }; +} + +if (!document.getElementsByClassName) { + document.getElementsByClassName = function (classname) { + var a = []; + var re = new RegExp('(^| )' + classname + '( |$)'); + var els = this.getElementsByTagName("*"); + for (var i = 0, j = els.length; i < j; i++) + if (re.test(els[i].className)) + a.push(els[i]); + return a; + }; +} + +if (!Array.prototype.find) { + Array.prototype.find = function (callback, thisArg) { + "use strict"; + var arr = this, + arrLen = arr.length, + i; + for (i = 0; i < arrLen; i += 1) { + if (callback.call(thisArg, arr[i], i, arr)) { + return arr[i]; + } + } + return undefined; + }; +} + +var PMDynaform = { + VERSION: "0.1.0", + view: {}, + model: {}, + collection: {}, + Extension: {}, + restData: {}, + activeProject: null, + FLashMessage: null, + PATH_RTL_CSS: "css/PMDynaform-rtl.css" +}; +/** + * Extends the PMDynaform namespace with the given `path` and making a pointer + * from `path` to the given `class` (note that the `path`'s last token will be the pointer visible from outside + * the definition of the class). + * + * // e.g. + * // let's define a class inside an anonymous function + * // so that the global scope is not polluted + * (function () { + * var Class = function () {...}; + * + * // let's extend the namespace + * PMDynaform.extendNamespace('PMDynaform.package.Class', Class); + * + * }()); + * + * // now PMDynaform.package.Class is a pointer to the class defined above + * + * @param {string} path + * @param {Object} newClass + * @return {Object} The argument `newClass` + */ +PMDynaform.extendNamespace = function (path, newClass) { + var current, + pathArray, + extension, + i; + + if (arguments.length !== 2) { + throw new Error("Dynaform.extendNamespace(): method needs 2 arguments"); + } + + pathArray = path.split('.'); + if (pathArray[0] === 'PMDynaform') { + pathArray = pathArray.slice(1); + } + current = PMDynaform; + + // create the 'path' namespace + for (i = 0; i < pathArray.length - 1; i += 1) { + extension = pathArray[i]; + if (typeof current[extension] === 'undefined') { + current[extension] = {}; + } + current = current[extension]; + } + + extension = pathArray[pathArray.length - 1]; + if (current[extension]) { + + } + current[extension] = newClass; + return newClass; +}; + +/** + * Creates an object whose [[Prototype]] link points to an object's prototype (the object is gathered using the + * argument `path` and it's the last token in the string), since `subClass` is given it will also mimic the + * creation of the property `constructor` and a pointer to its parent called `superclass`: + * + * // constructor pointer + * subClass.prototype.constructor === subClass // true + * + * // let's assume that superClass is the last token in the string 'path' + * subClass.superclass === superClass // true + * + * An example of use: + * + * (function () { + * var Class = function () {...}; + * + * // extending the namespace + * PMDynaform.extendNamespace('PMDynaform.package.Class', Class); + * + * }()); + * + * (function () { + * var NewClass = function () {...}; + * + * // this class inherits from PMDynaform.package.Class + * PMDynaform.inheritFrom('PMDynaform.package.Class', NewClass); + * + * // extending the namespace + * PMDynaform.extendNamespace('PMDynaform.package.NewClass', NewClass); + * + * }()); + * + * @param {string} path + * @param {Object} subClass + * @return {Object} + */ +PMDynaform.inheritFrom = function (path, subClass) { + var current, + extension, + pathArray, + i, + prototype; + + if (arguments.length !== 2) { + throw new Error("PMDynaform.inheritFrom(): method needs 2 arguments"); + } + + // function used to create an object whose [[Prototype]] link + // points to `object` + function clone(object) { + var F = function () { + }; + F.prototype = object; + return new F(); + } + + pathArray = path.split('.'); + if (pathArray[0] === 'PMDynaform') { + pathArray = pathArray.slice(1); + } + current = PMDynaform; + + // find that class the 'path' namespace + for (i = 0; i < pathArray.length; i += 1) { + extension = pathArray[i]; + if (typeof current[extension] === 'undefined') { + throw new Error("PMDynaform.inheritFrom(): object " + extension + " not found, full path was " + path); + } + current = current[extension]; + } + + prototype = clone(current.prototype); + + prototype.constructor = subClass; + subClass.prototype = prototype; + subClass.superclass = current; +}; +/** + * Get the keys from active project + * @returns {*} + */ +PMDynaform.getProjectKeys = function () { + var resp = null, + options; + if (this.activeProject) { + options = this.activeProject.webServiceManager.options; + resp = _.extend(options.keys, options.token); + } + return resp; +}; + +/** + * Set the instance of an active project pmdynaform + * @param project + * @returns { null | PMDynaform.core.ProjectMobile | PMDynaform.core.Project } + */ +PMDynaform.setActiveProject = function (project) { + if ((PMDynaform.core.ProjectMobile && project instanceof PMDynaform.core.ProjectMobile) || project instanceof PMDynaform.core.Project) { + this.activeProject = project; + return project; + } + return null; +}; + +/** + * Get the active project instance of pmdynaform + * @returns { PMDynaform.core.ProjectMobile | PMDynaform.core.Project } + */ +PMDynaform.getActiveProject = function () { + return this.activeProject; +}; + +/** + * Get the workspace from the project + * @returns {*} + */ +PMDynaform.getWorkspaceName = function () { + var resp = null; + if (this.activeProject) { + resp = this.activeProject.webServiceManager.getKey("workspace"); + } + return resp; +}; + +/** + * Get the Accestoken from the project + * @returns {*} + */ +PMDynaform.getAccessToken = function () { + var resp = null; + if (this.activeProject) { + resp = this.activeProject.webServiceManager.getToken()["accessToken"]; + } + return resp; +}; + +/** + * Get the hostName from the project + * @returns {*} + */ +PMDynaform.getHostName = function () { + var resp = null; + if (this.activeProject) { + resp = this.activeProject.webServiceManager.getKey("server"); + } + return resp; +}; + +/** + * Get the enviroment (desktop, webkit android or iOS) + * @returns {string} + */ +PMDynaform.getEnvironment = function () { + var nav = navigator.userAgent, + resp; + resp = nav; + if (nav === 'formslider-ios') { + resp = "iOS"; + } + if (nav === 'formslider-android') { + resp = "android"; + } + return resp; +}; + +/** + * Helper to get user information. + * @return {*|{}|string} + */ +PMDynaform.getUserInfo = function () { + var navigator = window.navigator.userAgent, + response; + if (navigator === 'formslider-ios' || navigator === 'formslider-android') { + response = this.activeProject.userInfo; + } else { + response = this.activeProject.webServiceManager.getUserInfo(); + response['language'] = PMDynaform.lang.I18N.currentLanguage; + } + return response; +}; +/** + * Helper to escape the CSS selectors + * PMDynaform.escapeSelector() + * @param {string} sel + * @return {string} + */ +PMDynaform.escapeSelector = function(sel) { + var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g; + var fcssescape = function(ch, asCodePoint) { + if (asCodePoint) { + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if (ch === "\0") { + return "\uFFFD"; + } + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " "; + } + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }; + + return (sel + '').replace(rcssescape, fcssescape); +}; + +String.prototype.capitalize = function () { + return this.toLowerCase().replace(/(^|\s)([a-z])/g, function (m, p1, p2) { + return p1 + p2.toUpperCase(); + }); +}; + +jQuery.fn.extend({ + setLabel: function (newLabel, col) { + var field = getFieldById(this.attr("id")) || null; + if (typeof newLabel === "string" && field) { + field.setLabel(newLabel, col); + } + return this; + }, + getLabel: function (col) { + var field = getFieldById(this.attr("id")) || null; + if (field) { + return field.getLabel(col); + } + return null; + }, + /** + * Sets a field's value into a form or grid + * @param value + * @param row + * @param col + * @returns {jQuery} + */ + setValue: function (value, row, col) { + var field = getFieldById(this.attr("id")) || null; + if (field) { + if (field.model.get("type") === "grid") { + field.setValue(value, row, col); + } else { + field.setValue(value); + } + } + return this; + }, + /** + * Sets a field's value into a form or grid async mode + * @param {*} value + * @param {*} row + * @param {*} col + * @param {*} fn + */ + setValueAsync: function (value, row, col, fn) { + var field = getFieldById(this.attr("id")) || null; + if (field) { + if (field.model.get("type") !== "grid") { + field.setValueAsync(value, row); + } else { + field.setValueAsync(value, row, col, fn); + } + } + return this; + }, + /** + * Sets a field's text into a form or grid async mode + * @param {*} value + * @param {*} row + * @param {*} col + * @param {*} fn + */ + setTextAsync: function (value, row, col, fn) { + var field = getFieldById(this.attr("id")) || null; + if (field) { + if (field.model.get("type") !== "grid") { + field.setTextAsync(value, row); + } else { + field.setTextAsync(value, row, col, fn); + } + } + return this; + }, + setText: function (value, row, col) { + var field = getFieldById(this.attr("id")) || null; + if (field) { + if (field.model.get("type") === "grid") { + field.setText(value, row, col); + } else { + field.setText(value); + } + } + return this; + }, + /** + * Helper for get the value of a Field or Grid + * @param row + * @param col + * @returns {*} + */ + getValue: function (row, col) { + var field = getFieldById(this.attr("id")) || null, + val = "", + type; + if (field) { + type = field.model.get("type"); + if (type === "grid") { + val = field.getValue(row, col); + } else { + val = field.getValue(); + } + } + return val; + }, + /** + * helper getAppDocUID function to get app document uid as reference to a document + * @returns {array} val + */ + getAppDocUID: function () { + var item, + val = null; + if (getFieldById(this.attr("id"))) { + item = getFieldById(this.attr("id")); + if (typeof item.model.getAppDocUID === 'function' + && item.model.getAppDocUID()) { + val = item.model.getAppDocUID(); + } + } + return val; + }, + /** + * Helper setOnChange + * @param handler + * @returns {jQuery} + */ + setOnchange: function (handler) { + var item = this.getIntanceById(this.attr("id")); + if (item && typeof handler === "function" && typeof item.setOnChange === "function") { + item.setOnChange(handler); + } + return this; + }, + getInfo: function () { + var field = getFieldById(this.attr("id")) || null; + if (field) { + return field.getInfo(); + } + return null; + }, + setHref: function (value) { + var field = getFieldById(this.attr("id")) || null; + if (field.model.get("type") === "link") { + field.setHref(value); + } + return this; + }, + getHref: function () { + var field = getFieldById(this.attr("id")) || null; + if (field.model.get("type") === "link") { + return field.getHref(); + } + return this; + }, + setRequired: function (field) { + }, + required: function (field) { + }, + getText: function (row, col) { + var field = getFieldById(this.attr("id")) || null, + typeField, + val = null; + + if (field) { + typeField = field.model.get("type"); + if (typeField === "grid") { + val = field.getText(row, col); + } else { + val = field.getText(); + } + } + return val; + }, + disableValidation: function (col) { + var field = getFieldById(this.attr("id")) || null, val; + if (field && field.disableValidation) { + field.disableValidation(col); + } + return this; + }, + enableValidation: function (col) { + var field = getFieldById(this.attr("id")) || null, val; + if (field && field.enableValidation) { + field.enableValidation(col); + } + return this; + }, + /** + * Helper for get the control of a Field + * @param row + * @param col + * @returns {Array} + */ + getControl: function (row, col) { + var field = getFieldById(this.attr("id")) || null, + control = [], + type; + if (field) { + type = field.model.get("type"); + if (type === "grid") { + control = field.getControl(row, col); + } else { + control = field.getControl(); + } + } + return control; + }, + getLabelControl: function () { + var field = getFieldById(this.attr("id")) || null, val; + if (field) { + field.getLabelControl(); + } + return this; + }, + getHintHtml: function () { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field) { + html = field.$el.find(".glyphicon-info-sign"); + } + return $(html); + }, + getSummary: function (col) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid") { + return field.getSummary(col); + } + return this; + }, + getNumberRows: function () { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") === "grid") { + return field.getNumberRows(); + } + return this; + }, + addRow: function (data) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") === "grid") { + field.addRow(data, data ? data.length > 0 : false); + } + return this; + }, + deleteRow: function (row) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid") { + if (!row) { + row = field.getNumberRows(); + } + field.deleteRow(row); + } + return this; + }, + onBeforeAdd: function () { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid") { + if (typeof handler === "function") { + field.setOnBeforeAddCallback(handler); + } + } + }, + onAddRow: function (handler) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid") { + if (typeof handler === "function") { + field.setOnAddRowCallback(handler); + } + } + }, + onShowRowDialog: function (handler) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid" && PMDynaform.core.ProjectMobile) { + if (typeof handler === "function") { + field.setOnShowRowDialog(handler); + } + } + }, + onDeleteRow: function (handler) { + var field = getFieldById(this.attr("id")) || null, html = []; + if (field && field.model.get("type") == "grid") { + if (typeof handler === "function") { + field.setOnDeleteRowCallback(handler); + } + } + }, + hideColumn: function (col) { + var field = getFieldById(this.attr("id")) || null; + if (field && field.model.get("type") === "grid") { + field.hideColumn(parseInt(col, 10)); + } + }, + showColumn: function (col) { + var field = getFieldById(this.attr("id")) || null; + if (field && field.model.get("type") === "grid") { + field.showColumn(parseInt(col, 10)); + } + }, + getData: function () { + var field = getFieldById(this.attr("id")) || null, val; + if (field && field.getData) { + return field.getData(); + } + return this; + }, + getDataLabel: function () { + var field = getFieldById(this.attr("id")) || null, val; + if (field && field.getDataLabel) { + return field.getDataLabel(); + } + return this; + }, + getForm: function () { + var form; + if (this.length) { + form = getFormById(this.attr('id') || '') || null; + return form; + } + }, + submitForm: function () { + var project, + form = this.getForm(); + if (form) { + project = form.project; + if (project && !project.isMobile()) { + if (form.isValid()) { + form.submitNextStep(); + } + } else { + form.onSubmit(); + } + } + }, + /** + * Saves form's data + * @returns {jQuery} + */ + saveForm: function () { + var form; + form = getFormById(this.attr("id")); + if (form) { + form.saveForm(); + } + return this; + }, + /** + * Set a callback in submit action + * @param callback + * @returns {jQuery} + */ + setOnSubmit: function (callback) { + var form; + form = getFormById(this.attr("id")); + if (form) { + form.setOnSubmit(callback); + } + return this; + }, + _getJSONFormValues: function (elements) { + var i; + var data = {}; + if (elements.length > 0) { + for (i = 0; i < elements.length; i += 1) { + data[elements[i].name] = elements[i].value; + } + } + return data; + }, + /** + * This is a help function to close the form, supported for mobile version + * @returns {jQuery} + */ + closeForm: function () { + var form = getFormById(this.attr("id")); + if (form && form instanceof PMDynaform.view.FormPanel) { + form.close(); + } + return this; + }, + /** + * Show Modal Loading + * @returns {jQuery} + */ + showFormModal: function () { + var form = this.getForm(), modal; + if (form) { + modal = form.project.modalProgress; + modal.render(); + } + return this; + }, + /** + * Hide Modal Loading + * @returns {jQuery} + */ + hideFormModal: function () { + var form = this.getForm(), modal; + if (form) { + modal = form.project.modalProgress; + modal.hide(); + } + return this; + }, + /** + * Hide New Button of the Grid + * @returns {jQuery} + */ + hideNewButton: function () { + var field = getFieldById(this.attr("id")) || null, + actionButton = "add"; + if (field && field.model.get("type") === "grid") { + field.hideButton(actionButton); + } + return this; + }, + /** + * Show New Button of the Grid + * @returns {jQuery} + */ + showNewButton: function () { + var field = getFieldById(this.attr("id")) || null, + actionButton = "add"; + if (field && field.model.get("type") === "grid") { + field.showButton(actionButton); + } + return this; + }, + /** + * Clear Content File with params + * With out params clear all grid's rows + * @param row + * @param col + * @returns {jQuery} + */ + clear: function (row, col) { + var field = getFieldById(this.attr("id")) || null, + type; + if (field) { + type = field.model.get("type"); + if (type === "grid") { + if (row === undefined && col === undefined) { + field.clearAllRows(); + } else { + field.clearContent(row, col); + } + } else { + field.clearContent(); + } + } + return this; + }, + /** + * Get Instance by Id (Form or Field) + * @returns {*} + */ + getIntanceById: function (idItem) { + var idInstance = idItem || null, + instanceResult = getFormById(idInstance) || getFieldById(idInstance); + return instanceResult || null; + }, + /** + * Returns all the forms fields, including the ones in any nested subform. + * @param id The form's id. + * @returns {ArrayPMDynaform.view.Field} + */ + getFields: function (id) { + var form = getFormById(this.attr("id")) + || getFieldById(this.attr("id")); + + return (form && form.getAllFields()) || []; + }, + /** + * Enables the fixed location helper function + * @returns {ArrayPMDynaform.view.Field} + */ + enableFixedLocationGeomap: function () { + var field = getFieldById(this.attr("id")) || null; + if (field && typeof field.model.setFixedLocation === 'function' + && PMDynaform.core.ProjectMobile) { + field.model.setFixedLocation(true); + } + return this; + }, + /** + * Disables the fixed location helper function + * @returns {ArrayPMDynaform.view.Field} + */ + disableFixedLocationGeomap: function () { + var field = getFieldById(this.attr("id")) || null; + if (field && typeof field.model.setFixedLocation === 'function' + && PMDynaform.core.ProjectMobile) { + field.model.setFixedLocation(false); + } + return this; + } +}); +(function () { + var InputsValidation = function () { + var config = { + "data": { + "name": "", + "description": "", + "items": [ + { + "type": "form", + "variable": "", + "var_uid": "", + "dataType": "", + "id": "", + "name": "", + "description": "", + "mode": "edit", + "script": "", + "language": "en", + "externalLibs": "", + "printable": false, + "items": [], + "variables": [] + } + ] + }, + "delIndex": 0, + "dynaformUid": "", + "keys": { + "server": (location.protocol + "//" + window.location.host), + "projectId": "", + "workspace": "workflow" + }, + "token": { + "accessToken": "", + "expiresIn": 0, + "tokenType": "bearer", + "scope": "", + "refreshToken": "", + "clientId": "", + "clientSecret": "" + }, + isPreview : false, + isRTL: false, + language: null, + formAction: null, + formAjax: null, + submitRest: false, + globalMode: null, + externalLibs: "", + renderTo: document.body, + onLoad: new Function() + }; + return { + getDefaultData : function(){ + return config; + } + }; + }; + PMDynaform.extendNamespace("PMDynaform.util.InputsValidation", InputsValidation); +}()); + +(function () { + /** + * Class handler for events in PMDYNAFORM + * Object CHANNEL + * { + * channel:"channelName", + * type: "joinFork", + * callback: function(){}, + * events: [ + * { + * event: "eventName", + * complete: true, + * payload: {} + * } + * ] + * } + * + */ + var EventBus = function (options) { + this.bus = _.extend({}, Backbone.Events); + this.channels = {}; + this.topics = []; + }; + /** + * Emit events based in Redux Framework + * @param event + * { + * channel: "", + * event: "", + * payload: "", + * } + */ + EventBus.prototype.emit = function (event) { + this.bus.trigger(event.channel || "default", event); + }; + /** + * Create a channel for event bus + * @param {*} t + * @returns {EventBus} + */ + EventBus.prototype.createChannel = function (t) { + t.channel = t.channel || "default"; + if (!this.channels[t.channel]) { + this.channels[t.channel] = []; + } + this.channels[t.channel].push(t); + return this; + }; + /** + * Subscriber for callback in a channel in some TYPE (joinFork|joinForkTwice) + * INPUT + * { + * channel: "", + * type: "joinFork", + * id:"", + * events:[{ + * event:"event1", + * queue:[{payload: ""}] + * }], + * callback: ()=>{} + * } + * @param {*} t + */ + EventBus.prototype.subscribe = function (t) { + var that = this, isDefined = true; + t.channel = t.channel || "default"; + if (!this.channels[t.channel]) { + this.channels[t.channel] = []; + isDefined = false; + } + this.channels[t.channel].push(t); + if (!isDefined) { + PMDynaform.EventBus.on(t.channel, function (payload) { + var arr = that.channels[t.channel]; + payload.channel = payload.channel || "default"; + if (payload && payload.channel == t.channel) { + _.forEach(arr, function (el) { + _.forEach(el.events, function (e) { + if (e.event == payload.event) { + if (!e.queue) { + e.queue = []; + } + e.queue.push({ + payload: payload.payload + }); + + } + }); + that.pipe(el); + }); + that.channels[t.channel] = _.reject(arr, function (el) { + return el.complete && el.deleteOnCompletion; + }); + } + }, t.context); + } + }; + /** + * Executes a type of pipe joinForkTwice or joinFork + * @param {*} el + */ + EventBus.prototype.pipe = function (el) { + var evC = true; + if (el.type == "joinForkTwice") { + _.forEach(el.events, function (e) { + if (!e.queue || !(e.queue.length >= 1 && e.queue.length <= 2)) { + evC = false; + } + }); + if (evC) { + _.forEach(el.events, function (e) { + if (e.queue.length == 2) { + e.queue = [_.last(e.queue)]; + } + }); + if (_.isFunction(e.callback)) { + setTimeout(function () { + e.callback(); + }, 10); + } + } + } + + //For joinFork way in EventBus + if (el.type == "joinFork") { + _.forEach(el.events, function (e) { + if (!e.queue || !e.queue.length === 1) { + evC = false; + } + }); + if (evC) { + _.forEach(el.events, function (e) { + e.queue = null; + }); + el.complete = true; + if (_.isFunction(el.callback)) { + setTimeout(function () { + el.callback(); + }, 10); + } + } + } + }; + /** + * Add event to a observable object + * INPUT + * { + * channel: "", + * id:"", + * events:[{ + * event:"event1" + * }] + * } + * @param {String} t + */ + EventBus.prototype.subscribeEventToJoinFork = function (t) { + t.channel = t.channel || "default"; + var observables = this.channels[t.channel]; + if (observables) { + _.forEach(observables, function (o) { + if (o.id == t.id) { + o.events = o.events.concat(t.events); + } + }); + } + return this; + }; + /** + * The method verify if exists in channel a observable id + * @param {String} channel + * @param {String} idObservable + * @returns {*} + */ + EventBus.prototype.verifyObservableChannel = function (channel, idObservable) { + channel = channel || "default"; + var observables = this.channels[channel], + obs; + if (observables) { + obs = _.find(observables, function (o) { + return o.id == idObservable + }); + } + return obs; + }; + /** + * Bind a callback function to an object. The callback will be invoked whenever the event is fired. + * @param event + * @param callback + */ + EventBus.prototype.on = function (event, callback) { + this.bus.on(event, callback); + }; + + /** + * Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks. + * @param event + * @param payload + */ + EventBus.prototype.trigger = function (event, payload) { + this.bus.trigger(event, payload); + }; + + /** + * Create a channel Topic with events listeners in BUS + * @param topicStr + * @param events + * @param callback + */ + EventBus.prototype.joinForkTopic = function (topicStr, events, callback) { + var that = this, + topic = { + topic: topicStr, + events: events, + callback: callback + }; + + this.removeTopic(topic); + this.topics.push(topic); + _.forEach(events, function (v) { + var fn = function (payload) { + _.filter(topic.events, function (ev) { + if (ev.event == v.event) { + ev.complete = true; + ev.payload = payload; + } + return ev.event == v.event + }); + + if (_.every(topic.events, function (everyEvent) { + return everyEvent.complete == true; + })) { + topic.callback(); + that.emptyPayloadInTopic(topicStr); + } + }; + v.callback = fn; + that.bus.on(topicStr + "/" + v.event, fn); + }); + }; + + /** + * Remove all payloads of events in TOPIC + * @param topic + */ + EventBus.prototype.emptyPayloadInTopic = function (topic) { + var that = this; + _.find(this.topics, function (t) { + if (t.topic == topic) { + _.forEach(t.events, function (e) { + e.payload = null; + }); + } + return t.topic == topic; + }); + }; + + /** + * Remove all listener from topic + * @param topic + */ + EventBus.prototype.removeTopic = function (topic) { + var that = this, + nTopics; + nTopics = _.reject(this.topics, function (t) { + if (t.topic == topic) { + _.forEach(t.events, function (e) { + that.bus.off(t.topic + "/" + e.event); + }); + } + return t.topic == topic; + }); + this.topics = nTopics; + }; + + /** + * Create only topic without events + * @param topic + * @param callback + */ + EventBus.prototype.callbackJoinForkTopic = function (obj) { + var topic, + fTop = _.find(this.topics, function (top) { + if (top.topic == obj.topic) { + top.callback = obj.callback; + } + return top.topic == obj.topic; + }); + if (!fTop) { + topic = { + topic: obj.topic, + events: [], + callback: obj.callback + }; + this.topics.push(topic); + } + }; + + /** + * Add events to Join Topic + * @param topic + * @param event + * @param callback + */ + EventBus.prototype.addJoinForkTopic = function (obj) { + var topic, + that = this, + fTop = _.find(this.topics, function (top) { + return top.topic == obj.topic; + }); + if (!fTop) { + topic = { + topic: obj.topic, + events: [], + callback: null + }; + this.topics.push(topic); + } + + _.find(this.topics, function (t) { + //Find topic + if (t.topic == obj.topic) { + //Find event + var ev = _.find(t.events, function (e) { + return e.event == obj.event; + }); + if (!ev) { + t.events.push({ + event: obj.event, + complete: false, + payload: null + }); + var strTopicEvent = obj.topic + "/" + obj.event; + PMDynaform.EventBus.on(strTopicEvent, function (payload) { + var filterEvent = _.filter(t.events, function (ev) { + if (ev.event == obj.event) { + ev.complete = true; + ev.payload = payload; + } + return ev.event == obj.event; + }); + + if (_.every(t.events, function (everyEvent) { + return everyEvent.complete == true; + })) { + t.callback(); + that.emptyPayloadInTopic(t.topic); + } + }); + } + + } + return t.topic == obj.topic; + }); + }; + + PMDynaform.extendNamespace("PMDynaform.EventBus", new EventBus()); +}()); +(function () { + /** + * I18N Manager + * @type {{indexes: {}, repository: {}, observers: Array, defaultLanguage: string, currentLanguage: string, + * contextIndex: {}, setDefaultLanguage: setDefaultLanguage, MD5: MD5}} + */ + var I18N = { + indexes: {}, + repository: {}, + observers: [], + defaultLanguage: 'en', + currentLanguage: 'en', + contextIndex: {}, + setDefaultLanguage: function (lang) { + this.defaultLanguage = lang; + }, + MD5: function (string) { + + function RotateLeft(lValue, iShiftBits) { + return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); + } + + function AddUnsigned(lX, lY) { + var lX4, + lY4, + lX8, + lY8, + lResult; + + lX8 = (lX & 0x80000000); + lY8 = (lY & 0x80000000); + lX4 = (lX & 0x40000000); + lY4 = (lY & 0x40000000); + lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); + if (lX4 & lY4) { + return (lResult ^ 0x80000000 ^ lX8 ^ lY8); + } + if (lX4 | lY4) { + if (lResult & 0x40000000) { + return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); + } else { + return (lResult ^ 0x40000000 ^ lX8 ^ lY8); + } + } else { + return (lResult ^ lX8 ^ lY8); + } + } + + function F(x, y, z) { + return (x & y) | ((~x) & z); + } + + function G(x, y, z) { + return (x & z) | (y & (~z)); + } + + function H(x, y, z) { + return (x ^ y ^ z); + } + + function I(x, y, z) { + return (y ^ (x | (~z))); + } + + function FF(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function GG(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function HH(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function II(a, b, c, d, x, s, ac) { + a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); + return AddUnsigned(RotateLeft(a, s), b); + }; + + function ConvertToWordArray(string) { + var lWordCount, + lMessageLength = string.length, + lNumberOfWords_temp1 = lMessageLength + 8, + lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64, + lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16, + lWordArray = Array(lNumberOfWords - 1), + lBytePosition = 0, + lByteCount = 0; + + while (lByteCount < lMessageLength) { + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); + lByteCount++; + } + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); + lWordArray[lNumberOfWords - 2] = lMessageLength << 3; + lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; + + return lWordArray; + }; + + function WordToHex(lValue) { + var WordToHexValue = "", + WordToHexValue_temp = "", + lByte, + lCount; + + for (lCount = 0; lCount <= 3; lCount += 1) { + lByte = (lValue >>> (lCount * 8)) & 255; + WordToHexValue_temp = "0" + lByte.toString(16); + WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2); + } + return WordToHexValue; + }; + + function Utf8Encode(string) { + var utftext = "", + n, + c; + + string = string.replace(/\r\n/g, "\n"); + for (n = 0; n < string.length; n += 1) { + c = string.charCodeAt(n); + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if ((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + } + + return utftext; + }; + + var x, + k, + AA, + BB, + CC, + DD, + a, + b, + c, + d, + S11 = 7, + S12 = 12, + S13 = 17, + S14 = 22, + S21 = 5, + S22 = 9, + S23 = 14, + S24 = 20, + S31 = 4, + S32 = 11, + S33 = 16, + S34 = 23, + S41 = 6, + S42 = 10, + S43 = 15, + S44 = 21, + temp; + + string = Utf8Encode(string); + + x = ConvertToWordArray(string); + + a = 0x67452301; + b = 0xEFCDAB89; + c = 0x98BADCFE; + d = 0x10325476; + + for (k = 0; k < x.length; k += 16) { + AA = a; + BB = b; + CC = c; + DD = d; + a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478); + d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756); + c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB); + b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE); + a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF); + d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A); + c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613); + b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501); + a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8); + d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF); + c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1); + b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE); + a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122); + d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193); + c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E); + b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821); + a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562); + d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340); + c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51); + b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA); + a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D); + d = GG(d, a, b, c, x[k + 10], S22, 0x2441453); + c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681); + b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8); + a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6); + d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6); + c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87); + b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED); + a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905); + d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8); + c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9); + b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A); + a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942); + d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681); + c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122); + b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C); + a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44); + d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9); + c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60); + b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70); + a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6); + d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA); + c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085); + b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05); + a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039); + d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5); + c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8); + b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665); + a = II(a, b, c, d, x[k + 0], S41, 0xF4292244); + d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97); + c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7); + b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039); + a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3); + d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92); + c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D); + b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1); + a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F); + d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0); + c = II(c, d, a, b, x[k + 6], S43, 0xA3014314); + b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1); + a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82); + d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235); + c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB); + b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391); + a = AddUnsigned(a, AA); + b = AddUnsigned(b, BB); + c = AddUnsigned(c, CC); + d = AddUnsigned(d, DD); + } + + temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d); + + return temp.toLowerCase(); + } + }; + /** + * Set Deafult Language + * @param lang + * @returns {I18N} + */ + I18N.setDefaultLanguage = function (lang) { + this.defaultLanguage = lang; + if (this.repository[lang]) { + this.loadDefaultLanguege(this.repository[lang]); + } + return this; + }; + /** + * Load Language + * @param data + * @param lang + * @param loaded + * @returns {I18N} + */ + I18N.loadLanguage = function (data, lang, loaded) { + if (typeof data != 'object') { + throw new Error("loadLanguage(): the first parameter is not valid, should be 'object'"); + } + if (typeof lang != 'string') { + throw new Error("loadLanguage(): the second parameter is not valid, should be 'string'"); + } + if (this.defaultLanguage == lang) { + this.loadDefaultLanguege(data); + } + if (!loaded) { + this.repository[lang] = data; + } + return this; + }; + /** + * Load Default Language + * @param data + * @returns {I18N} + */ + I18N.loadDefaultLanguege = function (data) { + var label, + value; + + this.indexes = {}; + this.contextIndex = {}; + for (label in data) { + if (!this.indexes[data[label]]) { + this.indexes[data[label]] = label; + } else { + if (!this.contextIndex[data[label]]) { + value = this.indexes[data[label]]; + this.contextIndex[data[label]] = {}; + this.contextIndex[data[label]]['0'] = value; + this.contextIndex[data[label]]['1'] = label; + } else { + var n = this.getSizeJson(this.contextIndex[data[label]]); + this.contextIndex[data[label]][n.toString()] = label; + } + } + } + return this; + }; + /** + * Get Size Json + * @param json + * @returns {I18N} + */ + I18N.getSizeJson = function (json) { + var size = 0, + i; + + if (typeof json == 'object') { + for (i in json) { + size += 1; + } + return size; + } else { + throw new Error('the parameter is not a JSON'); + } + return this; + }; + /** + * Set Current Language + * @param lang + * @returns {I18N} + */ + I18N.setCurrentLanguage = function (lang) { + this.currentLanguage = lang; + if (this.repository[lang]) { + this.loadLanguage(this.repository[lang], lang, true); + } + return this; + }; + /** + * Get Translate value + * @param variablesLabels + * @returns {string} + */ + I18N.translate = function (variablesLabels) { + var translation = String(this), + index, + i; + + index = I18N.indexes[this]; + if (index && I18N.repository[I18N.currentLanguage][index]) { + translation = I18N.repository[I18N.currentLanguage][index]; + } + if (variablesLabels) { + for (i = 0; i < variablesLabels.length; i += 1) { + translation = translation.replace("{" + i + "}", String(variablesLabels[i])); + } + } + return translation; + }; + /** + * Get Translate Context + * @param value + * @returns {*} + */ + I18N.translateContext = function (value) { + var translation, + index, + label; + + if (typeof value != 'number') { + for (label in I18N.contextIndex[this]) { + if (I18N.contextIndex[this][label] == value) { + index = I18N.contextIndex[this][label]; + } + } + } else { + index = I18N.contextIndex[this][value.toString()]; + } + + if (index) { + translation = I18N.repository[I18N.currentLanguage][index]; + return translation; + } + + return String(this); + }; + // Declarations created to instantiate in NodeJS environment + if (typeof exports !== 'undefined') { + module.exports = I18N; + } + + PMDynaform.extendNamespace("PMDynaform.lang.I18N", I18N); + +}()); +/** + * Class representing a Translation + * @constructor + */ +var Translation = function () { + this.lang = null; + Translation.prototype.initialize.call(this); +}; +/** + * A module representing a Translation + **/ +Translation.prototype = { + /** + * Sets the lang + * @param {string} lang + */ + setLang: function (lang) { + this.lang = lang; + return this; + }, + /** + * Get the Lang value + * @returns {null|*|string} The Lang value + */ + getLang: function () { + return this.lang || 'en'; + }, + /** + * initialize Translation + */ + initialize: function () { + String.prototype.translate = PMDynaform.lang.I18N.translate; + String.prototype.translateContext = PMDynaform.lang.I18N.translateContext; + + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (elt /*, from*/) { + var len = this.length >>> 0; + + var from = Number(arguments[1]) || 0; + from = (from < 0) + ? Math.ceil(from) + : Math.floor(from); + if (from < 0) + from += len; + + for (; from < len; from += 1) { + if (from in this && + this[from] === elt) + return from; + } + return -1; + }; + } + return this; + }, + /** + * Get Language + * @returns {string} + */ + getLanguageFromWindowLocation: function () { + var url, + lang = 'en'; + + if (window.parent) { + try { + url = window.parent.location.pathname.split('/'); + } catch (e) { + url = window.location.pathname.split('/'); + } + lang = url[2] || lang; + } + return lang; + }, + /** + * Load Language + * @param data + * @param lang + * @param loaded + * @returns {Translation} + */ + loadLanguage: function (data, lang, loaded) { + PMDynaform.lang.I18N.loadLanguage(data, lang, loaded); + return this; + }, + /** + * Set Current Language + * @param lang + * @returns {Translation} + */ + setCurrentLanguage: function (lang) { + PMDynaform.lang.I18N.setCurrentLanguage(lang); + return this; + }, + /** + * Set Default Language + * @param lang + * @returns {Translation} + */ + setDefaultLanguage: function (lang) { + PMDynaform.lang.I18N.setDefaultLanguage(lang); + return this; + }, + /** + * Load Translation + * @param lang + * @returns {Translation} + */ + loadTranslation: function (lang) { + this.setLang(lang || this.getLanguageFromWindowLocation()); + /** + * To maintain compatibility we use the same MAFE translation array. + * Now the translations of PMDynaform will also be in the same array. + */ + if (typeof __TRANSLATIONMAFE != 'undefined' && typeof __TRANSLATIONMAFE[this.getLang()] != 'undefined') { + this.loadLanguage(__TRANSLATIONMAFE.en, 'en'); + this.loadLanguage(__TRANSLATIONMAFE[this.getLang()], this.getLang()); + + this.setDefaultLanguage('en'); + this.setCurrentLanguage(this.getLang()); + } + return this; + }, +}; +PMDynaform.extendNamespace("PMDynaform.lang.Translation", Translation); + +var translatePMDynaform = new Translation(); +translatePMDynaform.loadTranslation(); +/** + * Singleton for implement the flow Case independent + * @type {{VERSION: string, view: {}, model: {}, collection: {}, Extension: {}, restData: {}, activeProject: null, FLashMessage: null}} + */ +var xCase = { + VERSION: "0.1.0", + view: {}, + model: {}, + collection: {}, + Extension: {}, + restData: {}, + activeProject: null, + FLashMessage: null +}; + +xCase.extendNamespace = function (path, newClass) { + var current, + pathArray, + extension, + i; + + if (arguments.length !== 2) { + throw new Error("xCase.extendNamespace(): method needs 2 arguments"); + } + + pathArray = path.split('.'); + if (pathArray[0] === 'xCase') { + pathArray = pathArray.slice(1); + } + current = xCase; + + // create the 'path' namespace + for (i = 0; i < pathArray.length - 1; i += 1) { + extension = pathArray[i]; + if (typeof current[extension] === 'undefined') { + current[extension] = {}; + } + current = current[extension]; + } + + extension = pathArray[pathArray.length - 1]; + if (current[extension]) { + + } + current[extension] = newClass; + return newClass; +}; +(function () { + /* + * @param {String} + * The following key selectors are availables for the + * getField and getGridField methods + * - Using '#', is possible select a field with the identifier of the field + * - Using ''. is possible select a field with the className of the field + * - Putting 'attr[name="my-name"]' is possible select fields with the same name attribute + **/ + var Selector = function (options) { + this.onSupportSelectorFields = null; + this.fields = {}; + this.queries = []; + this.form = {}; + + Selector.prototype.init.call(this, options); + }; + /** + * Initializes properties of the selector + * @param options + */ + Selector.prototype.init = function (options) { + var defaults = { + fields: {}, + queries: [], + form: {}, + onSupportSelectorFields: { + text: "onTextField", + textarea: "onTextAreaField" + } + }; + + $.extend(true, defaults, options); + + this.setOnSupportSelectorFields(defaults.onSupportSelectorFields) + .setFields(defaults.fields) + .setForms(defaults.form) + .applyGlobalSelectors(); + }; + Selector.prototype.addQuery = function (query) { + if (typeof query === "string") { + this.queries.push(query); + } else { + throw new Error("The query selector must be a string"); + } + + return this; + }; + Selector.prototype.setOnSupportSelectorFields = function (support) { + if (typeof support === "object") { + this.onSupportSelectorFields = support; + } else { + throw new Error("The parameter for the support fields is wrong"); + } + + return this; + }; + /** + * Sets fields + * @param fields + * @returns {Selector} + */ + Selector.prototype.setFields = function (fields) { + if (typeof fields === "object") { + this.fields = fields; + } + return this; + }; + /** + * Sets form + * @param form + * @returns {Selector} + */ + Selector.prototype.setForms = function (form) { + if (typeof form === "object") { + this.form = form; + } + return this; + }; + Selector.prototype.onTextField = function () { + return this; + }; + Selector.prototype.onTextAreaField = function () { + return this; + }; + /** + * Gets field instance searched + * @param selectorId + * @returns {object || null} + */ + Selector.prototype.findFieldById = function (selectorId) { + return selectorId && this.fields.hasOwnProperty(selectorId) ? + this.fields[selectorId] : null; + }; + /** + * Gets form instance by id + * @param selectorId + * @returns {object || null} + */ + Selector.prototype.findFormById = function (selectorId) { + return selectorId && this.form.model.get("id") === selectorId ? + this.form : null; + }; + /** + * Gets fields searched by name + * @param selectorAttr + * @returns {Array} + */ + Selector.prototype.findFieldByName = function (selectorAttr) { + var prop, + fieldFinded = []; + + for (prop in this.fields) { + if (this.fields[prop].model.get("name") === selectorAttr) { + fieldFinded.push(this.fields[prop]); + } + } + return fieldFinded; + }; + /** + * Gets fields by attribute + * @param parameter + * @param value + * @returns {Array} + */ + Selector.prototype.findFieldByAttribute = function (parameter, value) { + var prop, + fieldFinded = [], + modelField; + for (prop in this.fields) { + modelField = this.fields[prop].model; + if (value && modelField.attributes.hasOwnProperty(parameter) && modelField.get(parameter) === value) { + fieldFinded.push(this.fields[prop]); + } + } + return fieldFinded; + }; + /** + * findFieldByVariable: Gets a field considering the variable name as a parameter + * @returns {object} + */ + Selector.prototype.findFieldByVariable = function(selectorAttr) { + var prop, + fieldFinded; + for (prop in this.fields) { + if (this.fields[prop].model.get("variable") === selectorAttr) { + fieldFinded = this.fields[prop]; + break; + } + } + return fieldFinded; + }; + Selector.prototype.applyGlobalSelectors = function () { + var that = this; + + window.getFieldByAttribute = function (attr, value) { + that.addQuery(attr + ": " + value); + return that.findFieldByAttribute(attr, value); + }; + + window.getFieldById = function (query) { + that.addQuery("id: " + query); + return that.findFieldById(query); + }; + + window.getFieldByName = function (query) { + that.addQuery("name: " + query); + return that.findFieldByName(query); + }; + + window.getFormById = function (query) { + that.addQuery("id: " + query); + return that.findFormById(query); + }; + /** + * getFieldByVariable :Gets a field searched by the variable + * @returns {object|undefined} + */ + window.getFieldByVariable = function(query) { + that.addQuery("name: " + query); + return that.findFieldByVariable(query); + }; + /** + * get the subform with the supplied id + * @param id + * @returns {PMDynaform.view.SubForm|null} + */ + window.getSubformById = function (id) { + return that.findFieldById(id); + }; + return this; + }; + + PMDynaform.extendNamespace("PMDynaform.core.Selector", Selector); +}()); + +(function () { + + var Utils = { + generateID: function () { + var rand = function (min, max) { + // Returns a random number + // + // version: 1109.2015 + // discuss at: http://phpjs.org/functions/rand + // + original by: Leslie Hoare + // + bugfixed by: Onno Marsman + // % note 1: See the commented out code below for a + // version which will work with our experimental + // (though probably unnecessary) srand() function) + // * example 1: rand(1, 1); + // * returns 1: 1 + + // fix for jsLint + // from: var argc = arguments.length; + if (typeof min === "undefined") { + min = 0; + } + if (typeof max === "undefined") { + max = 999999999; + } + return Math.floor(Math.random() * (max - min + 1)) + min; + }, + uniqid = function (prefix, more_entropy) { + var php_js = {}, + retId, + formatSeed; + // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + revised by: Kankrelune (http://www.webfaktory.info/) + // % note 1: Uses an internal counter (in php_js global) to avoid collision + // * example 1: uniqid(); + // * returns 1: 'a30285b160c14' + // * example 2: uniqid('foo'); + // * returns 2: 'fooa30285b1cd361' + // * example 3: uniqid('bar', true); + // * returns 3: 'bara20285b23dfd1.31879087' + if (typeof prefix === 'undefined') { + prefix = ""; + } + + formatSeed = function (seed, reqWidth) { + var tempString = "", + i; + + seed = parseInt(seed, 10).toString(16); // to hex str + if (reqWidth < seed.length) { // so long we split + return seed.slice(seed.length - reqWidth); + } + if (reqWidth > seed.length) { // so short we pad + // jsLint fix + tempString = ""; + for (i = 0; i < 1 + (reqWidth - seed.length); i += 1) { + tempString += "0"; + } + return tempString + seed; + } + return seed; + }; + + // BEGIN REDUNDANT + if (!php_js) { + php_js = {}; + } + // END REDUNDANT + if (!php_js.uniqidSeed) { // init seed with big random int + php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15); + } + php_js.uniqidSeed += 1; + + retId = prefix; // start with prefix, add current milliseconds hex string + retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8); + retId += formatSeed(php_js.uniqidSeed, 5); // add seed hex string + if (more_entropy) { + // for more entropy we add a float lower to 10 + retId += (Math.random() * 10).toFixed(8).toString(); + } + + return retId; + }, + sUID; + + do { + sUID = uniqid(rand(0, 999999999), true); + sUID = sUID.replace('.', '0'); + } while (sUID.length !== 32); + + return "PMD-" + sUID; + }, + generateName: function (type) { + return type + "[" + PMDynaform.core.Utils.generateID() + "]"; + }, + /** + * validate JSON parse + * @param str + * @returns {boolean} + */ + isJsonAndParse: function (str) { + var result; + try { + result = JSON.parse(str); + } catch (e) { + result = str.split(','); + } + return result; + }, + /** + * check if it is a valid version of Internet Explorer for pmdynaform + */ + checkValidIEVersion: function () { + var version = false, + appName = navigator.appName, + appVersion = navigator.appVersion; + if (appName == "Netscape") { + if (appVersion.indexOf('Trident') !== -1){ + version = 11; + } + if(appVersion.indexOf('Edge') !== -1){ + version = 12; + } + } + return version; + } + }; + PMDynaform.extendNamespace("PMDynaform.core.Utils", Utils); + +}()); +(function () { + /** + * @class PMDynaform.util.ExternalLibraries + * Class that manages all external resources used and presented in json definition. + * + * The external libraries are used into a form as a externalLib property. + * + * The external library has the following types: + * - Regular js files + * - Regular css files + * - Images + * Example to use: + * // e.g. + * // let's assume that there are an arroy of external resources + * // let's assume that callback is callback function to render after all resources has been load + * + * this.externalLibraries = new PMDynaform.util.ExternalLibraries({ + * "libs": libs, + * "afterLoad": callback + * }); + * @param options + * @constructor + */ + var ExternalLibraries = function (options) { + this.libs = []; + this.cachedLibs = []; + this.afterLoad = null; + + ExternalLibraries.prototype.init.call(this, options); + }; + /** + * This function init the class External libraries + * * @param options + * @returns {CaseManager} + */ + ExternalLibraries.prototype.init = function (options) { + var defaults = { + "libs": [], + "afterLoad": null + }; + defaults = _.extend(defaults, options); + this.setLibs(defaults.libs) + .setAfterLoad(defaults.afterLoad); + return this; + }; + /** + * Loads all scripts, an arroy of all libraries is used to do that + * after has been load completly all libraries the collback afterLoad is executed + * @returns {ExternalLibraries} + */ + ExternalLibraries.prototype.setExternalLibreries = function (i) { + var that = this, link; + if (that.libs && i < that.libs.length) { + link = that.onLoadScript(that.libs[i]); + if (link) { + link.onload = function () { + that.setExternalLibreries(i + 1); + }; + link.onerror = function () { + console.error('invalid link :' + that.libs[i].url); + that.setExternalLibreries(i + 1); + }; + } else { + that.setExternalLibreries(i + 1); + } + } else { + this.afterLoad(); + } + }; + /** + * Hook to execute all scripts and call loadjscssfile method + * to load the external libraries and that is stored in cachedLibs property + * @param lib + * @returns {ExternalLibraries} + */ + ExternalLibraries.prototype.onLoadScript = function (lib) { + var type = lib.url.substring(lib.url.lastIndexOf(".") + 1); + this.cachedLibs.push(lib); + return this.loadjscssfile(lib.url, type); + }; + /** + * Append css or js external libraries to html head + * if filetype is not js or css return null, + * @param filename + * @param filetype + * @returns {*} + */ + ExternalLibraries.prototype.loadjscssfile = function (filename, filetype) { + var fileref = null; + if (filetype === "js") { //if filename is a external JavaScript file + fileref = document.createElement('script'); + fileref.setAttribute("type", "text/javascript"); + fileref.setAttribute("src", filename); + } else if (filetype === "css") { //if filename is an external CSS file + fileref = document.createElement("link"); + fileref.setAttribute("rel", "stylesheet"); + fileref.setAttribute("type", "text/css"); + fileref.setAttribute("href", filename); + } + if (fileref && fileref !== "undefined") { + document.getElementsByTagName("head")[0].appendChild(fileref); + } + return fileref; + }; + + /** + * Sets the array libs property + * @param libs + * @returns {ExternalLibraries} + */ + ExternalLibraries.prototype.setLibs = function (libs) { + if (_.isArray(libs)) { + this.libs = libs; + } + return this; + }; + /** + * Sets the afterLoad callback as a external library property + * @param callback + * @returns {ExternalLibraries} + */ + ExternalLibraries.prototype.setAfterLoad = function (callback) { + if (_.isFunction(callback)) { + this.afterLoad = callback; + } + return this; + }; + /** + * Gets the External library cachedLibs property + * @returns {Array} + */ + ExternalLibraries.prototype.getCachedLibs = function () { + return this.cachedLibs; + }; + /** + * Clean the External library cachedLibs property + */ + ExternalLibraries.prototype.clearCachedLibs = function () { + this.cachedLibs = []; + }; + + PMDynaform.extendNamespace("PMDynaform.util.ExternalLibraries", ExternalLibraries); +}()); +(function () { + /** + * Jquery Transport for download file type Blob. + */ + jQuery.ajaxTransport("binary", function(options, originalOptions, jqXHR) { + if (window.FormData && options && options.dataType && (options.dataType === 'binary' || options.dataType instanceof Blob) && + options.url && options.type && options.headers && + options.hasOwnProperty('async') && typeof options.async === "boolean") { + return { + send: function (headers, callback) { + var xhr = new XMLHttpRequest(), + url = options.url, + type = options.type, + asynchronous = options.async, + headers = options.headers, + dataType = options.responseType || 'blob', + data = {}; + xhr.addEventListener('load', function () { + data[options.dataType] = xhr.response; + callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders()); + }); + xhr.open(type, url, asynchronous); + xhr.setRequestHeader('Authorization', headers.authorization); + xhr.responseType = dataType; + xhr.send(data); + }, + abort: function () { + jqXHR.abort(); + } + }; + } + }); + +}()); +(function () { + var messageRequired = "This field is required.".translate(), + Validators = { + requiredText: { + message: messageRequired, + fn: function (val) { + var value = val; + if (_.isNumber(val)) { + value = val.toString(); + } + value = value.trim(); + if (value === null || value.length === 0 || /^\s+$/.test(value)) { + return false; + } + return true; + } + }, + requiredDropDown: { + message: messageRequired, + fn: function (value) { + value = typeof value === 'string' ? value.trim() : value; + return !!value || typeof value === 'number'; + } + }, + requiredCheckBox: { + message: messageRequired, + fn: function (value) { + if (typeof value === "number") { + var bool = (value > 0) ? true : false; + } else { + bool = false; + } + return bool; + } + }, + requiredCheckGroup: { + message: messageRequired, + fn: function (value) { + if (typeof value === "number") { + var bool = (value > 0) ? true : false; + } else { + bool = false; + } + return bool; + } + }, + requiredFile: { + message: messageRequired, + fn: function (value) { + value = value.trim(); + if (value === null || value.length === 0 || /^\s+$/.test(value)) { + return false; + } + return true; + } + }, + requiredRadioGroup: { + message: messageRequired, + fn: function (value) { + value = typeof value === 'string' ? value.trim() : value; + return !!value || typeof value === 'number'; + } + }, + integer: { + message: "Invalid value for the integer field".translate(), + mask: /[\d\.]/i, + fn: function (n) { + return (typeof n === 'string') ? /^-?\d+$/.test(n) : !isNaN(n = parseFloat(n, 10) && n % 1 === 0); + } + }, + float: { + message: "Invalid value for the float field".translate(), + fn: function (n) { + return /^-?\d+\.?\d*$/.test(n); + } + }, + string: { + fn: function (string) { + return true; + } + }, + boolean: { + fn: function (string) { + return true; + } + }, + maxLength: { + message: "The maximum length are ".translate(), + fn: function (value, maxLength) { + var maxLen; + if (typeof maxLength !== "number") { + throw new Error("The parameter maxlength is not a number".translate()); + } + maxLen = (value.toString().length <= maxLength) ? true : false; + return maxLen; + } + }, + /** + * validate that there is at least one row on the grid + * return [boolean] + */ + requiredGrid: { + message: "Information Required".translate(), + fn: function (value) { + if (value === null || value === 0) { + return false; + } + return true; + } + } + }; + + PMDynaform.extendNamespace("PMDynaform.core.Validators", Validators); +}()); + +(function () { + var ModalProgressBar = Backbone.View.extend({ + timeHide: 1000, + template: _.template($("#tpl-modal-global").html()), + initialize: function () { + //TODO: no need params. + }, + render: function () { + if ($('#modalProgressBar').length) { + $('#modalProgressBar').remove(); + } + $('body').append(this.template()); + this.show(); + return this; + }, + show: function () { + $('#modalProgressBar').modal({backdrop: 'static', keyboard: false}, 'show'); + return this; + }, + hide: function () { + if ($('#modalProgressBar').length) { + setTimeout(function () { + $('#modalProgressBar').modal('hide'); + }, this.timeHide); + } + return this; + }, + setTimeHide: function (timeHide) { + this.timeHide = timeHide; + return this; + }, + getTimeHide: function () { + return this.timeHide; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.ModalProgressBar", ModalProgressBar); +}()); +(function () { + var Project = function (options) { + this.model = null; + this.modalProgress = null; + this.view = null; + this.data = null; + this.delIndex = null; + this.fields = null; + this.keys = null; + this.token = null; + this.renderTo = null; + this.urlFormat = null; + this.endPointsPath = null; + this.forms = null; + this.externalLibs = null; + this.externalLibsArray = []; + this.dependentLibraries = null; + this.submitRest = null; + this.formAjax = null; + this.globalMode = null; + this.onSubmitForm = new Function(); + this.language = ""; + this.onBeforePrintHandler = null; + this.onAfterPrintHanlder = null; + this.flashView = null; + this.isRTL = false; + this.isPreview = false; + this.dynaformUid = null; + this.googleMaps = { + key: "" + }; + this.loadDataField = true; + Project.prototype.init.call(this, options); + }; + + Project.prototype.init = function (options) { + var defaults = new PMDynaform.util.InputsValidation(), + that = this; + defaults = jQuery.extend(true, defaults.getDefaultData(), options); + defaults.endPointsPath = { + project: "", + createVariable: "process-variable", + variableList: "process-variable", + /** + * @key {var_uid} Defines the identifier of the variable + * The Endpoint is for get all information about Variable + **/ + variableInfo: "process-variable/{var_uid}", + /** + * @key {var_name} Defines the variable name + * The Endpoint executes the query associated to variable + **/ + executeQuery: "process-variable/{var_name}/execute-query", + /** + * + * @key {field_name} Defines the field name + * The Endpoint uploads a file + **/ + uploadFile: "uploadfile/{field_name}", + executeQuerySuggest: "process-variable/{var_name}/execute-query-suggest", + fileStreaming: "en/neoclassic/cases/casesStreamingFile?actionAjax=streaming&a={caseID}&d={fileId}", + getAllDataCase: "case/{caseID}/variables", + imageDownload: 'light/case/{caseID}/download64', + fileDownload: "case/{caseID}/file/{fileID}", + imageInfo: "light/case/{caseID}/download64", + getImageGeo: "light/case/{caseID}/download64" + }; + defaults.urlFormatMobile = "{server}/api/1.0/{workspace}/{endPointPath}"; + defaults.urlFormat = "{server}/{apiName}/{apiVersion}/{workspace}/{keyProject}/{projectId}/{endPointPath}"; + this.urlFormatStreaming = "{server}/sys{workspace}/{endPointPath}"; + that.setIsRTL(defaults.isRTL); + that.setIsPreview(defaults.isPreview); + $("body").append("
    "); + this.loadExternalLibs(defaults.data, defaults.keys.server, function () { + that.delIndex = defaults.delIndex; + that.setDynaformUID(defaults.dynaformUid); + that.setFormAjax(defaults.formAjax); + that.setBeforePrintHandler(defaults.onBeforePrintHandler); + that.setAfterPrintHandler(defaults.onAfterPrintHandler); + that.setData(defaults.data); + that.setLanguage(); + that.initModalProgress(); + that.setUrlFormat(defaults.urlFormat); + that.setUrlFormatMobile(defaults.urlFormatMobile); + that.setKeys(defaults.keys); + that.setToken(defaults.token); + that.setRenderTo(defaults.renderTo); + that.setEndPointsPath(defaults.endPointsPath); + that.setGoogleMapsSettings(defaults.googleMaps); + that.createWebServiceManager(); + PMDynaform.setActiveProject(that); + that.checkMobileData(); + that.submitRest = defaults.submitRest; + if (!PMDynaform.core.ProjectMobile) { + that.checkGeoMapsLibraries(defaults.onLoad); + } else { + that.checkGeoMapsLibraries(); + } + //stop loading + $("body").find(".pmDynaformLoading").remove(); + }); + }; + Project.prototype.setDynaformUID = function (dynUid) { + var dyn_uid = null; + if (dynUid || dynUid === null) { + dyn_uid = dynUid; + } + this.dynaformUid = dyn_uid; + return this; + }; + /** + * sets the value true if the project is a preview of processmaker + * and false if it is running case + * @param value, true or false + * @returns {Project} + */ + Project.prototype.setIsPreview = function (value) { + if ((typeof value === "boolean") && value) { + this.isPreview = true; + } else { + this.isPreview = false; + } + return this; + }; + /** + * setIsRTL + * if the project is actually owned RTL this fixed property to adds + * a stylesheet to support RTL + */ + Project.prototype.setIsRTL = function (value) { + if (typeof value === "boolean") { + this.isRTL = value; + } else { + if (window.isRTL != undefined && window.isRTL != null) { + this.isRTL = typeof window.isRTL === "boolean" ? window.isRTL : false; + } + } + if (this.isRTL) { + this.addCSSToRTL(); + } else { + this.removeCSSToRTL(); + } + }; + /** + * getIsRTL + * get the value of the property isRTL, this can be true or false + */ + Project.prototype.getIsRTL = function () { + return this.isRTL; + }; + /** + * addCSSToRTL + * add a stylesheet with support of view (right to left) + */ + Project.prototype.addCSSToRTL = function () { + var link = document.createElement("link"); + link.rel = "stylesheet"; + link.id = "rtl-style"; + if (window.pathRTLCss !== undefined && window.pathRTLCss !== null) { + link.href = window.pathRTLCss; + PMDynaform.PATH_RTL_CSS = window.pathRTLCss; + } else { + link.href = PMDynaform.PATH_RTL_CSS || ""; + } + document.head.appendChild(link); + return this; + }; + /** + * Remove CSS RTL + * @returns {Project} + */ + Project.prototype.removeCSSToRTL = function () { + var link = $("#rtl-style"); + if (link) { + link.remove(); + } + return this; + }; + + Project.prototype.setFormAjax = function (params) { + if (params) { + this.formAjax = params; + } + return this; + }; + Project.prototype.getFormAjax = function () { + return this.formAjax; + }; + Project.prototype.initModalProgress = function () { + this.modalProgress = new PMDynaform.view.ModalProgressBar(); + return this; + }; + /** + * @param globalMode + * @returns {Project} + */ + Project.prototype.setGlobalMode = function (globalMode) { + if (globalMode) { + this.globalMode = globalMode; + } + return this; + }; + Project.prototype.checkMobileData = function () { + if (!PMDynaform.core.ProjectMobile) { + this.mobileDataControls = this.loadAllDataCase(); + } + return this; + }; + Project.prototype.setLanguage = function () { + if (window.sysLang) { + this.language = window.sysLang; + } + return this; + }; + + /** + * Loads external libraries, here instance ExternalLibraries class. + * @param jsonForm + * @param callback + */ + Project.prototype.loadExternalLibs = function (jsonForm, server, callback) { + var libs = this.prepareLibsPath(jsonForm, server); + this.externalLibraries = new PMDynaform.util.ExternalLibraries({ + "libs": libs, + "afterLoad": callback + }); + this.externalLibraries.setExternalLibreries(0); + + }; + /** + * Prepare external libraries path + * @returns {Array} + */ + Project.prototype.prepareLibsPath = function (jsonForm, server) { + var expression = /^(?:(http|https):)?(\/{2,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/; + this.getAllExternalLibs(jsonForm, true); + return _.map(this.externalLibsArray, function (lib) { + lib = $.trim(lib); + if (!expression.test(lib) && lib !== "") { + lib = (lib.charAt(0) !== '/') ? '/' + lib : lib; + lib = server + lib; + + } + return { + "url": lib, + "skipCache": true + }; + }); + }; + /** + * Gets all external libraries considering json definition, that method is recursive. + * @param jsonForm + * @param externalLibs + * @param root + * @returns {*} + */ + Project.prototype.getAllExternalLibs = function (jsonForm, root) { + var i, + form, + result = "", + max; + if (root) { + if (_.isArray(jsonForm.items)) { + for (i = 0, max = jsonForm.items.length; i < max; i += 1) { + form = jsonForm.items[i]; + if (form.type === 'form') { + result = (typeof form.externalLibs !== 'undefined' && form.externalLibs !== null) ? + form.externalLibs.replace(/\s+/g, '') : result; + if (result !== "") { + result = result.split(","); + this.externalLibsArray = _.union(this.externalLibsArray, result); + } + if (form.items && form.items.length > 0) { + this.getAllExternalLibs(form.items, false); + } + + } + } + } + } else { + for (i = 0, max = jsonForm.length; i < max; i += 1) { + form = jsonForm[i]; + if (form[0].items && form[0].items.length > 0) { + if (form[0].type === 'form') { + result = (typeof form[0].externalLibs !== 'undefined' && form[0].externalLibs !== null) ? + form[0].externalLibs.replace(/\s+/g, '') : result; + if (result !== "") { + result = result.split(","); + this.externalLibsArray = _.union(this.externalLibsArray, result); + this.getAllExternalLibs(form[0], true); + } + + } + } + } + } + }; + + Project.prototype.setData = function (data) { + if (typeof data === "object") { + this.data = data; + } + if (this.view) { + this.destroy(); + this.loadProject(); + } + return this; + }; + Project.prototype.setData2 = function (data) { + this.view.setData2(data); + return this; + }; + /** + * setAppData Sets the data to the form + * @param {object} Set of valid data for the form + */ + Project.prototype.setAppData = function(data) { + var forms = this.getForms(), + firstForm = 0; + if (_.isArray(forms) && forms.length) { + forms[firstForm].setAppData(data); + } + return this; + }; + Project.prototype.setUrlFormat = function (url) { + if (typeof url === "string") { + this.urlFormat = url; + } + return this; + }; + Project.prototype.setUrlFormatMobile = function (url) { + if (typeof url === "string") { + this.urlFormatMobile = url; + } + return this; + }; + Project.prototype.setKeys = function (keys) { + var keysFixed = {}, + key, + leftBracket; + if (!PMDynaform.core.ProjectMobile) { + if (keys.server.indexOf("http://") == -1 || keys.server.indexOf("https://") == -1) { + keys.server = keys.server; + } + } + if (typeof keys === "object") { + for (key in keys) { + leftBracket = (keys[key][0] === "/") ? keys[key].substring(1) : keys[key]; + keysFixed[key] = (leftBracket[leftBracket.length - 1] === "/") ? leftBracket.substring(0, leftBracket.length - 1) : leftBracket; + } + this.keys = keysFixed; + } + return this; + }; + Project.prototype.setToken = function (objToken) { + if (typeof objToken === "object") { + this.token = objToken; + } + + return this; + }; + Project.prototype.setRenderTo = function (to) { + this.renderTo = to; + + return this; + }; + Project.prototype.setEndPointsPath = function (endpoints) { + var leftBracket, + point, + endpointsVerified = {}; + + for (point in endpoints) { + if (typeof endpoints[point] === "string") { + leftBracket = (endpoints[point][0] === "/") ? endpoints[point].substring(1) : endpoints[point]; + endpointsVerified[point] = (endpoints[point][endpoints[point].length - 1] === "/") ? + endpoints[point].substring(0, endpoints[point].length - 1) : + endpoints[point]; + } else { + throw new Error("The endpoint path is not correct, " + endpoints[point]); + } + } + this.endPointsPath = endpointsVerified; + + return this; + }; + /** + * Sets the google maps keys and other settings + * @param {*} settings + */ + Project.prototype.setGoogleMapsSettings = function (settings) { + if (settings) { + this.googleMaps = settings; + } + return this; + }; + Project.prototype.checkGeoMapsLibraries = function (onload) { + var i, + libs = [], + enableGeoMap = false, + searchingMap, + forms = this.data.items; + + searchingMap = function (fields) { + var j, + k, + l, + dependent = [ + "geomap", + "other", + "location" + ]; + + outer_loop: + for (j = 0; j < fields.length; j += 1) { + for (k = 0; k < fields[j].length; k += 1) { + if ($.inArray(fields[j][k].type, dependent) >= 0) { + enableGeoMap = true; + break outer_loop; + } else if (fields[j][k].type === "form") { + searchingMap(fields[j][k].items); + } + } + } + }; + + for (i = 0; i < forms.length; i += 1) { + searchingMap(forms[i].items || []); + } + + if (enableGeoMap) { + this.loadGeoMapDependencies(onload); + } else { + this.loadProject(onload); + } + + return this; + }; + Project.prototype.checkScript = function () { + var i, j, k, code, model, scriptCode = "", rows, item, type, row; + for (i = 0; i < this.forms.length; i += 1) { + rows = this.forms[i].model.get("items"); + if (!_.isEmpty(this.forms[i].model.get("script"))) { + scriptCode = scriptCode.concat(this.forms[i].model.get("script").code); + } + for (j = 0; j < rows.length; j += 1) { + row = rows[j]; + for (var k = 0; k < row.length; k += 1) { + item = row[k]; + if (item.type === "form") { + if (!_.isEmpty(item.script)) { + scriptCode = scriptCode.concat(item.script.code); + } + } + } + } + } + if (scriptCode.trim().length) { + code = new PMDynaform.core.Script({ + script: scriptCode + }); + code.render(); + } + }; + Project.prototype.setAllFields = function (fields) { + if (typeof fields === "object") { + this.fields = fields; + this.selector.setFields(fields); + } + return this; + }; + Project.prototype.getModelForm = function (index) { + if (this.data.items[index] !== undefined) { + return this.data.items[index]; + } else { + return false; + } + }; + + Project.prototype.loadProject = function (onload) { + var that = this, firstForm; + firstForm = this.getModelForm(0); + if (firstForm) { + if (typeof this.onBeforePrintHandler === "function") { + firstForm.onBeforePrintHandler = this.onBeforePrintHandler; + } + if (typeof this.onAfterPrintHandler === "function") { + firstForm.onAfterPrintHandler = this.onAfterPrintHandler; + } + } + this.model = new PMDynaform.model.Panel(this.data); + this.view = new PMDynaform.view.Panel({ + tagName: "div", + renderTo: this.renderTo, + model: this.model, + project: this + }); + this.flashMessage(); + if (onload && typeof onload === "function") { + onload(); + } + this.forms = this.view.getPanels(); + this.createGlobalPmdynaformClass(this.view); + this.createSelectors(); + this.checkScript(); + this.createMessageLoading(); + that.view.afterRender(); + that.view.$el.find(".pmdynaform-form-message-loading").remove(); + $("#shadow-form").remove(); + this.onScrollUpdate(); + return this; + }; + Project.prototype.createMessageLoading = function () { + var msgTpl = _.template($('#tpl-loading').html()); + this.view.$el.prepend(msgTpl({ + title: "Loading", + msg: "Please wait while the data is loading..." + })); + this.view.$el.find("#shadow-form").css("height", this.view.$el.height() + "px"); + }; + /** + * Create selector instance + * @returns {Project} + */ + Project.prototype.createSelectors = function () { + var currentForm = this.getForm(), + allFields = this.getAllItems(currentForm); + + this.fields = allFields; + this.selector = new PMDynaform.core.Selector({ + fields: allFields, + form: currentForm + }); + return this; + }; + /** + * Creates a object with all children fields of the + * form (included the fields into SubForms and SubForms objects) ordered by id. + * Example: + * { + * "textVar001": [Object View], + * "textareaVar001": [Object View], + * "suggestVar001": [Object View], + * "dropdownVar001": [Object View], + * "checkboxVar001": [Object View], + * "32123154646546545644565": [Object View], //SubFormId + * "textareaSubForm": [object View] // Children SubForm + * ... + * } + * @param form + * @returns {{}} + */ + Project.prototype.getAllItems = function (form) { + var that = this, + formItems = form ? form.getFields() : [], + type, + items = {}, + subItems = {}; + + if (formItems.length) { + $.each(formItems, function (index, item) { + type = item.model.get("type"); + if (type !== "empty") { + items[item.model.get("id")] = item; + if (type === "form") { + subItems = that.getAllItems(item.getFormView()); + } + $.extend(items, subItems); + } + }); + } + return items; + }; + Project.prototype.createGlobalPmdynaformClass = function (form) { + + }; + Project.prototype.loadGeoMapDependencies = function (onload) { + var i, + auxClass, + instanceClass, + that = this, + loadScript = true, + libs = ""; + + libs = document.body.getElementsByTagName("script"); + outer_script: + for (i = 0; i < libs.length; i += 1) { + if ($(libs[i]).data) { + if ($(libs[i]).data("script") === "google") { + loadScript = false; + break outer_script; + } + } + } + if (loadScript) { + auxClass = function (params) { + this.project = params.project; + }; + auxClass.prototype.load = function () { + this.project.loadProject(onload); + }; + window.pmd = new auxClass({project: this}); + var script = document.createElement('script'); + script.type = 'text/javascript'; + $(script).data("script", "google"); + script.src = "https://maps.googleapis.com/maps/api/js?callback=pmd.load"; + script.src += window.pmd.project.googleMaps.key ? "&key=" + window.pmd.project.googleMaps.key : ""; + document.body.appendChild(script); + } else { + this.loadProject(onload); + } + return this; + }; + Project.prototype.registerKey = function (key, value) { + if ((typeof key === "string") && (typeof value === "string")) { + if (!this.keys[key]) { + this.keys[key] = value; + } else { + throw new Error("The key already exists."); + } + } else { + throw new Error("The parameters must be strings."); + } + + return this; + }; + Project.prototype.getEndPoint = function (type) { + return this.endPointsPath[type]; + }; + Project.prototype.setModel = function (model) { + if (model instanceof Backbone.Model) { + this.model = model; + } + return this; + }; + Project.prototype.setView = function (view) { + if (view instanceof Backbone.View) { + this.view = view; + } + return this; + }; + /** + * Gets the current form + * @returns {object || null} + */ + Project.prototype.getForm = function () { + var forms = this.getForms(), + index = 0; + return forms && forms.length ? forms[index] : null; + }; + /** + * Gets Array forms + * @returns {array || null} + */ + Project.prototype.getForms = function () { + var forms; + if (this.view instanceof PMDynaform.view.Panel) { + forms = this.view.getPanels(); + } + return forms; + }; + Project.prototype.getData = function () { + var formData = this.view.getData(); + + return formData; + }; + Project.prototype.destroy = function () { + this.view.$el.remove(); + + return this; + }; + /* + Mobile project methods + */ + Project.prototype.loadAllDataCase = function () { + var restClient, endpoint, url, that = this, resp = {}; + if (window.app_uid) { + this.webServiceManager.getData(function (err, data) { + if (!err) { + resp = data; + } + }); + } + return resp; + }; + + Project.prototype.getFullEndPoint = function (urlEndpoint) { + var k, + keys = this.keys, + urlFormat = urlEndpoint; + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlFormat = urlFormat.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + return urlFormat; + }; + Project.prototype.getFullURLMobile = function (endpoint) { + var k, + keys = this.keys, + urlFormat = this.urlFormatMobile; + urlFormat = urlFormat.replace(/{endPointPath}/, endpoint); + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlFormat = urlFormat.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + urlFormat = window.location.protocol + "//" + urlFormat.replace(/{endPointPath}/, endpoint); + return urlFormat; + }; + Project.prototype.getFullURL = function (endpoint) { + var k, + keys = this.keys, + urlFormat = this.urlFormat; + + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlFormat = urlFormat.replace(new RegExp("{" + k + "}", "g"), keys[k]); + //endPointFixed =endpoint.replace(new RegExp(variable, "g"), keys[variable]); + } + } + urlFormat = window.location.protocol + "//" + urlFormat.replace(/{endPointPath}/, endpoint); + if (urlFormat.indexOf("file") > -1) { + urlFormat = urlFormat.replace(/file/g, "http"); + } + return urlFormat; + }; + + Project.prototype.getFullURLStreaming = function (endpoint) { + var k, + keys = this.keys, + urlFormat = this.urlFormatStreaming; + urlFormat = urlFormat.replace(/{endPointPath}/, endpoint); + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlFormat = urlFormat.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + urlFormat = window.location.protocol + "//" + urlFormat.replace(/{endPointPath}/, endpoint); + return urlFormat; + }; + Project.prototype.createWebServiceManager = function () { + var keys1 = { + server: this.keys.server, + processUID: this.keys.projectId, + taskUID: window.app_uid ? window.app_uid : null, + caseUID: window.app_uid ? window.app_uid : null, + workspace: this.keys.workspace, + formUID: null, + keyProject: "project", + stepID: null, + delIndex: this.delIndex, + dyn_uid: this.dynaformUid + }; + + this.webServiceManager = new xCase.service.WebServiceManager({ + keys: keys1, + token: this.token, + language: this.language + }); + }; + Project.prototype.setBeforePrintHandler = function (handler) { + if (typeof handler === "function") { + this.onBeforePrintHandler = handler; + } else { + handler = null; + } + return this; + }; + Project.prototype.setAfterPrintHandler = function (handler) { + if (typeof handler === "function") { + this.onAfterPrintHandler = handler; + } else { + handler = null; + } + return this; + }; + Project.prototype.flashMessage = function (config) { + if (typeof config === "object") { + if (!Project.flashMessage) { + this.flashModel = new PMDynaform.ui.FlashMessageModel({ + message: config.message || "", + emphasisMessage: config.emphasisMessage || "", + startAnimation: config.startAnimation || 1000, + type: config.type || "info", + appendTo: config.appendTo || document.body, + duration: config.duration, + absoluteTop: config.absoluteTop || false + }); + this.flashView = new PMDynaform.ui.FlashMessageView({ + model: this.flashModel + }); + } else { + this.configFlashMessage(config); + } + this.flashView.render(); + if (this.flashModel.get("absoluteTop")) { + this.onScrollUpdate(this.flashView.el); + } + } + return this; + }; + Project.prototype.configFlashMessage = function (config) { + if (this.flashModel && this.flashModel instanceof PMDynaform.ui.FlashMessageModel) { + this.flashModel.set("message", config.message || "undefined message"); + this.flashModel.set("emphasisMessage", config.emphasisMessage || "undefined emphasisMessage"); + this.flashModel.set("startAnimation", config.startAnimation || 500); + this.flashModel.set("type", config.type || "info"); + this.flashModel.set("appendTo", config.appendTo || document.body); + this.flashModel.set("duration", config.duration || 1500); + this.flashModel.set("absoluteTop", config.absoluteTop || false); + } + return this; + }; + Project.prototype.hideCalendars = function (exclude) { + var dateTimePicker, + picker, + i; + + dateTimePicker = $(document).find(".datetime-container").children(); + for (i = 0; i < dateTimePicker.length; i += 1) { + if (dateTimePicker.get(i) === exclude) { + continue; + } + if (dateTimePicker.eq(i).data) { + picker = dateTimePicker.eq(i).data().DateTimePicker; + if (picker) { + picker.hide(); + } + } + } + }; + Project.prototype.onScrollUpdate = function (element) { + var that = this; + + if (!this.isMobile()) { + $(window).scroll(function () { + if (element) { + element.style.top = $(document).scrollTop() + "px"; + } + that.hideCalendars(); + }); + } + }; + Project.prototype.isMobile = function () { + return !!PMDynaform.core.ProjectMobile; + }; + + /** + * getDynUID: Get the form id, to consume services + * @returns {string} + */ + Project.prototype.getDynUID = function() { + var content = this.data, + masterFormIndex = 0; + if (content && _.isArray(content.items) && content.items[masterFormIndex]) { + return content.items[masterFormIndex].id; + } + return null; + }; + /** + * Gets current language. + * @returns {string} + */ + Project.prototype.getLanguage = function () { + return this.language || 'en'; + }; + + PMDynaform.extendNamespace("PMDynaform.core.Project", Project); + +}()); + +(function () { + /** + * @class PMDynaform.core.TokenStream + * Class to handle tokens or attributes for build de Formula + * @param {Object} tokens + */ + var TokenStream = function (tokens) { + /** + * @property {Number} [cursor=0] The property represents the current index + * of the tokens array. + * @private + */ + this.cursor = 0; + /** + * @property {Object} Encapsulate all tokens passed as parameter + * @private + */ + this.tokens = tokens; + }; + /** + * Gets the next token element of the array + * @return {String} element selected. + * @private + */ + TokenStream.prototype.next = function () { + return this.tokens[this.cursor++]; + }; + /** + * The method helps in the cases when exist brackets inside of Formula + * @private + * @param {String} direction + * @return {String} token Element selected from token array + */ + TokenStream.prototype.peek = function (direction) { + if (direction === undefined) { + direction = 0; + } + return this.tokens[this.cursor + direction]; + }; + PMDynaform.extendNamespace("PMDynaform.core.TokenStream", TokenStream); + + + /** + * @class PMDynaform.core.Tokenizer + * Class to manage all fields and their values, those values may be CONSTANTS, + * MATH functions and FIELDS. + * @param {Object} tokens + */ + var Tokenizer = function () { + /** + * @property {Number} [tokens={}] The property represents all the tokens stored + * @private + */ + this.tokens = {}; + /** + * @property {String} [regex=null] Represents the property that encapsulate the execution + * of the Regular Expression when the token is been finded or executed + * @private + */ + this.regex = null; + /** + * @property {Array} [fields=[]] Encapsulate all the fields associated or that are inside + * of the tokens + * @private + */ + this.fields = []; + /** + * @property {Array} [tokenNames=[]] All the names of the tokens are stored in the array + * @private + */ + this.tokenNames = []; + /** + * @property {Object} [tokenFields={}] All the tokens fields are stored in this property + * @private + */ + this.tokenFields = {}; + }; + /** + * Adds new token to tokens array. If the element already exist this is replaced. + * @param {String} name The name corresponde to name of the property inside of the tokens + * @param {String} expression This is the value if the element is a field and is an expression + * if the element is a bracket or some function. + * @private + */ + Tokenizer.prototype.addToken = function (name, expression) { + this.tokens[name] = expression; + }; + /** + * Adds new expression to field + * @param {String} name Parameter that describes to new element (Must of times is 'field') + * @param {String} expression Value of the new element (Must of times is the name of the field) + * @private + */ + Tokenizer.prototype.addField = function (name, expression) { + var expr; + + if ($.inArray(expression, this.fields) === -1) { + this.fields.push(expression); + } + + expr = this.fields.toString().replace(/,/g, "|"); + expr = expr.replace(new RegExp("\\[", "g"), "\\["); + expr = expr.replace(new RegExp("\\]", "g"), "\\]"); + this.tokens[name] = expr; + }; + /** + * Sets the value for the field selected + * @param {String} name Corresponds to name of the field + * @param {String||Number} value Value for the field + * @private + */ + Tokenizer.prototype.addTokenValue = function (name, value) { + this.tokenFields[name] = parseFloat(value); + }; + /** + * Executes and find tokens based on the formula expression + * @param {Object} data + * @private + */ + Tokenizer.prototype.tokenize = function (data) { + var tokens; + + this.buildExpression(data); + tokens = this.findTokens(data); + + return new TokenStream(tokens); + }; + /** + * Builds the formula expression separating by tokens + * @param {object} data Represent the data of the formula + * @private + */ + Tokenizer.prototype.buildExpression = function (data) { + var tokenRegex = [], + tokenName; + + for (tokenName in this.tokens) { + this.tokenNames.push(tokenName); + tokenRegex.push('(' + this.tokens[tokenName] + ')'); + } + + this.regex = new RegExp(tokenRegex.join('|'), 'g'); + }; + /** + * Find the tokens based of the data parameter and build an tokens array + * @param {String} data + * @private + */ + Tokenizer.prototype.findTokens = function (data) { + var tokens = [], + match, + group; + + while ((match = this.regex.exec(data)) !== null) { + if (match === undefined) { + continue; + } + + for (group = 1; group < match.length; group += 1) { + if (!match[group]) continue; + + tokens.push({ + name: this.tokenNames[group - 1], + data: match[group], + value: null + }); + } + } + + return tokens; + }; + PMDynaform.extendNamespace("PMDynaform.core.Tokenizer", Tokenizer); + + /** + * @class PMDynaform.core.Formula + * Class to handle all the formula property. The class support brackets that encapsulates + to numbers, mathematical operations and functions. + * @param {Object} tokens + */ + var Formula = function (data) { + this.data = data.toString(); + this.tokenizer = new Tokenizer(); + + }; + /** + * Initializes tokens by default, like division, multiplication, constant and function. + * Using the {@link PMDynaform.core.Tokenizer Tokenizer} class for sets the new tokens + */ + Formula.prototype.initializeTokens = function () { + this.tokenizer.addToken('whitespace', '\\s+'); + this.tokenizer.addToken('l_paren', '\\('); + this.tokenizer.addToken('r_paren', '\\)'); + this.tokenizer.addToken('float', '[0-9]+\\.[0-9]+'); + this.tokenizer.addToken('int', '[0-9]+'); + this.tokenizer.addToken('div', '\\/'); + this.tokenizer.addToken('mul', '\\*'); + this.tokenizer.addToken('add', '\\+'); + this.tokenizer.addToken('sub', '\\-'); + this.tokenizer.addToken('constant', 'pi|PI'); + this.tokenizer.addToken('function', '[a-zA-Z_][a-zA-Z0-9_]*'); + + return this; + }; + /** + * Adds new token using the {@link PMDynaform.core.Tokenizer Tokenizer} class for + * set the data + * @param {String} name Name of the token + * @param {String} value Value for the new token + */ + Formula.prototype.addToken = function (name, value) { + this.tokenizer.addToken(name, value); + return this; + }; + /** + * Adds new token using the {@link PMDynaform.core.Tokenizer Tokenizer} class for + * set the data + * @param {String} name Name of the token + * @param {String} value Value for the new token + */ + Formula.prototype.addField = function (name, value) { + this.tokenizer.addField(name, value); + return this; + }; + /** + * Adds value for the field using {@link PMDynaform.core.Tokenizer Tokenizer} class for set + * the data + * @param {String} name Name of the token + * @param {String} value Value for the new token + */ + Formula.prototype.addTokenValue = function (name, value) { + this.tokenizer.addTokenValue(name, value); + + return this; + }; + /** + * The current method add the prefix 'Math' to data from token + * @param {String} token Represents the token + * @return {String} Return the Mathematical valid data + */ + Formula.prototype.consumeConstant = function (token) { + return 'Math.' + token.data.toUpperCase(); + }; + /** + * Gets the valid value for the field passed as parameter + * @param {String} token Token that represent the data of the field + * @return {String} + */ + Formula.prototype.consumeField = function (token) { + return (this.tokenizer.tokenFields[token.data] === undefined) ? 0 : this.tokenizer.tokenFields[token.data]; + }; + /** + * Adds new token using the {@link PMDynaform.core.Tokenizer Tokenizer} class + * @param {String} name Name of the token + * @param {String} value Value for the new token + */ + Formula.prototype.consumeFunction = function (ts, token) { + var a = [token.data], + t; + + while (t = ts.next()) { + a.push(t.data); + if (t.name === 'r_paren') { + break; + } + } + + return 'Math.' + a.join(''); + }; + /** + * Adds new token using the {@link PMDynaform.core.Tokenizer Tokenizer} class + * @param {String} name Name of the token + * @param {String} value Value for the new token + */ + Formula.prototype.evaluate = function () { + var ts, + valueFixed, + expr = [], + e, + t, + message, + auxExpr; + + this.initializeTokens(); + ts = this.tokenizer.tokenize(this.data); + + while (t = ts.next()) { + switch (t.name) { + case 'int': + case 'float': + case 'mul': + case 'div': + case 'sub': + case 'add': + + expr.push(t.data); + break; + case 'field': + expr.push(this.consumeField(t)); + break; + case 'constant': + expr.push(this.consumeConstant(t)); + break; + case 'l_paren': + expr.push("("); + break; + case 'r_paren': + expr.push(")"); + break; + case 'function': + var n = ts.peek(); + if (n && n.name === 'l_paren') { + expr.push(this.consumeFunction(ts, t)); + continue; + } + default: + break; + } + } + auxExpr = []; + for (var i = 0; i < expr.length; i += 1) { + if (typeof expr[i] === "number") { + auxExpr.push("(" + expr[i] + ")"); + } else { + auxExpr.push(expr[i]); + } + } + expr = auxExpr; + e = expr.join(''); + try { + valueFixed = (new Function('return ' + e))(); + } catch (e) { + valueFixed = 0; + message = new PMDynaform.implements.Logger(); + message.showMessage("formula"); + throw new Error("Error in the formula property"); + } + valueFixed = _.isNaN(valueFixed) ? "" : valueFixed; + return valueFixed; + }; + + PMDynaform.extendNamespace("PMDynaform.core.Formula", Formula); +}()); + + +(function () { + var WebServiceManager = function (options) { + /* + options.keys + options.endPoints + options.urlBase + options.token + */ + this.options = options || {}; + this.options.endPoints = { + startCase: "light/process/{processUID}/task/{taskUID}/start-case", + trigger: "light/process/{processUID}/task/{taskUID}/case/{caseUID}/step/{stepUID}/execute-trigger/{triggerOption}", + getData: "light/{caseUID}/variables?pro_uid={processUID}&act_uid={taskUID}&app_index={delIndex}&dyn_uid={dyn_uid}", + conditionalSteps: "light/process/{processUID}/case/{caseUID}/{delIndex}/step/{stepPosition}", + form: "light/project/{processUID}/dynaforms", + saveData: "light/{caseUID}/variable?dyn_uid={formUID}&del_index={delIndex}", + query: "project/{processUID}/process-variable/{var_name}/execute-query", + querySuggest: "project/{processUID}/process-variable/{var_name}/execute-query-suggest", + imageInfo: "light/case/{caseUID}/download64", + nextStep: "light/get-next-step/{caseUID}", + uploadMultipart: "case/{caseUID}/upload/{var_name}", + uploadMultipartInputDoc: "case/{caseUID}/upload/{var_name}/{docUID}", + uploadMultipartVersion: "case/{caseUID}/upload/{var_name}/{docUID}/{appDocUid}", + fileStreaming: "en/neoclassic/cases/casesStreamingFile?actionAjax=streaming&a={caseUID}&d={fileId}", + fileVersionsList: "cases/{caseUID}/input-document/{docUID}/versions", + downloadFile: "cases/{caseUID}/input-document/{docUID}/file?v={version}", + userInfo: "light/user/data" + }; + this.options.links = { + showDocument: "{server}/sys{workspace}/en/{skin}/cases/cases_ShowDocument?a={docUID}&v={version}" + }; + this.options.urlBase = "{server}/api/1.0/{workspace}/{endPointPath}"; + this.options.urlBaseStreaming = "{server}/sys{workspace}/{endPointPath}"; + this.memoryCache = {}; + + }; + + WebServiceManager.prototype.getFullEndPoint = function (keys, urlBase, endPoint) { + var k; + urlBase = urlBase.replace(/{endPointPath}/, endPoint); + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlBase = urlBase.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + return urlBase; + }; + + WebServiceManager.prototype.setKey = function (name, value) { + if (this.options.keys) + this.options.keys[name] = value; + return this; + }; + + WebServiceManager.prototype.getKey = function (name) { + var resp = false; + if (this.options.keys) + resp = this.options.keys[name]; + return resp; + }; + + WebServiceManager.prototype.deleteKey = function (name, value) { + if (this.options.keys) + delete this.options.keys[name]; + return this; + }; + + WebServiceManager.prototype.getToken = function () { + return this.options.token; + }; + + WebServiceManager.prototype.startCase = function (callback) { + var that = this, + resp, + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.startCase), + method = "POST"; + + $.ajax({ + url: url, + type: method, + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + resp = { + "caseUID": data.caseId, + "caseTitle": data.caseNumber, + "caseNumber": data.caseNumber + }; + callback(null, resp); + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "state": "internetFail" + }; + callback(resp, null); + } + }); + return resp; + }; + + WebServiceManager.prototype.getData = function (callback, options) { + var that = this, + method, url, resp; + if (typeof options === 'object') { + this.setKey('dyn_uid', options['dyn_uid']); + } + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.getData); + method = "GET"; + this.deleteKey('dyn_uid'); + + $.ajax({ + url: url, + type: method, + async: false, + cache: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + callback(null, data); + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "status": "error" + }; + callback(resp, null); + } + }); + return resp; + }; + /** + * This function that execute a endpoint VARIABLES of ProcessMaker + * @param formID + * @param data + * @returns {*} + */ + WebServiceManager.prototype.saveData = function (config, callback) { + var that = this, + url, + method; + this.setKey('formUID', config["formUID"]); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.saveData); + method = "PUT"; + this.deleteKey('formUID'); + + config.data = (config.data && _.isObject(config.data)) ? config.data : {}; + $.ajax({ + url: url, + type: method, + async: false, + data: JSON.stringify(config.data), + contentType: "application/json", + timeout: (1000), + dataType: 'text', + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language !== null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + callback(null, data); + }, + error: function (jqXHR, textStatus, errorThrown) { + console.error("Error! Type: " + textStatus); + callback(textStatus, null); + } + }); + }; + + WebServiceManager.prototype.execAjax = function (ajaxParams) { + var resp; + var that = this; + + function beforeSendCallback(xhr) { + if (ajaxParams.isJSON) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + } + } + + var params = { + url: ajaxParams.url, + type: ajaxParams.method, + async: false, + data: ajaxParams.data || {}, + beforeSend: function (xhr) { + beforeSendCallback(xhr); + }, + success: function (data, textStatus) { + resp = { + "state": "success" + }; + }, + error: function (xhr, textStatus, errorThrown) { + if (xhr.status == 200) { + resp = { + "state": "success" + }; + } else { + resp = { + "state": "internetFail" + }; + } + } + }; + + $.ajax(params); + }; + WebServiceManager.prototype.trigger = function (config, callback) { + var that = this, + method = "POST", + url, + resp = {}; + + this.setKey('stepUID', config["stepUID"]); + this.setKey('triggerOption', config["triggerOption"]); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.trigger); + + this.deleteKey('stepUID'); + this.deleteKey('triggerOption'); + + $.ajax({ + url: url, + type: method, + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + resp = data ? data : true; + callback(null, resp); + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "status": "error" + }; + callback(resp, null); + } + }); + return resp; + }; + /** + * This function executes synchronously the endpoint "execute-query" of ProcessMaker + * @param data + * @param varName + */ + WebServiceManager.prototype.executeSyncQuery = function (data, varName) { + var that = this, + method = "POST", url, resp = []; + this.setKey('var_name', varName); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.query); + this.deleteKey('var_name'); + data = data || {}; + data.app_uid = (this.options && this.options.keys && this.options.keys.caseUID) || null; + data.del_index = (this.options && this.options.keys && this.options.keys.delIndex) || null; + $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + resp = data; + } + }); + return resp; + }; + /** + * This function executes the endpoint "execute-query" of ProcessMaker + * @param data + * @param varName + * @param target + */ + WebServiceManager.prototype.executeQuery = function (data, varName, target) { + var that = this, + method = "POST", url, resp = []; + + this.setKey('var_name', varName); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.query); + + this.deleteKey('var_name'); + + data = data || {}; + data.app_uid = (this.options && this.options.keys && this.options.keys.caseUID) || null; + data.del_index = (this.options && this.options.keys && this.options.keys.delIndex) || null; + + return $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: target.get("form").get("isSync") ? false : true, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + target.afterExecuteQuery(data); + }, + error: function (xhr, textStatus, errorThrown) { + target.afterExecuteQueryFail(textStatus); + } + }); + }; + + WebServiceManager.prototype.conditionalStep = function (config, callback) { + var that = this, + method = "GET", url, resp; + + this.setKey('stepUID', config["stepUID"]); + this.setKey('stepPosition', config["stepPosition"]); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.conditionalSteps); + + this.deleteKey('stepUID'); + this.deleteKey('stepPosition'); + + $.ajax({ + url: url, + type: method, + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function (data, textStatus) { + callback(null, data); + }, + error: function (xhr, textStatus, errorThrown) { + resp = JSON.parse(xhr.responseText); + callback(resp, null); + } + }); + return resp; + }; + + WebServiceManager.prototype.getForm = function (config, callback) { + var that = this, + method, + url, + sendData = [], + resp = {}; + + sendData.push(config["formUID"]); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.form); + + method = "POST"; + $.ajax({ + url: url, + type: method, + async: false, + data: JSON.stringify({ + formId: sendData + }), + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + var respData = null; + if (data.length != 0) { + respData = data[0].formContent; + } + callback(null, respData); + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "state": "internetFail" + }; + callback(resp, null); + } + }); + return resp; + }; + + WebServiceManager.prototype.getFormDefinition = function () { + var that = this, + method, + url, + resp = {}; + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.dynaformDefinition); + method = "GET", + $.ajax({ + url: url, + type: method, + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function (data, textStatus) { + resp = { + "data": data.data.formContent, + "state": "success" + }; + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "state": "internetFail" + }; + } + }); + return resp; + }; + + WebServiceManager.prototype.imageInfo = function (id, width) { + var that = this, + method, + url, + resp = {}; + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.imageInfo); + method = "POST"; + $.ajax({ + url: url, + type: method, + async: false, + data: JSON.stringify([{ + fileId: id, + width: width, + version: 1 + }]), + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language !== null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lan); + } + }, + success: function (data, textStatus) { + resp = { + id: data[0].fileId, + base64: data[0].fileContent + } + }, + error: function (error) { + resp = false; + } + }); + return resp; + }; + + WebServiceManager.prototype.imagesInfo = function (data) { + var that = this, + method, + url, + resp = []; + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.imageInfo); + method = "POST"; + $.ajax({ + url: url, + type: method, + async: false, + data: JSON.stringify(data), + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language !== null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function (data, textStatus) { + resp = data; + } + }); + return resp; + }; + + WebServiceManager.prototype.restClient = function () { + defaults = { + url: "/rest/v10", + method: "GET", + contentType: "application/json", + data: '', + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + keys.access_token); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function () { + }, + error: function () { + } + }; + _.extend(defaults, parems); + + defaults.type = _methodsMap[defaults.method]; + defaults.data = JSON.stringify(defaults.data); + $.ajax(defaults); + }; + + WebServiceManager.prototype.getFullURLStreaming = function (id) { + var k, + keys = this.options.keys, + urlFormat = this.options.urlBaseStreaming; + this.setKey('fileId', id); + urlFormat = urlFormat.replace(/{endPointPath}/, this.options.endPoints.fileStreaming); + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlFormat = urlFormat.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + this.deleteKey("fileId"); + return urlFormat; + }; + /** + * consumes suggest rest service + * @param data + * @param varName + * @returns {Array} + */ + WebServiceManager.prototype.executeQuerySuggest = function (data, varName, target, options) { + var that = this, + method = "POST", url, + appUID = this.options && this.options.keys ? this.getKey("caseUID") : null, + delIndex = this.options && this.options.keys ? this.getKey("delIndex") : null; + + this.setKey('var_name', varName); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.querySuggest); + + this.deleteKey('var_name'); + + data = data ? data : {}; + data.app_uid = appUID; + data.del_index = delIndex; + + return $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: target.get("form").get("isSync") ? false : true, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus, xhr) { + target.afterExecuteQuery(data, xhr, options); + } + }); + }; + /** + * consumes suggest rest service Asynchronously + * @param data + * @param varName + * @returns {Array} + */ + WebServiceManager.prototype.executeSyncQuerySuggest = function (data, varName) { + var that = this, + method = "POST", url, + appUID = this.options && this.options.keys ? this.getKey("caseUID") : null, + delIndex = this.options && this.options.keys ? this.getKey("delIndex") : null, + resp; + + this.setKey('var_name', varName); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.querySuggest); + + this.deleteKey('var_name'); + + data = data ? data : {}; + data.app_uid = appUID; + data.del_index = delIndex; + + $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus, xhr) { + resp = data; + } + }); + return resp; + }; + /** + * Consume and initialize Suggest rest service + * @param data + * @param varName + * @param uidModal + * @param suggest + * @returns {Object} + */ + WebServiceManager.prototype.executeSuggestSelect2 = function (data, varName, uidModal, suggest) { + var that = this, + res, + retObj, + transport, // Use this for the changes in REACT NATIVE with select2 + method = "POST", url, + appUID = this.options && this.options.keys ? this.getKey("caseUID") : null, + delIndex = this.options && this.options.keys ? this.getKey("delIndex") : null; + + this.setKey('var_name', varName); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.querySuggest); + this.deleteKey('var_name'); + data = data ? data : {}; + data.app_uid = appUID; + data.del_index = delIndex; + + retObj = { + ajax: { + url: url, + type: method, + dataType: 'json', + delay: suggest.model.get('delay'), + async: suggest.model.get("form").get("isSync") ? false : true, + contentType: 'application/json', + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + data: function (params) { + var dt = suggest.model.buildDataForQuery(); + dt.filter = params.term || ""; + return JSON.stringify(dt); + }, + processResults: function (data, params) { + var results = $.map(suggest.model.mergeLocalAndRemoteOptions(data, params), function (item) { + return { + id: item.value, + text: item.text || item.label + } + }); + if (!suggest.model.get('forceSelection') && !_.findWhere(results, {text: params.term})) { + results.unshift({ + id: params.term, + text: params.term + }) + } + return { + results: results + }; + }, + transport: function (params, success, failure) { + var res, + request, + cacheKey = params.data; + if (params.dataType === "json") { + //Build your cache key, typically with url and search term and page number + if (suggest.model.get("memoryCache") && that.memoryCache && that.memoryCache[cacheKey]) { + res = that.memoryCache[cacheKey]; + success(res); + return { + abort: function () { + console.log("ajax call aborted"); + } + } + } else { + request = $.ajax(params); + request.then(function (data) { + that.memoryCache[cacheKey] = data; + return data; + }) + .then(success); + request.fail(failure); + return request; + } + } else { + request = $.ajax(params); + request.then(success); + request.fail(failure); + return request; + } + }, + cache: true + }, + width: '100%', + placeholder: suggest.model.get('placeholder') || '', + dir: suggest.model.get('project').isRTL ? 'rtl' : 'ltl', + dropdownParent: uidModal, + tags: !suggest.model.get('forceSelection'), + allowClear: true, + theme: 'bootstrap' + }; + + if (PMDynaform.core.ProjectMobile) { + $.extend(retObj, { + ajax: { + data: function (params) { + var dt = suggest.model.buildDataForQuery(); + dt.filter = params.term || ""; + return dt; + }, + transport: function (params, success, failure) { + var dtQuery = suggest.model.buildDataForQuery(); + dtQuery.filter = params.data && params.data.filter ? params.data.filter : ""; + //If there is not sql in suggest return the local options + if (suggest.model.get("datasource") === "database" && suggest.model.get("sql") === "") { + res = { + results: $.map(suggest.model.mergeLocalAndRemoteOptions([], params), function (item) { + return { + id: item.value, + text: item.text || item.label + } + }) + }; + success(res); + } else { + suggest.model.get("project").requestManager.channelEvents( + { + handler: suggest.model.get("id"), + type: suggest.model.eventsMobile.EXECUTE_QUERY_SUGGEST, + bridge: true, + data: dtQuery, + callback: function (response) { + if (!response.error) { + res = { + results: $.map(suggest.model.mergeLocalAndRemoteOptions(response, params), function (item) { + return { + id: item.value, + text: item.text || item.label + } + }) + }; + success(res); + } else { + failure(response); + } + } + }); + } + } + } + }); + } + return retObj; + }; + WebServiceManager.prototype.nextStep = function (config, callback) { + var that = this, + data, + method = "POST", url, resp = []; + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.nextStep); + + data = { + "pro_uid": this.getKey("processUID"), + "act_uid": this.getKey("taskUID"), + "step_uid": config["stepUID"], + "step_pos": config["stepPosition"], + "app_index": this.getKey("delIndex"), + "dyn_uid": null + }; + + $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: false, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + resp = data; + callback(null, data); + }, + error: function (xhr, textStatus, errorThrown) { + callback(textStatus, null); + } + }); + return resp; + }; + /** + * Returns all the versions of a doc. + * @param {String} appDocUid The doc uid from the versions must be retrieved. + * @param {Function} callback A callback to invoke when the petition completes or fails. + * @returns {WebServiceManager} + */ + WebServiceManager.prototype.getFileVersions = function (appDocUid, callback) { + var url = this.getFullEndPoint({ + caseUID: this.options.keys.caseUID, + docUID: appDocUid, // or use the options one? + server: this.options.keys.server, + workspace: this.options.keys.workspace + }, this.options.urlBase, this.options.endPoints.fileVersionsList), + that = this; + + $.ajax({ + url: url, + type: 'GET', + async: true, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function (data, textStatus) { + resp = { + status: "success", + data: data + }; + callback(null, resp); + }, + error: function (xhr, textStatus, errorThrown) { + resp = { + "status": "error" + }; + callback(resp, null); + } + }); + return this; + }; + + /** + * Upload multipart of a file. + * @param data + * @param callback + * @param callbackupdate + * @return {*} + */ + WebServiceManager.prototype.uploadMultipart = function (data, callback, callbackupdate) { + var that = this, + method = "POST", + url, + index = 0, + formData = data[index].formData, + resp; + this.setKey('var_name', data[index].fieldName); + if (data[index].docUid !== "") { + this.setKey('docUID', data[index].docUid); + if (data[index].appDocUid) { + this.setKey('appDocUid', data[index].appDocUid); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.uploadMultipartVersion); + this.deleteKey('appDocUid'); + } else { + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.uploadMultipartInputDoc); + } + this.deleteKey('docUID'); + } else { + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.uploadMultipart); + } + if (typeof this.options.keys.delIndex !== 'undefined') { + formData.append("delIndex",this.options.keys.delIndex); + } + this.deleteKey('var_name'); + return $.ajax({ + url: url, + type: method, + data: formData, + async: true, + processData: false, + contentType: false, + xhr: function () { + var myXhr = $.ajaxSettings.xhr(); + if (myXhr.upload) { + myXhr.upload.addEventListener('progress', callbackupdate, false); + } + return myXhr; + }, + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.language); + } + }, + success: function (data) { + resp = { + status: "success", + data: data + }; + callback(null, data); + }, + error: function (xhr, textStatus, errorThrown) { + var message; + if (xhr.responseJSON) { + message = xhr.responseJSON.error.message; + callback({ code: xhr.status, message: message }); + } + } + }); + }; + + /** + * Make the URL to download the file + * @param data + * @returns {string} + */ + WebServiceManager.prototype.showDocument = function (data) { + var keys = { + docUID: data.uid || "", + type: data.type || "", + version: data.version || 1 + }; + return this.getDocumentLink(keys); + }; + + WebServiceManager.prototype.getDocumentLink = function (options) { + var k, + keys, + urlbase = this.options.links[options["type"]]; + if (urlbase) { + keys = $.extend(true, this.options.keys, options); + for (k in keys) { + if (keys.hasOwnProperty(k)) { + urlbase = urlbase.replace(new RegExp("{" + k + "}", "g"), keys[k]); + } + } + } + return urlbase; + }; + /** + * Gets file type blob + * @param data {object} + * @param callback + */ + WebServiceManager.prototype.downloadFile = function (data, callback) { + var that = this, + method = "GET", + url; + + this.setKey('docUID', data.docUID); + this.setKey('version', data.version); + url = this.getFullEndPoint(this.options.keys, this.options.urlBase, this.options.endPoints.downloadFile); + this.deleteKey('docUID'); + this.deleteKey('version'); + + $.ajax({ + url: url, + type: method, + headers: { authorization: "Bearer " + that.options.token.accessToken }, + dataType: 'binary', + async: true, + responseType: 'blob', + success: function (data) { + callback(data); + }, + error: function () { + callback(null); + } + }); + }; + + /** + * Gets information of user logged. + */ + WebServiceManager.prototype.getUserInfo = function () { + var that = this, + method = "GET", + url, + response = {}; + url = this.getFullEndPoint(this.options.keys, this.options.urlBase, this.options.endPoints.userInfo); + $.ajax({ + url: url, + type: method, + headers: { authorization: "Bearer " + that.options.token.accessToken }, + async: false, + success: function (data) { + response = { + "uid": data.userId, + "username": data.userName, + "firstName": data.firstName, + "lastName": data.lastName + }; + }, + error: function () { + return "error"; + } + }); + return response; + }; + /** + * New implementation of execute query + * @param {*} data + * @param {*} varName + * @param {*} async + * @param {*} callback + * @returns {*} + */ + WebServiceManager.prototype.execQuery = function (data, varName, async, memoryCache, callback) { + var that = this, + method = "POST", url, resp = [], + cacheKey = JSON.stringify(data); + + this.setKey('var_name', varName); + + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.query); + + this.deleteKey('var_name'); + + data = data || {}; + data.app_uid = (this.options && this.options.keys && this.options.keys.caseUID) || null; + data.del_index = (this.options && this.options.keys && this.options.keys.delIndex) || null; + if (memoryCache && this.memoryCache && this.memoryCache[cacheKey]) { + callback(this.memoryCache[cacheKey], null); + return false; + } + return $.ajax({ + url: url, + type: method, + data: JSON.stringify(data), + async: async, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (data, textStatus) { + that.memoryCache[cacheKey] = data; + callback(data, null); + }, + error: function (xhr, textStatus, errorThrown) { + callback(null, textStatus); + } + }); + }; + /** + * Consumes suggest rest service + * @param data + * @returns {*} + */ + WebServiceManager.prototype.execQuerySuggest = function (data) { + var that = this, + dt, + method = "POST", url, + appUID = this.options && this.options.keys ? this.getKey("caseUID") : null, + delIndex = this.options && this.options.keys ? this.getKey("delIndex") : null, + cacheKey = JSON.stringify(data); + + this.setKey('var_name', data.variable); + url = that.getFullEndPoint(that.options.keys, that.options.urlBase, that.options.endPoints.querySuggest); + this.deleteKey('var_name'); + dt = data.data ? data.data : {}; + dt.app_uid = appUID; + dt.del_index = delIndex; + if (this.memoryCache && this.memoryCache[cacheKey]) { + data.callback(this.memoryCache[cacheKey], null); + return false; + } + return $.ajax({ + url: url, + type: method, + data: JSON.stringify(dt), + async: data.async, + contentType: "application/json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Authorization", "Bearer " + that.options.token.accessToken); + if (that.options.language != null) { + xhr.setRequestHeader("Accept-Language", that.options.keys.lang); + } + }, + success: function (res, textStatus, xhr) { + that.memoryCache[cacheKey] = res; + data.callback(res, null); + } + }); + }; + + xCase.extendNamespace("xCase.service.WebServiceManager", WebServiceManager); +}()); + +(function () { + var Logger = function (option) { + this.template = _.template($("#tpl-messageWarning").html()), + this.messages = { + "formula": "There are references to missing objects in the form. The form configuration is not completed and it is not going to be displayed (rendered). Please contact the administrator.", + "default": "Please contact the administrator." + }, + this.$el; + Logger.prototype.init.call(this, option); + }; + + Logger.prototype.init = function (options) { + + }; + + Logger.prototype.showMessage = function (optionMessage) { + var html, + json = { + message: this.messages[optionMessage] || this.messages["default"] + }; + html = this.template(json); + $(".pmDynaformLoading").css("background", "no-repeat #f9f9f9"); + $(".pmDynaformLoading").append(html); + }; + + PMDynaform.extendNamespace("PMDynaform.implements.Logger", Logger); +}()); +(function () { + var TransformJSON = function (settings) { + this.parentMode = null; + this.field = null; + this.json = null; + this.jsonBuilt = null; + TransformJSON.prototype.init.call(this, settings); + }; + + TransformJSON.prototype.init = function (settings) { + var defaults = { + parentMode: "edit", + field: {}, + json: { + text: TransformJSON.prototype.text, + textarea: TransformJSON.prototype.textArea, + checkgroup: TransformJSON.prototype.checkgroup, + checkbox: TransformJSON.prototype.checkbox, + radio: TransformJSON.prototype.radio, + dropdown: TransformJSON.prototype.dropdown, + button: TransformJSON.prototype.button, + submit: TransformJSON.prototype.submit, + datetime: TransformJSON.prototype.datetime, + suggest: TransformJSON.prototype.suggest, + link: TransformJSON.prototype.link, + file: TransformJSON.prototype.file, + grid: TransformJSON.prototype.grid, + multipleFile: TransformJSON.prototype.file + } + }; + + jQuery.extend(true, defaults, settings); + + this.jsonBuilt = defaults.field; + this.setParentMode(defaults.parentMode) + .setField(defaults.field) + .setJSONFactory(defaults.json) + .buildJSON(); + + return this; + }; + TransformJSON.prototype.setParentMode = function (mode) { + this.parentMode = mode; + + return this; + }; + TransformJSON.prototype.text = function (field) { + return { + type: "label", + colSpanControl: field.colSpanControl, + colSpanLabel: field.colSpanLabel, + colSpan: field.colSpan, + label: field.label, + fullOptions: [ + field.defaultValue || field.value + ], + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.textArea = function (field) { + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + fullOptions: [ + field.defaultValue || field.value + ], + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.checkgroup = function (field) { + var validOpt = [], + i; + + for (i = 0; i < field.options.length; i += 1) { + if (field.options[i].selected) { + if (field.options[i].selected === true) { + validOpt.push(field.options[i].label); + } + } + + } + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + fullOptions: validOpt, + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.checkbox = function (field) { + var validOpt = [], + i; + for (i = 0; i < field.options.length; i += 1) { + if (field.options[i].selected) { + if (field.options[i].selected === true) { + validOpt.push(field.options[i].label); + } + } + } + return { + type: "checkbox", + colSpan: field.colSpan, + label: field.label, + fullOptions: validOpt, + id: field.id, + data: field.data, + mode: field.mode + }; + }; + TransformJSON.prototype.radio = function (field) { + var validOpt = [], + i; + for (i = 0; i < field.options.length; i += 1) { + if (field.defaultValue) { + if (field.options[i].value.toString() === field.defaultValue.toString()) { + validOpt.push(field.options[i].label); + } + } + } + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + fullOptions: validOpt, + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.dropdown = function (field) { + var validOpt = [], + i; + + for (i = 0; i < field.options.length; i += 1) { + if (field.defaultValue) { + if (field.options[i].value.toString() === field.defaultValue.toString()) { + validOpt.push(field.options[i].label); + } + } + } + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + fullOptions: validOpt, + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.button = function (field) { + return field; + }; + TransformJSON.prototype.submit = function (field) { + return field; + }; + TransformJSON.prototype.datetime = function (field) { + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + fullOptions: [ + field.defaultValue || field.value + ], + id: field.id, + data: field.data + }; + }; + TransformJSON.prototype.suggest = function (field) { + return field; + }; + TransformJSON.prototype.link = function (field) { + return { + type: "label", + colSpan: field.colSpan, + label: field.label, + id: field.id, + options: [ + field.value + ] + }; + }; + TransformJSON.prototype.file = function (field) { + return field; + }; + TransformJSON.prototype.grid = function (field) { + return field; + }; + TransformJSON.prototype.setField = function (field) { + this.field = field; + + return this; + }; + TransformJSON.prototype.setJSONFactory = function (factory) { + this.json = factory; + return this; + }; + TransformJSON.prototype.discardViewField = function (type) { + var disabled = [ + "button", + "submit", + "image", + "label", + "title", + "subtitle" + ]; + return ($.inArray(type, disabled) < 0) ? true : false; + }; + TransformJSON.prototype.reviewField = function (field) { + var jsonBuilt = field, + total, + sigleControl = ["text", "suggest", "textarea", "datetime"], + data, + i; + + if (this.json[field.type] && this.discardViewField(field.type)) { + switch (field.mode) { + case "disabled": + jsonBuilt = field; + jsonBuilt.disabled = true; + break; + case "parent": + field.mode = this.parentMode; + jsonBuilt = this.reviewField(field); + break; + case "view": + jsonBuilt = this.json[field.type](field); + break; + default: + jsonBuilt = field; + } + } + jsonBuilt.dataType = field.dataType || ""; + jsonBuilt.originalType = field.originalType || field.type; + jsonBuilt.var_name = field.var_name || ""; + jsonBuilt.var_uid = field.var_uid || ""; + jsonBuilt.options || field.var_accepted_values; + if (field.data) { + jsonBuilt.fullOptions = []; + if (sigleControl.indexOf(jsonBuilt.originalType) !== -1) { + if (jsonBuilt.originalType === "suggest") { + jsonBuilt.fullOptions = [field.data["label"] || field.defaultValue]; + } else { + jsonBuilt.fullOptions = [field.data["value"] || field.defaultValue]; + } + } else { + if (jsonBuilt.originalType === "checkgroup") { + data = []; + if ($.isArray(field["optionsSql"])) { + total = field["options"].concat(field["optionsSql"]); + } else { + total = field["options"]; + } + for (i = 0; i < total.length; i += 1) { + if (field.data["value"].indexOf(total[i]["value"]) !== -1) { + data.push(total[i]["label"]); + } + } + jsonBuilt.fullOptions = data || [field.defaultValue]; + } else { + jsonBuilt.fullOptions = [field.data["label"] || field.defaultValue]; + } + } + } + return jsonBuilt; + }; + TransformJSON.prototype.buildJSON = function () { + this.jsonBuilt = this.reviewField(this.field); + return this; + }; + + TransformJSON.prototype.getJSON = function () { + return this.jsonBuilt; + }; + PMDynaform.extendNamespace("PMDynaform.core.TransformJSON", TransformJSON); + +}()); +(function () { + var FileReader = window.FileReader, + FileReaderSyncSupport = false, + workerScript = "self.addEventListener('message', function(e) { var data=e.data; try { var reader = new FileReaderSync; postMessage({ result: reader[data.readAs](data.file), extra: data.extra, file: data.file})} catch(e){ postMessage({ result:'error', extra:data.extra, file:data.file}); } }, false);", + syncDetectionScript = "self.addEventListener('message', function(e) { postMessage(!!FileReaderSync); }, false);", + fileReaderEvents = ['loadstart', + 'progress', + 'load', + 'abort', + 'error', + 'loadend'], + FileStream = { + enabled: false, + setupInput: setupInput, + setupDrop: setupDrop, + setupClipboard: setupClipboard, + sync: false, + output: [], + opts: { + dragClass: "drag", + accept: false, + readAsDefault: 'BinaryString', + readAsMap: { + 'image/*': 'DataURL', + 'text/*': 'Text' + }, + on: { + loadstart: function () { + }, + progress: function () { + }, + load: function () { + }, + abort: function () { + }, + error: function () { + }, + loadend: function () { + }, + skip: function () { + }, + groupstart: function () { + }, + groupend: function () { + }, + beforestart: function () { + } + } + } + }; + + // Not all browsers support the FileReader interface. Return with the enabled bit = false. + if (!FileReader) { + return; + } + + // WorkerHelper is a little wrapper for generating web workers from strings + var WorkerHelper = (function () { + + var URL = window.URL || window.webkitURL; + var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; + + // May need to get just the URL in case it is needed for things beyond just creating a worker. + function getURL(script) { + if (window.Worker && BlobBuilder && URL) { + var bb = new BlobBuilder(); + bb.append(script); + return URL.createObjectURL(bb.getBlob()); + } + + return null; + } + + // If there is no need to revoke a URL later, or do anything fancy then just return the worker. + function getWorker(script, onmessage) { + var worker, + url = getURL(script); + + if (url) { + worker = new Worker(url); + worker.onmessage = onmessage; + return worker; + } + + return null; + } + + return { + getURL: getURL, + getWorker: getWorker + }; + + })(); + + // setupClipboard: bind to clipboard events (intended for document.body) + function setupClipboard(element, opts) { + var instanceOptions = {}; + if (!FileStream.enabled) { + return; + } + + $.extend(true, instanceOptions, FileStream.opts); + $.extend(true, instanceOptions, opts); + //instanceOptions = extend(extend({}, FileStream.opts), opts); + + element.addEventListener("paste", onpaste, false); + + function onpaste(e) { + var files = []; + var clipboardData = e.clipboardData || {}; + var items = clipboardData.items || []; + + for (var i = 0; i < items.length; i++) { + var file = items[i].getAsFile(); + + if (file) { + + // Create a fake file name for images from clipboard, since this data doesn't get sent + var matches = new RegExp("/\(.*\)").exec(file.type); + if (!file.name && matches) { + var extension = matches[1]; + file.name = "clipboard" + i + "." + extension; + } + + files.push(file); + } + } + + if (files.length) { + processFileList(e, files, instanceOptions); + e.preventDefault(); + e.stopPropagation(); + } + } + } + + // setupInput: bind the 'change' event to an input[type=file] + function setupInput(input, opts) { + var instanceOptions = {}; + + if (!FileStream.enabled) { + return; + } + //var instanceOptions = extend(extend({}, FileStream.opts), opts); + $.extend(true, instanceOptions, FileStream.opts); + $.extend(true, instanceOptions, opts); + + input.addEventListener("change", inputChange, false); + input.addEventListener("drop", inputDrop, false); + + function inputChange(e) { + processFileList(e, input.files, instanceOptions); + } + + function inputDrop(e) { + e.stopPropagation(); + e.preventDefault(); + processFileList(e, e.dataTransfer.files, instanceOptions); + } + } + + // setupDrop: bind the 'drop' event for a DOM element + function setupDrop(dropbox, opts) { + var dragClass, + initializedOnBody, + instanceOptions = {}; + + if (!FileStream.enabled) { + return; + } + //var instanceOptions = extend(extend({}, FileStream.opts), opts); + $.extend(true, instanceOptions, FileStream.opts); + $.extend(true, instanceOptions, opts); + + if (!instanceOptions.dnd) { + return; + } + dragClass = instanceOptions.dragClass; + initializedOnBody = false; + + // Bind drag events to the dropbox to add the class while dragging, and accept the drop data transfer. + dropbox.addEventListener("dragenter", onlyWithFiles(dragenter), false); + dropbox.addEventListener("dragleave", onlyWithFiles(dragleave), false); + dropbox.addEventListener("dragover", onlyWithFiles(dragover), false); + dropbox.addEventListener("drop", onlyWithFiles(drop), false); + + // Bind to body to prevent the dropbox events from firing when it was initialized on the page. + document.body.addEventListener("dragstart", bodydragstart, true); + document.body.addEventListener("dragend", bodydragend, true); + document.body.addEventListener("drop", bodydrop, false); + + function bodydragend(e) { + initializedOnBody = false; + } + + function bodydragstart(e) { + initializedOnBody = true; + } + + function bodydrop(e) { + if (e.dataTransfer.files && e.dataTransfer.files.length) { + e.stopPropagation(); + e.preventDefault(); + } + } + + function onlyWithFiles(fn) { + return function () { + if (!initializedOnBody) { + fn.apply(this, arguments); + } + }; + } + + function drop(e) { + e.stopPropagation(); + e.preventDefault(); + if (dragClass) { + removeClass(dropbox, dragClass); + } + processFileList(e, e.dataTransfer.files, instanceOptions); + } + + function dragenter(e) { + e.stopPropagation(); + e.preventDefault(); + if (dragClass) { + addClass(dropbox, dragClass); + } + } + + function dragleave(e) { + if (dragClass) { + removeClass(dropbox, dragClass); + } + } + + function dragover(e) { + e.stopPropagation(); + e.preventDefault(); + if (dragClass) { + addClass(dropbox, dragClass); + } + } + } + + // setupCustomFileProperties: modify the file object with extra properties + function setupCustomFileProperties(files, groupID) { + for (var i = 0; i < files.length; i++) { + var file = files[i]; + file.extra = { + nameNoExtension: file.name.substring(0, file.name.lastIndexOf('.')), + extension: file.name.substring(file.name.lastIndexOf('.') + 1), + fileID: i, + uniqueID: getUniqueID(), + groupID: groupID, + prettySize: prettySize(file.size) + }; + } + } + + // getReadAsMethod: return method name for 'readAs*' - http://www.w3.org/TR/FileAPI/#reading-a-file + function getReadAsMethod(type, readAsMap, readAsDefault) { + for (var r in readAsMap) { + if (type.match(new RegExp(r))) { + return 'readAs' + readAsMap[r]; + } + } + return 'readAs' + readAsDefault; + } + + // processFileList: read the files with FileReader, send off custom events. + function processFileList(e, files, opts) { + + var filesLeft = files.length, + group = { + groupID: getGroupID(), + files: files, + started: new Date() + }, + sync, + syncWorker; + + function groupEnd() { + group.ended = new Date(); + opts.on.groupend(group); + } + + function groupFileDone() { + if (--filesLeft === 0) { + groupEnd(); + } + } + + FileStream.output.push(group); + setupCustomFileProperties(files, group.groupID); + + opts.on.groupstart(group); + + // No files in group - end immediately + if (!files.length) { + groupEnd(); + return; + } + + sync = FileStream.sync && FileReaderSyncSupport; + syncWorker; + + // Only initialize the synchronous worker if the option is enabled - to prevent the overhead + if (sync) { + syncWorker = WorkerHelper.getWorker(workerScript, function (e) { + var file = e.data.file; + var result = e.data.result; + + // Workers seem to lose the custom property on the file object. + if (!file.extra) { + file.extra = e.data.extra; + } + + file.extra.ended = new Date(); + + // Call error or load event depending on success of the read from the worker. + opts.on[result === "error" ? "error" : "load"]({target: {result: result}}, file); + groupFileDone(); + + }); + } + + Array.prototype.forEach.call(files, function (file) { + + file.extra.started = new Date(); + + if (opts.accept && !file.type.match(new RegExp(opts.accept))) { + opts.on.skip(file); + groupFileDone(); + return; + } + + if (opts.on.beforestart(file) === false) { + opts.on.skip(file); + groupFileDone(); + return; + } + + var readAs = getReadAsMethod(file.type, opts.readAsMap, opts.readAsDefault); + + if (sync && syncWorker) { + syncWorker.postMessage({ + file: file, + extra: file.extra, + readAs: readAs + }); + } + else { + + var reader = new FileReader(); + reader.originalEvent = e; + + fileReaderEvents.forEach(function (eventName) { + reader['on' + eventName] = function (e) { + if (eventName == 'load' || eventName == 'error') { + file.extra.ended = new Date(); + } + opts.on[eventName](e, file); + if (eventName == 'loadend') { + groupFileDone(); + } + }; + }); + + reader[readAs](file); + } + }); + } + + // checkFileReaderSyncSupport: Create a temporary worker and see if FileReaderSync exists + function checkFileReaderSyncSupport() { + var worker = WorkerHelper.getWorker(syncDetectionScript, function (e) { + FileReaderSyncSupport = e.data; + }); + + if (worker) { + worker.postMessage({}); + } + } + + + // hasClass: does an element have the css class? + function hasClass(el, name) { + return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(el.className); + } + + // addClass: add the css class for the element. + function addClass(el, name) { + if (!hasClass(el, name)) { + el.className = el.className ? [el.className, name].join(' ') : name; + } + } + + // removeClass: remove the css class from the element. + function removeClass(el, name) { + if (hasClass(el, name)) { + var c = el.className; + el.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, ''); + } + } + + // prettySize: convert bytes to a more readable string. + function prettySize(bytes) { + var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'], + e = Math.floor(Math.log(bytes) / Math.log(1024)); + return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e]; + } + + // getGroupID: generate a unique int ID for groups. + var getGroupID = (function (id) { + return function () { + return id++; + }; + })(0); + + // getUniqueID: generate a unique int ID for files + var getUniqueID = (function (id) { + return function () { + return id++; + }; + })(0); + + // The interface is supported, bind the FileStream callbacks + FileStream.enabled = true; + + + PMDynaform.extendNamespace("PMDynaform.core.FileStream", FileStream); + +}()); +(function () { + /** + * FullScreen class + */ + var FullScreen = function (options) { + this.element = null; + this.onReadyScreen = null; + this.onCancelScreen = null; + this.isInFullScreen = null; + this.supported = null; + FullScreen.prototype.init.call(this, options); + }; + /** + * [init description] + * @param {Object} options Config options + */ + FullScreen.prototype.init = function (options) { + var defaults = { + element: document.documentElement, + onReadyScreen: function () { + }, + onCancelScreen: function () { + } + }; + jQuery.extend(true, defaults, options); + this.element = defaults.element; + this.onReadyScreen = defaults.onReadyScreen; + this.onCancelScreen = defaults.onCancelScreen; + this.checkFullScreen(); + }; + FullScreen.prototype.checkFullScreen = function () { + var el = this.element, + request = el.requestFullScreen || + el.webkitRequestFullScreen || + el.mozRequestFullScreen || + el.msRequestFullScreen; + + this.supported = request ? true : null; + + return this; + }; + FullScreen.prototype.cancel = function () { + var requestMethod, fnCancelScreen, wscript, el; + if (parent.document.documentElement === document.documentElement) { + el = document; + } else { + el = parent.document; + } + requestMethod = el.cancelFullScreen || + el.webkitCancelFullScreen || + el.mozCancelFullScreen || + el.exitFullscreen; + if (requestMethod) { + requestMethod.call(el); + try { + fnCancelScreen = this.onCancelScreen; + fnCancelScreen(el); + } catch (e) { + throw new Error(e); + } + } else if (typeof window.ActiveXObject !== "undefined") { // Older IE. + wscript = new ActiveXObject("WScript.Shell"); + if (wscript !== null) { + wscript.SendKeys("{F11}"); + } + } + }; + + FullScreen.prototype.applyZoom = function () { + var requestMethod, wscript, fnReadyScreen, el = this.element; + requestMethod = el.requestFullScreen || + el.webkitRequestFullScreen || + el.mozRequestFullScreen || + el.msRequestFullScreen; + + if (requestMethod) { + requestMethod.call(el); + try { + fnReadyScreen = this.onReadyScreen; + fnReadyScreen(el); + } catch (e) { + throw new Error(e); + } + } else if (typeof window.ActiveXObject !== "undefined") { + wscript = new ActiveXObject("WScript.Shell"); + if (wscript !== null) { + wscript.SendKeys("{F11}"); + } + } + return false + }; + FullScreen.prototype.toggle = function () { + var el; + if (parent.document.documentElement === document.documentElement) { + el = document; + } else { + el = parent.document; + } + this.isInFullScreen = (el.fullScreenElement && el.fullScreenElement !== null) || (el.mozFullScreen || el.webkitIsFullScreen); + if (this.isInFullScreen) { + this.cancel(); + } else { + this.applyZoom(); + } + return false; + }; + + PMDynaform.extendNamespace("PMDynaform.core.FullScreen", FullScreen); +}()); +(function () { + var Script = function (options) { + this.name = null; + this.type = null; + this.html = null; + this.script = ""; + this.renderTo = document.body; + + Script.prototype.init.call(this, options); + }; + Script.prototype.init = function (options) { + var defaults = { + type: "text/javascript", + script: "" + }; + + $.extend(true, defaults, options); + this.setType(defaults.type) + .setScript(defaults.script); + }; + Script.prototype.setType = function (type) { + this.type = type; + return this; + }; + Script.prototype.setScript = function (script) { + this.script = script; + return this; + }; + Script.prototype.createHTML = function () { + var html = document.createElement("script"); + + html.type = this.type; + html.text = this.script; + this.html = html; + + return html; + }; + Script.prototype.getHTML = function () { + if (!this.html) { + this.createHTML(); + } + + return this.html; + }; + Script.prototype.render = function () { + var html = this.getHTML(); + $(this.renderTo).append(html); + + return this; + }; + PMDynaform.extendNamespace("PMDynaform.core.Script", Script); +}()); + +(function () { + /** + * @class PMUI.util.ArrayList + * Construct a List similar to Java's ArrayList that encapsulates methods for + * making a list that supports operations like get, insert and others. + * + * some examples: + * var item, + * arrayList = new ArrayList(); + * arrayList.getSize() // 0 + * arrayList.insert({ // insert an object + * id: 100, + * width: 100, + * height: 100 + * }); + * arrayList.getSize(); // 1 + * arrayList.asArray(); // [{id : 100, ...}] + * item = arrayList.find('id', 100); // finds the first element with an id that equals 100 + * arrayList.remove(item); // remove item from the arrayList + * arrayList.getSize(); // 0 + * arrayList.isEmpty(); // true because the arrayList has no elements + * + * @constructor Returns an instance of the class ArrayList + */ + var ArrayList = function () { + /** + * The elements of the arrayList + * @property {Array} + * @private + */ + var elements = [], + /** + * The size of the array + * @property {number} [size=0] + * @private + */ + size = 0, + index, + i; + return { + + /** + * The ID of this ArrayList is generated using the function Math.random + * @property {number} id + */ + id: Math.random(), + /** + * Gets an element in the specified index or undefined if the index + * is not present in the array + * @param {number} index + * @returns {Object / undefined} + */ + get: function (index) { + return elements[index]; + }, + /** + * Inserts an element at the end of the list + * @param {Object} item + * @chainable + */ + insert: function (item) { + elements[size] = item; + size += 1; + return this; + }, + /** + * Inserts an element in a specific position + * @param {Object} item + * @chainable + */ + insertAt: function (item, index) { + elements.splice(index, 0, item); + size = elements.length; + return this; + }, + /** + * Removes an item from the list + * @param {Object} item + * @return {boolean} + */ + remove: function (item) { + index = this.indexOf(item); + if (index === -1) { + return false; + } + //swap(elements[index], elements[size-1]); + size -= 1; + elements.splice(index, 1); + return true; + }, + /** + * Gets the length of the list + * @return {number} + */ + getSize: function () { + return size; + }, + /** + * Returns true if the list is empty + * @returns {boolean} + */ + isEmpty: function () { + return size === 0; + }, + /** + * Returns the first occurrence of an element, if the element is not + * contained in the list then returns -1 + * @param {Object} item + * @return {number} + */ + indexOf: function (item) { + for (i = 0; i < size; i += 1) { + if (item === elements[i]) { + return i; + } + } + return -1; + }, + /** + * Returns the the first object of the list that has the + * specified attribute with the specified value + * if the object is not found it returns undefined + * @param {string} attribute + * @param {string} value + * @return {Object / undefined} + */ + find: function (target) { + var sortedValues = elements.sort(); + // summary: + // Performs a binary search on an array of sorted + // values for a specified target. + // sortedValues: Array + // Array of values to search within. + // target: String|Number + // Item to search for, within the sortedValues array. + // returns: + // Number or null. The location of the target within + // the sortedValues array, if found. Otherwise returns + // null. + + // define the recursive function. + function search(low, high) { + // If the low index is greater than the high index, + // return null for not-found. + if (low > high) { + return undefined; + } + + // If the value at the low index is our target, return + // the low index. + if (sortedValues[low] === target) { + return low; + } + + // If the value at the high index is our target, return + // the high index. + if (sortedValues[high] === target) { + return high; + } + + // Find the middle index and median element. + var middle = Math.floor(( low + high ) / 2); + var middleElement = sortedValues[middle]; + + // Recursive calls, depending on whether or not the + // middleElement is less-than or greater-than the + // target. + // Note: We can use high-1 and low+1 because we've + // already checked for equality at the high and low + // indexes above. + if (middleElement < target) { + return search(middle, high - 1); + } else if (middleElement > target) { + return search(low + 1, middle); + } + + // If middleElement === target, we can return that value. + return middle; + } + + // Start our search between the first and last elements of + // the array. + return search(0, sortedValues.length - 1); + }, + /** + * Returns true if the list contains the item and false otherwise + * @param {Object} item + * @return {boolean} + */ + contains: function (item) { + if (this.indexOf(item) !== -1) { + return true; + } + return false; + }, + /** + * Sorts the list using compFunction if possible, if no compFunction + * is passed as an parameter then a default sorting method will be used. This default method will sort in + * ascending order. + * @param {Function} [compFunction] The criteria function used to find out the position for the elements in + * the array list. This function will receive two parameters, each one will be an element from the array + * list, the function will compare those elements and it must return: + * + * - 1, if the first element must be before the second element. + * - -1, if the second element must be before the first element. + * - 0, if the current situation doesn't met any of the two situations above. In this case both elements + * can be evaluated as they had the same value. For example, in an array list of numbers, when you are + * trying to apply a lineal sorting (ascending/descending) in a array list of numbers, if the array sorting + * function finds two elements with the value 3 they should be evaluated returning 0, since both values are + * the same. + * + * IMPORTANT NOTE: for a correct performance the sent parameter must return at least two of the values + * listed above, if it doesn't the function can produce an infinite loop and thus an error. + * @return {boolean} + */ + sort: function (compFunction) { + var compFunction = compFunction || function (a, b) { + if (a < b) { + return 1; + } else if (a > b) { + return -1; + } else { + return 0; + } + }, swap = function (items, firstIndex, secondIndex) { + var temp = items[firstIndex]; + items[firstIndex] = items[secondIndex]; + items[secondIndex] = temp; + }, partition = function (items, left, right) { + var pivot = items[Math.floor((right + left) / 2)], + i = left, + j = right; + while (i <= j) { + while (compFunction(items[i], pivot) > 0) { + i++; + } + while (compFunction(items[j], pivot) < 0) { + j--; + } + if (i <= j) { + swap(items, i, j); + i++; + j--; + } + } + return i; + }, quickSort = function (items, left, right) { + var index; + if (items.length > 1) { + index = partition(items, left, right); + if (left < index - 1) { + quickSort(items, left, index - 1); + } + if (index < right) { + quickSort(items, index, right); + } + } + return items; + }; + + return quickSort(elements, 0, size - 1); + }, + /** + * Returns the list as an array + * @return {Array} + */ + asArray: function () { + return elements.slice(0); + }, + /** + * Swaps the position of two elements + * @chainable + */ + swap: function (index1, index2) { + var aux; + if (index1 < size && index1 >= 0 && index2 < size && index2 >= 0) { + aux = elements[index1]; + elements[index1] = elements[index2]; + elements[index2] = aux; + } + return this; + }, + /** + * Returns the first element of the list + * @return {Object} + */ + getFirst: function () { + return elements[0]; + }, + /** + * Returns the last element of the list + * @return {Object} + */ + getLast: function () { + return elements[size - 1]; + }, + + /** + * Returns the last element of the list and deletes it from the list + * @return {Object} + */ + popLast: function () { + var lastElement; + size -= 1; + lastElement = elements[size]; + elements.splice(size, 1); + return lastElement; + }, + /** + * Returns an array with the objects that determine the minimum size + * the container should have + * The array values are in this order TOP, RIGHT, BOTTOM AND LEFT + * @return {Array} + */ + getDimensionLimit: function () { + var result = [100000, -1, -1, 100000], + objects = [undefined, undefined, undefined, undefined]; + //number of pixels we want the inner shapes to be + //apart from the border + + for (i = 0; i < size; i += 1) { + if (result[0] > elements[i].y) { + result[0] = elements[i].y; + objects[0] = elements[i]; + + } + if (result[1] < elements[i].x + elements[i].width) { + result[1] = elements[i].x + elements[i].width; + objects[1] = elements[i]; + } + if (result[2] < elements[i].y + elements[i].height) { + result[2] = elements[i].y + elements[i].height; + objects[2] = elements[i]; + } + if (result[3] > elements[i].x) { + result[3] = elements[i].x; + objects[3] = elements[i]; + } + } + return result; + }, + /** + * Clears the content of the arrayList + * @chainable + */ + clear: function () { + if (size !== 0) { + elements = []; + size = 0; + } + return this; + }, + /** + * Sets the elements for the object. + * @param {Array|null} items Array with the items to set. + * @chainable + */ + set: function (items) { + if (!(items === null || jQuery.isArray(items))) { + throw new Error("set(): The parameter must be an array or null."); + } + elements = (items && items.slice(0)) || []; + size = elements.length; + return this; + } + }; + }; + + PMDynaform.extendNamespace("PMDynaform.util.ArrayList", ArrayList); + +}()); + +(function () { + /** + * @class PMDynaform.util.DependentsFieldManager + * Class that handles dependent field events + * @param options {Object} Instance configuration + */ + var DependentsFieldManager = function (options) { + /** + * @param {object}: eventsManager, Dependent field event manager + * extends Backbone.Events + */ + this.eventsManager = {}; + this.matrix = {}; + this.dependencies = {}; + this.fields; + + /** + * @param {object}: form, Related form + */ + this.form = null; + DependentsFieldManager.prototype.init.call(this, options); + }; + /** + * initialize the DependentsFieldManager + * @chainable + */ + DependentsFieldManager.prototype.init = function (options) { + var defaults = { + form: null + }; + _.extend(defaults, options); + this.setForm(defaults.form); + _.extend(this.eventsManager, Backbone.Events); + return this; + }; + /** + * setForm: Sets the corresponding Related form + * @param form {object} instace PMDynaform.model.FormPanel + * @chainable + */ + DependentsFieldManager.prototype.setForm = function (form) { + this.form = form; + return this; + }; + /** + * addEvent, Records a new dependent field event + * @param key {string} Is the identifier that is registered in the event manager + * @param callback {function} Is the function that will be called after executing the event + * @param target {object} Is the origin of the method call + * @chainable + */ + DependentsFieldManager.prototype.addEvent = function (key, callback, target) { + this.eventsManager.on(key, callback, target); + return this; + }; + /** + * removeEvent, Disable Events Logged on the Dependent Field Handler + * @chainable + */ + DependentsFieldManager.prototype.removeEvent = function (observer) { + this.eventsManager.off(observer); + return this; + }; + /** + * notify, executes the notification corresponding to the registered event + * @param info {object} Information of the item that ejects the event + * @chainable + */ + DependentsFieldManager.prototype.notify = function (info) { + this.eventsManager.trigger(info.registrationName, info); + return this; + }; + /** + * getForm, obtain the related form + * @returns {PMDynaform.model.FormPanel} + */ + DependentsFieldManager.prototype.getForm = function () { + return this.form; + }; + /** + * getProject, obtain the project related + * @returns {PMDynaform.core.Project} + */ + DependentsFieldManager.prototype.getProject = function () { + var form = this.getForm(); + if (form && form.get("project")) { + return form.get("project"); + } + return null; + }; + /** + * registerNewDependencyRelation, Prepares to Record Dependent Field for a Field That Has Dependents + * @param name + * @chainable + */ + DependentsFieldManager.prototype.registerNewDependencyRelation = function (name) { + var relations; + relations = this.matrix; + if (!relations.hasOwnProperty(name)) { + relations[name] = []; + } + return this; + }; + /** + * registerNewDependent,Registers a new dependent field + * @param dependency + * @param dependent + * @chainable + */ + DependentsFieldManager.prototype.registerNewDependent = function (dependency, dependent) { + var relations; + relations = this.matrix; + if (relations.hasOwnProperty(dependency)) { + relations[dependency].push(dependent); + } + return this; + }; + /** + * Register a new dependency for field model + * @param target + * @param dependency + * @chainable + */ + DependentsFieldManager.prototype.registerDependency = function (target, dependency) { + if (!this.dependencies[target]) { + this.dependencies[target] = []; + } + this.dependencies[target].push(dependency); + return this; + }; + /** + * Assign the fields to this class + * @param fields + * @chainable + */ + DependentsFieldManager.prototype.setupFields = function (fields) { + this.fields = fields; + return this; + }; + /** + * Return a field from array fields by ID + * @param id + * @returns {FieldModel} + */ + DependentsFieldManager.prototype.getFieldById = function (id) { + var result; + if (id && id !== undefined) { + result = _.find(this.fields, function (item) { + return item.model.get("id") == id; + }); + } + return result; + }; + /** + * Dispatch a event + * @param {*} payload + */ + DependentsFieldManager.prototype.emit = function (payload) { + PMDynaform.EventBus.emit(payload); + }; + /** + * Create dependencies callbacks for field model in desc tree of dependencies + * @param {FieldModel} modelField + */ + DependentsFieldManager.prototype.createOneDirectional = function (modelField) { + this.oneDirectional(modelField, "dependencies", ""); + if (this.matrix[this.getFieldId(modelField)]) { + PMDynaform.EventBus.emit({ + channel: "dependencies", + event: this.getFieldId(modelField), + payload: "" + }); + } + }; + /** + * Return the id from field model for dependencies + * @param {*} model + * @returns {String} + */ + DependentsFieldManager.prototype.getFieldId = function (model) { + var id, + parent = model.get("parent"); + id = parent.get("type") === "grid" ? (model.get("columnId") || model.get("id")) + "-" + model.get("keyEvent") : model.get("id"); + return id; + }; + /** + * Handle the dependencies when the independent field has default value + * Model Field dependent field + * @param {FieldModel} modelField + */ + DependentsFieldManager.prototype.defaultValuesDependency = function (modelField) { + var that = this, + serial = Date.now().toString(), + dt = {}; + _.forEach(this.dependencies[this.getFieldId(modelField)], function (el) { + _.extend(dt, that.getDependenciesData(that.matrix[el][0])); + }); + modelField.executeDependency(dt, serial); + }; + /** + * Create dependencies callback in asc and desc order + * Model Field has dependencies + * fn is a function to call when finish all + * @param {FieldModel} modelField + * @param {function} fn + */ + DependentsFieldManager.prototype.createBidirectional = function (modelField, fn) { + var that = this, + serial = Date.now().toString(), + channel = "dependencies", + that = this, evs = []; + if (this.matrix[this.getFieldId(modelField)]) { + _.forEach(this.matrix[this.getFieldId(modelField)], function (el) { + evs.push({ + event: that.getFieldId(el) + serial + }); + }); + + PMDynaform.EventBus.subscribe({ + channel: channel, + type: "joinFork", + id: this.getFieldId(modelField) + serial, + deleteOnCompletion: true, + callback: fn, + events: evs + }); + this.oneDirectional(modelField, channel, serial); + PMDynaform.EventBus.emit({ + channel: "dependencies", + event: this.getFieldId(modelField) + serial, + payload: "" + }); + } else if (_.isFunction(fn)) { + fn(); + } + }; + /** + * Create a dependencies callback in asc order + * ModelField has dependencies + * channel is a string for subsrcibe in event bus + * serial is a unique string for identify the calls + * @param {FieldModel} modelField + * @param {String} channel + * @param {String} serial + */ + DependentsFieldManager.prototype.oneDirectional = function (modelField, channel, serial) { + var that = this; + if (this.matrix[this.getFieldId(modelField)]) { + _.forEach(this.matrix[this.getFieldId(modelField)], function (el) { + if (PMDynaform.EventBus.verifyObservableChannel(channel, that.getFieldId(el) + serial)) { + PMDynaform.EventBus.subscribeEventToJoinFork({ + channel: channel, + id: that.getFieldId(el) + serial, + events: [{ event: that.getFieldId(modelField) + serial }] + }); + } else { + PMDynaform.EventBus.subscribe({ + channel: channel, + type: "joinFork", + id: that.getFieldId(el) + serial, + deleteOnCompletion: true, + callback: function () { + var dt = that.getDependenciesData(el); + el.executeDependency(dt, serial); + }, + events: [{ event: that.getFieldId(modelField) + serial }] + }); + } + if (that.matrix[that.getFieldId(el)]) { + that.oneDirectional(el, "dependencies", serial); + } + }); + } + }; + /** + * Return data for dependents fields from a field model + * @param {FieldModel} model + * @returns {*} + */ + DependentsFieldManager.prototype.getDependenciesData = function (model) { + var that = this, + deep, + grid, row, isColumn = false, + res = {}, id = model.get("id"); + // Get data from row in grid web is not working in mobile + if (model.get("parent") && model.get("parent").get("type") === "grid") { + if (this.dependencies[this.getFieldId(model)]) { + isColumn = true; + //For grids in Mobile + if (PMDynaform.core.ProjectMobile) { + row = _.find(model.get("parent").get("rowCollection").models, function (row) { + return (row.getCells()[0].get("keyEvent") === model.get("keyEvent")); + }); + _.forEach(row.getCells(), function (el) { + res[el.get("id")] = el.get("data")["value"]; + }); + } else { //For grid in Web Application + grid = model.get("parent").get("view"); + row = _.find(grid.gridtable, function (row) { + return (row[0].model.get("keyEvent") === model.get("keyEvent")); + }); + _.forEach(row, function (el) { + deep = _.find(that.dependencies[that.getFieldId(model)], function (o) { return o === that.getFieldId(el.model); }); + if (deep) { + res[el.model.get("columnId")] = el.model.get("data")["value"]; + } + }); + } + res["grid_name"] = model.get("parent").get("variable"); + } + } + // For form + _.forEach(this.dependencies[this.getFieldId(model)], function (el) { + var obj = _.find(that.fields, function (f) { + return f.model.get("id") == el; + }); + if (obj) { + res[obj.model.get("id")] = obj.model.get("data").value; + } + }); + return res; + }; + + PMDynaform.extendNamespace("PMDynaform.util.DependentsFieldManager", DependentsFieldManager); +}()); +(function () { + + var RestProxy = function (options) { + this.url = null; + this.method = null; + this.rc = null; + this.data = null; + RestProxy.prototype.init.call(this, options); + }; + + RestProxy.prototype.type = "RestProxy"; + RestProxy.prototype.init = function (options) { + var defaults = { + url: null, + method: 'GET', + data: {}, + dataType: 'json', + authorizationType: 'none', + authorizationOAuth: false, + success: function () { + }, + failure: function () { + }, + complete: function () { + } + }; + jQuery.extend(true, defaults, options); + this.setRestClient() + .setUrl(defaults.url) + .setAuthorizationOAuth(defaults.authorizationOAuth) + .setMethod(defaults.method) + .setData(defaults.data) + .setDataType(defaults.dataType) + .setSuccessAction(defaults.success) + .setFailureAction(defaults.failure) + .setCompleteAction(defaults.complete); + }; + + RestProxy.prototype.setRestClient = function () { + if (this.rc instanceof RestClient === false) { + this.rc = new RestClient(); + } + return this; + }; + + RestProxy.prototype.setUrl = function (url) { + this.url = url; + return this; + }; + + RestProxy.prototype.setAuthorizationOAuth = function (option) { + if (typeof option === 'boolean') { + this.rc.setSendBearerAuthorization(option); + } + return this; + }; + + RestProxy.prototype.setMethod = function (method) { + this.method = method; + return this; + }; + RestProxy.prototype.setSuccessAction = function (action) { + RestProxy.prototype.success = action; + return this; + }; + RestProxy.prototype.setFailureAction = function (action) { + RestProxy.prototype.failure = action; + return this; + }; + RestProxy.prototype.setCompleteAction = function (action) { + RestProxy.prototype.complete = action; + return this; + }; + + RestProxy.prototype.setData = function (data) { + this.data = data; + return this; + }; + RestProxy.prototype.getData = function () { + return this.data; + }; + RestProxy.prototype.setDataType = function (dataType) { + this.rc.setDataType(dataType); + return this; + }; + RestProxy.prototype.setCredentials = function (usr, pass) { + this.rc.setBasicCredentials(usr, pass); + return this; + }; + RestProxy.prototype.setContentType = function () { + this.rc.setContentType(); + return this; + }; + RestProxy.prototype.send = function () { + }; + + RestProxy.prototype.receive = function () { + }; + RestProxy.prototype.setAuthorizationType = function (type, credentials) { + this.rc.setAuthorizationType(type); + switch (type) { + case 'none': + break; + case 'basic': + this.rc.setBasicCredentials(credentials.client, credentials.secret); + break; + case 'oauth2': + this.rc.setAccessToken(credentials); + break; + } + + return this; + }; + + RestProxy.prototype.post = function (settings) { + var that = this; + if (settings !== undefined) { + that.init(settings); + } + if (this.rc) { + that.rc.postCall({ + url: that.url, + id: that.uid, + data: that.data, + success: function (xhr, response) { + that.success.call(that, xhr, response); + }, + failure: function (xhr, response) { + that.failure.call(that, xhr, response); + }, + complete: function (xhr, response) { + that.complete.call(that, xhr, response); + } + }); + that.rc.setSendBearerAuthorization(false); + + } else { + throw new Error("the RestClient was not defined, please verify the property 'rc' for continue."); + } + }; + + RestProxy.prototype.update = function (settings) { + var that = this; + if (settings !== undefined) { + that.init(settings); + } + if (this.rc) { + this.rc.putCall({ + url: this.url, + id: this.uid, + data: this.data, + success: function (xhr, response) { + that.success.call(this, xhr, response); + }, + failure: function (xhr, response) { + that.failure.call(this, xhr, response); + }, + complete: function (xhr, response) { + that.complete.call(that, xhr, response); + } + }); + } else { + throw new Error("the RestClient was not defined, please verify the property 'rc' for continue."); + } + }; + + RestProxy.prototype.get = function (settings) { + var that = this; + if (settings !== undefined) { + that.init(settings); + } + if (this.rc) { + that.rc.getCall({ + url: that.url, + id: that.uid, + data: that.data, + success: function (xhr, response) { + that.success.call(that, xhr, response); + }, + failure: function (xhr, response) { + that.failure.call(that, xhr, response); + }, + complete: function (xhr, response) { + that.complete.call(that, xhr, response); + } + }); + that.rc.setSendBearerAuthorization(false); + + } else { + throw new Error("the RestClient was not defined, please verify the property 'rc' for continue."); + } + }; + + RestProxy.prototype.remove = function (settings) { + var that = this; + if (settings !== undefined) { + that.init(settings); + } + if (this.rc) { + this.rc.deleteCall({ + url: this.url, + id: this.uid, + data: this.data, + success: function (xhr, response) { + that.success.call(this, xhr, response); + }, + failure: function (xhr, response) { + that.failure.call(this, xhr, response); + }, + complete: function (xhr, response) { + that.complete.call(that, xhr, response); + } + }); + } else { + throw new Error("the RestClient was not defined, please verify the property for continue."); + } + }; + + RestProxy.prototype.success = function (xhr, response) { + }; + + RestProxy.prototype.failure = function (xhr, response) { + }; + + RestProxy.prototype.complete = function (xhr, response) { + }; + + PMDynaform.extendNamespace('PMDynaform.proxy.RestProxy', RestProxy); + +}()); +(function () { + + var Validator = Backbone.View.extend({ + template: _.template($("#tpl-validator").html()), + events: { + "mouseover": "onMouseOver" + }, + initialize: function () { + this.render(); + }, + onMouseOver: function () { + + }, + render: function () { + this.$el.addClass("pmdynaform-message-error"); + this.$el.html(this.template(this.model.toJSON())); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Validator", Validator); + +}()); +(function () { + var PanelView = Backbone.View.extend({ + content: null, + colsIndex: null, + template: null, + collection: null, + items: null, + views: [], + renderTo: document.body, + project: null, + events: { + "click a#print-button": "printForm" + }, + initialize: function (options) { + var i, defaults = { + factory: { + products: { + "form": { + model: PMDynaform.model.FormPanel, + view: PMDynaform.view.FormPanel + }, + "fieldset": { + model: PMDynaform.model.Fieldset, + view: PMDynaform.view.Fieldset + }, + "panel": { + model: PMDynaform.model.FormPanel, + view: PMDynaform.view.FormPanel + } + }, + defaultProduct: "form" + } + }; + if (options.renderTo) { + this.renderTo = options.renderTo; + } + if (options.project) { + this.project = options.project; + } + this.views = []; + + this.makePanels(); + this.render(); + for (i = 0; i < this.views.length; i += 1) { + this.views[i].runningFormulator(); + this.views[i].afterRenderHook(); + } + }, + printForm: function () { + var result, + flashModel, + forms = this.views, + i, + form, + formMode = forms[0].model.get("mode"), + project = this.project; + + if ((project && project.isPreview) || formMode === "disabled") { + window.print(); + } else { + if (typeof this.views[0].model.get("onBeforePrintHandler") === "function") { + this.views[0].model.get("onBeforePrintHandler")(); + } + for (i = 0; i < forms.length; i += 1) { + form = forms[i]; + result = form.saveForm(); + } + if (result) { + window.print(); + if (typeof this.views[0].model.get("onAfterPrintHandler") === "function") { + this.views[0].model.get("onAfterPrintHandler")(); + } + } else { + flashModel = { + message: "error", + emphasisMessage: "Error:", + startAnimation: 1000, + type: "danger", + appendTo: this.el, + duration: 3000 + }; + this.project.flashMessage(flashModel); + } + } + return this; + }, + getData: function () { + var i, + k, + field, + subform, + fields, + panels, + formData; + + panels = this.model.get("items"); + formData = this.model.getData(); + for (i = 0; i < panels.length; i += 1) { + fields = this.views[i].items.asArray(); + for (k = 0; k < fields.length; k += 1) { + + if ((typeof fields[k].model.getData === "function") && (fields[k].model.attributes.type === "form")) { + subform = fields[k].getData(); + $.extend(true, formData.variables, subform.variables); + } else if (typeof fields[k].model.getData === "function") { + field = fields[k].model.getData(); + formData.variables[field.name] = field.value; + } + } + } + return formData; + }, + /** + * Function to get Data to end point + * @returns {{}} + */ + getData2: function () { + var i, + k, + fieldDt, + fields, + panels, + grid, + data = {}, + dataRecursive; + + panels = this.model.get("items"); + for (i = 0; i < panels.length; i += 1) { + fields = this.views[i].items.asArray(); + for (k = 0; k < fields.length; k += 1) { + if (this.isValidFieldToSendData(fields[k])) { + if (typeof fields[k].getItems === "function") { + dataRecursive = this.getDataRecursive(fields[k]); + $.extend(true, data, dataRecursive); + } else if (typeof fields[k].model.getData === "function") { + if (fields[k].model.get("type") === "grid") { + grid = fields[k].model; + data[grid.get("name")] = fields[k].getData2(); + } else { + fieldDt = fields[k].model.getAppData(); + $.extend(true, data, fieldDt); + } + } + } + } + } + return data; + }, + /** + * Function to get deleted data for multiple file upload field + * @returns {Object} + */ + getDeletedData: function () { + var i, + k, + fields, + panels, + removedDataRecursive, + grid, + data = {"__VARIABLE_DOCUMENT_DELETE__": {}}, + documentDelete; + panels = this.model.get("items"); + for (i = 0; i < panels.length; i += 1) { + fields = this.views[i].items.asArray(); + for (k = 0; k < fields.length; k += 1) { + if (this.isValidFieldToSendData(fields[k])) { + if (typeof fields[k].getItems === "function") { + removedDataRecursive = this.getRemovedDataRecursive(fields[k]); + $.extend(true, data["__VARIABLE_DOCUMENT_DELETE__"], removedDataRecursive); + } else if (typeof fields[k].model.getData === "function") { + if (fields[k].model.get("type") === "grid") { + grid = fields[k].model; + if (typeof fields[k].getDeletedData === "function") { + data["__VARIABLE_DOCUMENT_DELETE__"][grid.get("name")] = fields[k].getDeletedData(); + } + } else { + if (typeof fields[k].model.makeVariableDocumentDelete === "function") { + documentDelete = fields[k].model.makeVariableDocumentDelete(); + $.extend(true, data["__VARIABLE_DOCUMENT_DELETE__"], documentDelete); + } + } + } + } + } + } + return data; + }, + /** + * This function verify that field is valid to send data + * @param field + * @returns {boolean} + */ + isValidFieldToSendData: function (field) { + var flag = false, + invalidTypes = ["empty", "title", "subtitle", "button", "submit", "panel", "link", "image"]; + + if (field.model.get("mode") === "view") { + if (invalidTypes.indexOf(field.model.get("originalType")) === -1) { + flag = true; + } + } else { + if (invalidTypes.indexOf(field.model.get("type")) === -1) { + flag = true; + } + } + return flag; + }, + setAppData: function (data) { + this.getPanels()[0].setAppData(data); + }, + getDataRecursive: function (view) { + var items = view.getItems(), + viewField, + fieldDt, + dataRecursive = {}, + grid, + data = {}, + index; + + for (index = 0; index < items.length; index += 1) { + if (this.isValidFieldToSendData(items[index])) { + viewField = items[index]; + if (this.isValidFieldToSendData(viewField)) { + if (typeof viewField.getItems === "function") { + dataRecursive = this.getDataRecursive(viewField); + $.extend(true, data, dataRecursive); + } else if (typeof viewField.model.getData === "function") { + if (viewField.model.get("type") === "grid") { + grid = viewField.model; + data[grid.get("name")] = viewField.getData2(); + } else { + fieldDt = viewField.model.getAppData(); + $.extend(true, data, fieldDt); + } + } + } + } + } + return data; + }, + /** + * Get all subform multiple file removed data + * @param {*} view + * @returns {Object} + */ + getRemovedDataRecursive: function (view) { + var items = view.getItems(), + viewField, + fieldDt, + dataRecursive = {}, + grid, + data = {}, + index; + for (index = 0; index < items.length; index += 1) { + if (this.isValidFieldToSendData(items[index])) { + viewField = items[index]; + if (this.isValidFieldToSendData(viewField)) { + if (typeof viewField.getItems === "function") { + dataRecursive = this.getRemovedDataRecursive(viewField); + $.extend(true, data, dataRecursive); + } else if (typeof viewField.model.getData === "function") { + if (viewField.model.get("type") === "grid") { + grid = viewField.model; + if (typeof viewField.getDeletedData === "function") { + data[grid.get("name")] = viewField.getDeletedData(); + } + } else { + if (typeof viewField.model.makeVariableDocumentDelete === "function") { + fieldDt = viewField.model.makeVariableDocumentDelete(); + $.extend(true, data, fieldDt); + } + } + } + } + } + } + return data; + }, + setData2: function (data) { + var index = 0; + this.getPanels()[index].setData2(data); + return this; + }, + makePanels: function () { + var i, + items, + panelModel, + view; + + this.views = []; + items = this.model.get("items"); + + for (i = 0; i < items.length; i += 1) { + if ($.inArray(items[i].type, ["panel", "form"]) >= 0) { + items[i].parent = this; + panelModel = new PMDynaform.model.FormPanel(items[i]); + panelModel.set("project", this.project); + view = new PMDynaform.view.FormPanel({ + model: panelModel, + project: this.project + }); + + if (this.project) { + panelModel.set("project", this.project); + } + + this.views.push(view); + } + } + + return this; + }, + getPanels: function () { + return (this.views.length > 0) ? this.views : []; + }, + render: function () { + var i, + printed = true; + + this.$el = $(this.el); + for (i = 0; i < this.views.length; i += 1) { + printed = this.views[i].model.get("printable"); + this.$el.append(this.views[i].render().el); + if (i === 0 && printed && typeof PMDynaform.core.ProjectMobile === "undefined") { + this.addPrinForm(this.views[i].el); + if (typeof this.views[i].model.get("onBeforePrintHandler") === "function") { + this.model.set("onBeforePrintHandlder", this.views[i].model.get("onBeforePrintHandlder")) + } + if (typeof this.views[i].model.get("onAfterPrintHandler") === "function") { + this.model.set("onAfterPrintHandlder", this.views[i].model.get("onAfterPrintHandlder")) + } + } + } + this.$el.addClass("pmdynaform-container"); + if (PMDynaform.core.ProjectMobile) { + this.$el.css({ + height: "auto" + }); + } + $(this.renderTo).append(this.el); + + return this; + }, + afterRender: function () { + var i; + + for (i = 0; i < this.views.length; i += 1) { + this.views[i].afterRender(); + } + + return this; + }, + addPrinForm: function (container) { + var printContainer, + buttonPrint; + printContainer = document.createElement("div"); + buttonPrint = document.createElement("a"); + buttonPrint.className = "print-button"; + buttonPrint.id = "print-button"; + printContainer.appendChild(buttonPrint); + printContainer.className = "printContainer"; + if (container instanceof jQuery) { + container.prepend(printContainer); + } else { + $(container).prepend(printContainer); + } + return this; + }, + /** + * Execute this function on after the submit button + * @returns {PanelView} + */ + afterSubmit: function () { + var index; + for (index = 0; index < this.views.length; index += 1) { + if (_.isFunction(this.views[index].afterSubmit)) { + this.views[index].afterSubmit(); + } + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Panel", PanelView); + +}()); + +(function () { + var FormPanel = Backbone.View.extend({ + tagName: "form", + content: null, + template: null, + items: new PMDynaform.util.ArrayList(), + views: [], + templateRow: _.template($('#tpl-row').html()), + colSpanLabel: 3, + colSpanControl: 9, + project: null, + preTargetControl: null, + sqlFields: [], + changeFired: false, + submit: [], + events: { + 'submit': 'onSubmit' + }, + onChange: function () { + }, + onChangeCallback: function () { + }, + requireVariableByField: [], + /** + * Executes form and subForm's onChangeCallBack + * @param params + */ + checkBinding: function (params) { + var parent = this.project.getForm(), + mobileSubForm = this.model.get("form"), + idField = this.model.get("id") || (mobileSubForm && mobileSubForm.model.get("id")); + params = this.getExtraData(params); + //Executes onChangeCallBack of the SubForm + this.onChangeCallback(params.idField, params.current, params.previous, params.row); + if (parent && parent.model.isSubForm(idField)) { + //Executes onChangeCallBack of the Form + parent.onChangeCallback(params.idField, params.current, params.previous, params.row); + } + }, + /** + * Sets OnChangeCallBack function. + * @param handler + * @returns {FormPanel} + */ + setOnChange: function (handler) { + if (typeof handler === "function") { + this.onChangeCallback = handler; + } + return this; + }, + /** + * Modifies the current params. + * @param params {object} + * @returns {object} + */ + getExtraData: function (params) { + if (this.hasOwnProperty("extraData")) { + params.idField = this.createGridId(this.extraData.gridId, this.extraData.nRow, params.idField) || params.idField; + params.row = this.getFields() || null; + } + return params; + }, + /** + * Create newId for MobileGrid. + * @param gridId + * @param nRow + * @param idColumn + * @returns {string} + */ + createGridId: function (gridId, nRow, idColumn) { + return "[" + gridId + "][" + nRow + "][" + idColumn + "]"; + }, + onChangeHandler: function () { + var that = this; + return function (field, newValue, previousValue) { + if (typeof that.onChange === 'function') { + that.onChange(field, newValue, previousValue); + } + }; + }, + initialize: function (options) { + var fileConf, + gridConf; + + if (PMDynaform.core.ProjectMobile) { + gridConf = { + model: PMDynaform.model.GridMobile, + view: PMDynaform.view.GridMobile + }; + fileConf = { + model: PMDynaform.model.FileUpload, + view: PMDynaform.view.FileUpload + }; + } else { + gridConf = { + model: PMDynaform.model.GridPanel, + view: PMDynaform.view.GridPanel + }; + fileConf = { + model: PMDynaform.model.File, + view: PMDynaform.view.File + }; + } + var defaults = { + factory: { + products: { + "text": { + model: PMDynaform.model.TextR, + view: PMDynaform.view.TextR + }, + "textarea": { + model: PMDynaform.model.TextAreaR, + view: PMDynaform.view.TextAreaR + }, + "checkgroup": { + model: PMDynaform.model.CheckGroupR, + view: PMDynaform.view.CheckGroupR + }, + "checkbox": { + model: PMDynaform.model.CheckBox, + view: PMDynaform.view.CheckBox + }, + "radio": { + model: PMDynaform.model.RadioR, + view: PMDynaform.view.RadioR + }, + "dropdown": { + model: PMDynaform.model.DropdownR, + view: PMDynaform.view.DropdownR + }, + "button": { + model: PMDynaform.model.Button, + view: PMDynaform.view.Button + }, + "submit": { + model: PMDynaform.model.Submit, + view: PMDynaform.view.Submit + }, + "datetime": { + model: PMDynaform.model.DatetimeR, + view: PMDynaform.view.DatetimeR + }, + "fieldset": { + model: PMDynaform.model.Fieldset, + view: PMDynaform.view.Fieldset + }, + "suggest": { + model: PMDynaform.model.SuggestR, + view: PMDynaform.view.SuggestR + }, + "link": { + model: PMDynaform.model.Link, + view: PMDynaform.view.Link + }, + "hidden": { + model: PMDynaform.model.Hidden, + view: PMDynaform.view.Hidden + }, + "title": { + model: PMDynaform.model.Title, + view: PMDynaform.view.Title + }, + "subtitle": { + model: PMDynaform.model.Title, + view: PMDynaform.view.Title + }, + "label": { + model: PMDynaform.model.Label, + view: PMDynaform.view.Label + }, + "empty": { + model: PMDynaform.model.Empty, + view: PMDynaform.view.Empty + }, + "file": fileConf, + "image": { + model: PMDynaform.model.Image, + view: PMDynaform.view.Image + }, + "geomap": { + model: PMDynaform.model.GeoMap, + view: PMDynaform.view.GeoMap + }, + "grid": gridConf, + "form": { + model: PMDynaform.model.SubForm, + view: PMDynaform.view.SubForm + }, + "annotation": { + model: PMDynaform.model.Annotation, + view: PMDynaform.view.Annotation + }, + "location": { + model: PMDynaform.model.GeoMobile, + view: PMDynaform.view.GeoMobile + }, + "scannercode": { + model: PMDynaform.model.Qrcode_mobile, + view: PMDynaform.view.Qrcode_mobile + }, + "signature": { + model: PMDynaform.model.Signature_mobile, + view: PMDynaform.view.Signature_mobile + }, + "imagemobile": { + model: PMDynaform.model.ImageFieldModel, + view: PMDynaform.view.ImageFieldView + }, + "audiomobile": { + model: PMDynaform.model.FileMobile, + view: PMDynaform.view.FileMobile + }, + "videomobile": { + model: PMDynaform.model.FileMobile, + view: PMDynaform.view.FileMobile + }, + "panel": { + model: PMDynaform.model.PanelField, + view: PMDynaform.view.PanelField + }, + "multiplefile": { + model: PMDynaform.file.MultipleFileModel, + view: PMDynaform.file.MultipleFileView + } + }, + defaultProduct: "empty" + } + }; + this.items = new PMDynaform.util.ArrayList(); + this.onChangeCallback = options.onChangeCallback ? options.onChangeCallback : new Function(); + if (options.project) { + this.project = options.project; + } + this.setFactory(defaults.factory); + this.applyGlobalMode(); + this.makeItems(); + }, + setAction: function () { + this.$el.attr("action", this.model.get("action")); + return this; + }, + setMethod: function () { + this.$el.attr("method", this.model.get("method")); + + return this; + }, + setFactory: function (factory) { + this.factory = factory; + return this; + }, + getData: function () { + var i, + k, + field, + fields, + panels, + data = [], + + panels = this.viewsBuilt; + + for (i = 0; i < panels.length; i += 1) { + fields = panels[i]; + for (k = 0; k < fields.length; k += 1) { + field = fields[k].model.get("data"); + data.push(field); + } + } + return data; + }, + countElementsInJSON: function (obj) { + var i = 0, + item; + for (item in obj) { + i += 1; + } + return i; + }, + setData2: function (data) { + var key, value, label, field, nameReplace, name; + if (typeof data === "object") { + for (key in data) { + name = key; + field = getFieldByName(name); + if (_.isArray(field) && field.length > 0) { + value = data[key]; + if (data.hasOwnProperty(key + "_label")) { + label = data[key + "_label"]; + } else { + label = data[key]; + } + jQuery.each(field, function (index, element) { + element.setData({ + value: value, + label: label + }); + }); + } + } + } + return this; + }, + /** + * setAppData Sets the data to the form + * @param appData {object} Set of valid data for the form + * @chainable + */ + setAppData: function (appData) { + if (typeof appData === "object") { + this.model.setAppData(appData); + } + return this; + }, + validateVariableField: function (field) { + var isOk = false; + if ($.inArray(field.type, this.requireVariableByField) >= 0) { + if (field.var_uid) { + isOk = true; + } + } else { + isOk = "NOT"; + } + return isOk; + }, + makeItems: function () { + var i, + j, + factory = this.factory, + that = this, + product, + variableEnabled, + productBuilt, + rowView, + productModel, + jsonFixed, + fieldModel, + fields, + items, + configColSpan; + this.sqlFields = []; + fields = this.model.get("items"); + this.viewsBuilt = []; + this.items.clear(); + + for (i = 0; i < fields.length; i += 1) { + rowView = []; + for (j = 0; j < fields[i].length; j += 1) { + variableEnabled = this.validateVariableField(fields[i][j]); + if (fields[i][j] !== null && (variableEnabled === true || variableEnabled === "NOT")) { + fields[i][j] = this.applyGlobalModeField(fields[i][j]); + if (fields[i][j].type) { + if (!PMDynaform.core.ProjectMobile && fields[i][j].type === "location") { + fields[i][j].type = "geomap"; + } + if (fields[i][j].type === "label") { + fields[i][j].type = "annotation"; + } + if (fields[i][j].type === "checkbox" && fields[i][j].dataType !== "boolean" && fields[i][j].dataType !== "") { + fields[i][j].type = "checkgroup"; + } + if (fields[i][j].type === "file" && fields[i][j].hasOwnProperty("inputDocuments")) { + if ($.isArray(fields[i][j]["inputDocuments"])) { + $(fields[i][j]["inputDocuments"]).each(function () { + that.model.attributes.inputDocuments[fields[i][j]["variable"]] = this; + }); + } + } + jsonFixed = new PMDynaform.core.TransformJSON({ + parentMode: this.model.get("mode"), + field: fields[i][j] + }); + product = factory.products[jsonFixed.getJSON().type.toLowerCase()] ? + factory.products[jsonFixed.getJSON().type.toLowerCase()] : factory.products[factory.defaultProduct]; + } else { + jsonFixed = new PMDynaform.core.TransformJSON({ + parentMode: this.model.get("mode"), + field: fields[i][j] + }); + product = factory.products[factory.defaultProduct]; + } + + //The number 12 is related to 12 columns from Bootstrap framework + configColSpan = this.generateColSpan(fields[i][j].colSpan); + fieldModel = { + project: this.project, + parentMode: this.model.get("mode"), + namespace: this.model.get("namespace"), + variable: fields[i][j].variable ? fields[i][j].variable : null, + name: fields[i][j].name, + id: fields[i][j].id || PMDynaform.core.Utils.generateID(), + options: fields[i][j].options, + optionsSql: fields[i][j].optionsSql, + required: fields[i][j].required || false, + hint: fields[i][j].hint || "", + format: fields[i][j].format || "", + formula: fields[i][j].formula || "", + sql: fields[i][j].sql || "", + defaultValue: fields[i][j].defaultValue || "", + defaultDate: fields[i][j].defaultDate || null, + _hidden: fields[i][j]._hidden || false, + colSpanLabel: configColSpan.label, + colSpanControl: configColSpan.control + }; + if (fields[i][j].type === "form" || fields[i][j].type === "grid") { + fieldModel.variables = this.model.get("variables") || []; + fieldModel.data = this.model.get("data") || []; + } + + $.extend(true, fieldModel, jsonFixed.getJSON()); + + if (fieldModel.type === "form" && fieldModel.mode === "parent") { + fieldModel.mode = this.model.get("mode"); + } + + //format data: geotag to text and textarea + if (fieldModel.data && (fieldModel.type === "text" || fieldModel.type === "textarea" )) { + var geo = fieldModel.data.value; + if (geo && geo.latitude && geo.longitude && geo.altitude) { + fieldModel.data.value = geo.latitude + " " + geo.longitude + " " + geo.altitude; + fieldModel.data.label = geo.latitude + " " + geo.longitude + " " + geo.altitude; + } + } + fieldModel.form = this.model; + fieldModel.parent = this.model; + productModel = new product.model(fieldModel); + productBuilt = new product.view({ + model: productModel, + project: this.project, + parent: this, + form: this + }); + if (productModel.get("type") === "form") { + this.model.get("subForms").insert(productBuilt); + } + productBuilt.parent = this; + productBuilt.project = this.project; + this.model.addField(productModel, productModel.get("variable") || productModel.get("name") || productModel.get("id")); + //add view in mobile project + if (this.project.addViewFields && productModel.get("type") !== "empty") { + this.project.addViewFields(productBuilt); + } + rowView.push(productBuilt); + this.items.insert(productBuilt); + productBuilt.model.attributes.view = productBuilt; + } else { + console.error("The field must have the variable property and must to be an object: ", fields[i][j]); + } + } + if (rowView.length) { + this.viewsBuilt.push(rowView); + } + } + this.runningFormulator(); + + this.model.get("dependentsManager").setupFields(this.getAllFields()); + return this; + }, + /** + * Generate the colSpan to label and control + * @param colSpan + * @returns {{label: number, control: number}} + */ + generateColSpan: function (colSpan) { + var defaultColSpan = { + label: 2, + control: 10 + }; + switch (parseInt(colSpan)) { + case 6: + case 4: + case 1: + defaultColSpan.label = 4; + defaultColSpan.control = 8; + break; + case 5: + case 3: + case 2: + defaultColSpan.label = 5; + defaultColSpan.control = 7; + break; + } + return defaultColSpan; + }, + /** + * Execute a defined hook for all rendered views + * @chainable + */ + afterRenderHook: function () { + var items, + field, + i, + j, + rowCurrent, + col, + row, + rowsAll; + items = this.viewsBuilt; + for (i = 0; i < items.length; i += 1) { + for (j = 0; j < items[i].length; j += 1) { + field = items[i][j]; + if (typeof field.model.afterRenderHook === "function") { + field.model.afterRenderHook(); + } + if (field.model.get("type") === "grid") { + rowsAll = field.gridtable; + for (row = 0; row < rowsAll.length; row += 1) { + rowCurrent = rowsAll[row]; + for (col = 0; col < rowCurrent.length; col += 1) { + if (typeof rowCurrent[col].model.afterRenderHook === "function") { + rowCurrent[col].model.afterRenderHook(); + } + } + } + } + } + } + return this; + }, + runningFormulator: function () { + var items, + field, + i, + j, + fieldsAsocied, + rowCurrent, + col; + items = this.viewsBuilt; + for (i = 0; i < items.length; i += 1) { + for (j = 0; j < items[i].length; j += 1) { + field = items[i][j]; + if (field.model.get("type") === "form") { + if (field.runningFormulator) { + field.runningFormulator(); + } + } + if (field.model.get("type") === "grid") { + var rowsAll = field.gridtable; + for (var row = 0; row < rowsAll.length; row += 1) { + rowCurrent = rowsAll[row]; + for (col = 0; col < rowCurrent.length; col += 1) { + if (rowCurrent[col].model.get("formula") && rowCurrent[col].model.get("formula").trim().length) { + fieldsAsocied = rowCurrent.filter(function (element) { + if (rowCurrent[col].fieldValid.indexOf(element.model.get("id")) > -1) { + element.onFieldAssociatedHandler(); + } + }); + } + } + } + } else { + if (field.model.get("formula") && field.model.get("formula").trim().length) { + fieldsAsocied = items.filter(function (element) { + var k; + for (k = 0; k < element.length; k += 1) { + if (field.fieldValid.indexOf(element[k].model.get("id")) > -1) { + element[k].onFieldAssociatedHandler(); + } + } + }); + } + } + } + } + return this; + }, + getVariable: function (var_uid) { + var i, + varSelected, + variables = this.model.attributes.variables; + + loop_variables: + for (i = 0; i < variables.length; i += 1) { + if (variables[i] && variables[i].var_uid === var_uid) { + varSelected = variables[i]; + break loop_variables; + } + } + return varSelected; + }, + getFields: function () { + return (this.items.getSize() > 0) ? this.items.asArray() : []; + }, + /** + * Returns all the fields in the form including the ones in any nested subform. + * @returns {Array.PMDynaform.view.Field} + */ + getAllFields: function () { + var formElements = this.getFields(), + subformsFields = [], + fields; + + fields = formElements.filter(function (i) { + // The second expression is necessary since Grid for Mobile doesn't inherit from PMDynaform.view.Field. + if (i instanceof PMDynaform.view.Field + || (PMDynaform.view.GridMobile && i instanceof PMDynaform.view.GridMobile)) { + return true; + } else if (i instanceof PMDynaform.view.SubForm) { + subformsFields = subformsFields.concat(i.getAllFields()); + } + return false; + }); + + return fields.concat(subformsFields); + }, + beforeRender: function () { + return this; + }, + applySuccess: function () { + var items = this.items.asArray(), + i; + + for (i = 0; i < items.length; i += 1) { + if (items[i].applyStyleSuccess) { + items[i].applyStyleSuccess(); + } + } + }, + onSubmit: function (event) { + var booResponse; + if (this.executeSubmitArray()) { + if (!this.isValid(event)) { + booResponse = false; + } else { + this.applySuccess(); + booResponse = true; + } + //validate if has has submitRest enabled + if (this.project.submitRest) { + if (event !== undefined) { + event.preventDefault(); + } + if (booResponse) { + this.project.onSubmitForm(); + } + } else { + if (booResponse && event && event.type === 'submit') { + this.prepareFormToPost(); + } + } + } + else { + if (event !== undefined) { + event.preventDefault(); + } + } + return booResponse; + }, + /** + * Submit to next step the current form panel + */ + submitNextStep: function () { + this.$el.submit(); + return this; + }, + /** + * prepare and enable fields to post the data + * @param event + * @returns {FormPanel} + */ + prepareFormToPost: function () { + //force to enable to post data + if (this.project) { + this.project.modalProgress.render(); + } + this.$el.find(".form-control").prop('disabled', false); + this.$el.find("input[type='hidden']").prop('disabled', false); + this.$el.find(".pmdynaform-control-checkbox").prop('disabled', false); + this.$el.find(".pmdynaform-control-checkgroup").prop('disabled', false); + this.$el.find(".pmdynaform-control-radio").prop('disabled', false); + return this; + }, + executeSubmitArray: function () { + var executeSubmit = true, + responseCallback = true, + indexSubmit; + + for (indexSubmit = 0; indexSubmit < this.submit.length; indexSubmit += 1) { + if (typeof this.submit[indexSubmit] === "function") { + responseCallback = this.submit[indexSubmit](); + if (responseCallback !== undefined && typeof responseCallback === "boolean" && responseCallback === false) { + executeSubmit = false; + break; + } + } + } + return executeSubmit; + }, + /** + * Ckeck if there is a dependent field loading. + * @returns {Boolean} + */ + isRunningDependents: function () { + var i, + formValid = true, + itemsField = this.items.asArray(), + field, + hasLoadingFields = false; + if (itemsField.length > 0) { + for (i = 0; i < itemsField.length; i += 1) { + field = itemsField[i]; + if (field.isLoading && field.isLoading()) { + hasLoadingFields = true; + break; + } + } + } + if (hasLoadingFields) { + this.waitToLoadFieldsMessage(); + formValid = false; + } + return formValid; + }, + isValid: function (event) { + var i, + formValid = true, + itemField, + itemsField = this.items.asArray(), + filesNoUploaded = [], + field, + hasLoadingFields = false; + + if (itemsField.length > 0) { + for (i = 0; i < itemsField.length; i += 1) { + field = itemsField[i]; + if (field.validate) { + if (field.firstLoad) { + field.firstLoad = false; + } + field.validate(event); + if (!field.model.get("valid")) { + if (itemField === undefined) { + itemField = field; + } + formValid = field.model.get("valid"); + } + } + if (field.isLoading && field.isLoading()) { + hasLoadingFields = true; + } + // Verify if there is getFilesNotUploaded method + if (field.getFilesNotUploaded && typeof field.getFilesNotUploaded === "function") { + filesNoUploaded = filesNoUploaded.concat(field.getFilesNotUploaded()); + } + } + } + if (hasLoadingFields) { + this.waitToLoadFieldsMessage(); + formValid = false; + } + if (filesNoUploaded.length > 0) { + formValid = false; + this.showFilesNoUploaded(filesNoUploaded); + } + if (formValid) { + for (i = 0; i < itemsField.length; i += 1) { + if (( itemsField[i].model.get("var_name") !== undefined) && (itemsField[i].model.get("var_name").trim().length === 0 )) { + if (itemsField[i].model.get("type") === "radio") { + itemsField[i].$el.find("input").attr("name", ""); + } + } + } + } else { + if (itemField && itemField.model.get("type") !== "grid" && itemField.model.get("type") !== "form") { + itemField.setFocus(); + } + } + return formValid; + }, + render: function (subForm) { + var i, + j, + $rowView; + if (subForm) { + this.el = document.createElement("div"); + this.$el = $(this.el); + } + for (i = 0; i < this.viewsBuilt.length; i += 1) { + $rowView = $(this.templateRow()); + for (j = 0; j < this.viewsBuilt[i].length; j += 1) { + this.viewsBuilt[i][j].model.set('nameModalSuggest', this.__uidModal || null); + $rowView.append(this.viewsBuilt[i][j].render().el); + } + this.$el.append($rowView); + } + this.$el.attr("role", "form"); + this.$el.addClass("form-horizontal pmdynaform-form"); + this.el.style.height = "auto"; + this.setAction(); + this.setMethod(); + this.$el.attr("id", this.model.get("id")); + if (this.model.get("target")) { + this.$el.attr("target", this.model.get("target")); + } + + var ids = this.model.get("inputDocuments"); + for (var id in ids) { + var hidenInputs = document.createElement("input"); + hidenInputs.name = "INPUTS[" + id + "]"; + hidenInputs.type = "hidden"; + hidenInputs.value = ids[id]; + this.el.appendChild(hidenInputs); + } + return this; + }, + afterRender: function () { + var i, + items = this.items.asArray(); + for (i = 0; i < items.length; i += 1) { + if (items[i].afterRender) { + items[i].afterRender(); + } + } + return this; + }, + setOnSubmit: function (callback) { + this.submit = []; + if (callback && typeof callback === "function") { + this.submit.push(callback); + } else { + return null; + } + }, + applyGlobalModeField: function (json) { + if (this.project.globalMode && this.project.globalMode === 'view') { + json.mode = this.project.globalMode; + } + return json; + }, + applyGlobalMode: function () { + if (this.project.globalMode === "view") { + if (this.model.get("type") && this.model.get("type") === "form") { + this.model.set("mode", this.project.globalMode); + } + } + return this; + }, + /** + * this method close this form, stand alone version for mobile + */ + close: function () { + this.model.close(); + }, + /** + * This method looks fields from a valid criterion + * @param {String} criteria : es un criterio de filtro + * @return {Array} result filter + */ + searchFieldType: function (criteria) { + var result = [], + fields = this.getFields(); + if (criteria && criteria !== undefined) { + result = _.filter(fields, function (item) { + if (item.model.get("type") === criteria) { + return item; + } + }); + } + return result; + }, + /** + * Saves form's data and validate connection (offline/online) + * @returns {boolean} + */ + saveForm: function () { + var project = this.project, + panel = this.model.get("parent"), + formId = this.model.get("id"), + webServiceManager, + requestManager, + formData, + resp = true; + + if (project && panel && this.isRunningDependents()) { + webServiceManager = project.webServiceManager; + formData = panel.getData2(); + if (project.isMobile()) { + $.extend(true, + formData, + { + "__VARIABLE_DOCUMENT_DELETE__": project.getDataExtra("__VARIABLE_DOCUMENT_DELETE__") + }); + requestManager = project.getRequestManager(); + if (requestManager && requestManager.isOffLine()) { + app.saveFormDataOffLine(); + return resp; + } + } else { + $.extend(true, formData, panel.getDeletedData()); + } + webServiceManager.saveData({ + formUID: formId, + data: formData + }, function (err) { + resp = !err; + }); + return resp; + } + }, + /** + * Execute this function on after the submit button + * @returns {FormPanel} + */ + afterSubmit: function () { + var items = this.items.asArray(), + index; + for (index = 0; index < items.length; index += 1) { + if (items[index].afterSubmit) { + items[index].afterSubmit(); + } + } + return this; + }, + /** + * Show flash message with files no uploaded yet. + * @param files + */ + showFilesNoUploaded: function (files) { + var flashModel, + i, + nameFiles = [], + message = "Form cannot be submitted because file(s) {%%%FILES%%%} (are/is) still uploading".translate(); + for (i = 0; i < files.length; i += 1) { + if (files[i].type) { + message = "Form cannot be submitted because file(s) {%%%FILES%%%} (are/is) didn't upload correctly," + + " remove the files from the form or upload the files again".translate(); + } + nameFiles.push(files[i].name); + } + if (files.length > 0) { + message = message.replace("{%%%FILES%%%}", nameFiles); + flashModel = { + message: message, + startAnimation: 1000, + type: "danger", + duration: 4000, + absoluteTop: true + }; + this.project.flashMessage(flashModel); + } + }, + /** + * Show flash message with the labels of the not loaded fields. + * @param files + */ + waitToLoadFieldsMessage: function () { + var warningLabel = "Warning".translate(); + message = "The form cannot be saved, please wait until all the fields are loaded".translate(); + + $.notify({ + // options + message: ''+ warningLabel +': ' + message + },{ + // settings + type: 'warning', + spacing: 10, + allow_dismiss: true, + delay: 6000, + timer: 1000, + placement: { + from: "top", + align: "center" + }, + animate: { + enter: 'animated fadeInDown', + exit: 'animated fadeOutUp' + } + }); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.FormPanel", FormPanel); +}()); + +(function () { + var FieldView = Backbone.View.extend({ + form: null, + _hidden: false, + tagName: "div", + tagControl: "", + tagHiddenToLabel: "", + keyLabelControl: "", + enableValidate: true, + events: { + "click .form-control": "onclickField" + }, + language: null, + spinner: null, + initialize: function (options) { + var defaults = { + hidden: true + }; + this.form = options.form ? options.form : null; + jQuery.extend(true, defaults, options); + + if (defaults.hidden) { + this.hide(); + } else { + this.show(); + } + + if (options && options.project) { + this.project = options.project; + } + this.setClassName() + .render(); + }, + setColumnIndex: function (index) { + this.columnIndex = index; + }, + setClassName: function () { + return this; + }, + enableTooltip: function () { + var tl = this.$el.find("[data-toggle=tooltip]"); + tl.tooltip({ + placement: "auto left", + trigger: "click hover" + }); + return this; + }, + applyStyleError: function () { + this.$el.addClass("has-error has-feedback"); + return this; + }, + applyStyleWarning: function () { + this.$el.addClass('has-warning'); + return this; + }, + applyStyleSuccess: function () { + this.$el.removeClass("has-error"); + if (!this.model.get("disabled")) { + this.$el.addClass("has-success"); + } + + return this; + }, + /** + * The method is only supported if the field have options. + * Checks if the value to sets is inside of the options property. + */ + setValueToDomain: function () { + var htmlElement = this.getHTMLControl(); + + if (htmlElement.length && !this.model.attributes.disabled) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error'); + } + + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + + htmlElement.parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } + + return this; + }, + /** + * Apply Javascript events associated to control + * + */ + on: function (e, fn) { + var that = this, + control = this.$el.find("input"); + + if (control) { + control.on(e, function (event) { + fn(event, that); + + event.stopPropagation(); + }); + } else { + throw new Error("Is not possible find the HTMLElement associated to field"); + } + + return this; + }, + /** + * The method is just for return the Jquery HTML of the control + * @return {JQuery HTMLElement} Encapsulate the HTMLElement + */ + getHTMLControl: function () { + return this; + }, + render: function () { + if (this._hidden || this.model.get("_hidden")) { + this.hide(); + } else { + this.show(); + } + if (!this.model.get("enableValidate")) { + this.hideRequire(); + } + return this; + }, + onclickField: function () { + return this; + }, + setLabel: function (label, col) { + if (this.model.get("type") === "grid") { + if (col !== undefined) { + if (col > 0 && col <= this.columnsModel.length) { + this.domTitleHeader[col - 1].find("span[class='title-column']").text(label); + } else { + return null; + } + } + } else { + if (this.model.attributes.label !== undefined) { + this.model.attributes.label = label; + if (this.el || this.$el.length) { + this.$el.find("label").find("span[class='textlabel']").text(label); + this.$el.find("h4").find("span[class='textlabel']").text(label); + this.$el.find("h5").find("span[class='textlabel']").text(label); + this.$el.find(".pmdynaform-grid-title span").text(label); + this.$el.find(".pmdynaform-control-annotation span").text(label); + this.$el.find("button[type='button'].btn-primary span").text(label); + this.$el.find("button[type='submit'] span").text(label); + } + } + } + return this; + }, + getLabel: function (col) { + if (this.model.get("label") !== undefined) { + if (col && this.model.get("type") === "grid") { + if (col <= this.columnsModel.length) { + return this.columnsModel[col - 1].label || ""; + } else { + return null; + } + } else { + return this.model.get("label"); + } + } + return null; + }, + setText: function (value, row, col) { + var options, + data, + existData, + type, + dataType, + i, + valuesfortrue, + valuesforFalse; + existData = false; + type = this.model.get("type"); + dataType = this.model.get("dataType"); + data = {}; + if (type === "grid") { + if (row !== undefined && col !== undefined) { + if ((row > 0 && col > 0) && row <= this.gridtable.length && col <= this.columnsModel.length) { + return this.gridtable[row - 1][col - 1].setText(value); + } else { + return null; + } + } + } + if (value && value.toString().length || jQuery.isArray(value)) { + options = this.model.get("options"); + if (options && jQuery.isArray(options)) { + if (dataType === "boolean" && options.length) { + valuesfortrue = [1, true, "1", "true"]; + valuesforFalse = [0, false, "0", "false"]; + if (options[0].label === value) { + value = options[0].value; + } + if (options[1].label === value) { + value = options[1].value; + } + if (valuesfortrue.indexOf(options[0].value) > -1 && + valuesfortrue.indexOf(value) > -1) { + data = { + value: "1", + label: options[0].label + }; + this.setValue(data["value"]); + return; + } + if (valuesforFalse.indexOf(options[1].value) > -1 && + valuesforFalse.indexOf(value) > -1) { + data = { + value: "0", + label: options[1].label + }; + this.setValue(data["value"]); + return; + } + } else { + if (type === "checkgroup") { + var arrayDataValue = [], arrayDataLabel = []; + for (i = 0; i < options.length; i += 1) { + options[i].selected = false; + if (value.indexOf(options[i].label) > -1) { + options[i].selected = true; + arrayDataLabel.push(options[i].label); + arrayDataValue.push(options[i].value); + } + } + data = { + value: arrayDataValue, + label: arrayDataLabel + }; + this.setValue(data["value"]); + return; + } else { + for (i = 0; i < options.length; i += 1) { + if (options[i].label === value) { + data = { + label: options[i].label, + value: options[i].value + }; + existData = true; + this.setValue(data["value"]); + return; + } + } + } + } + } + if (!existData) { + if (type === "text" || type === "textarea" || type === "hidden" || type === "link" || type === "image" || + type == "title" || type == "annotation" || type == "subtitle" || type === "button" || type === "submit" || type === "suggest") { + data = { + value: value, + label: value + }; + this.setValue(data["value"]); + return; + existData = true; + } + if (type === "datetime") { + value = value.replace(/-/g, "/"); + if (new Date(value).toString() !== "Invalid Date") { + data = { + value: value, + label: value + } + this.setValue(data["value"]); + return; + } + existData = true; + } + } + if (existData) { + this.updateValueControlAndData(data, type, dataType); + } + } else { + if (this.model.get("type") === "annotation") { + this.$el.find(".pmdynaform-control-annotation span").text(value); + this.model.attributes.label = value; + } + if (this.model.get("type") === "button") { + this.$el.find("button[type='button'].btn-primary span").text(value); + this.model.attributes.label = value; + } + if (this.model.get("type") === "submit") { + this.$el.find("button[type='submit'] span").text(value); + this.model.attributes.label = value; + } + if (this.model.get("type") === "image") { + this.model.attributes.src = value; + this.$el.find("img").attr("src", value); + } + } + return this; + }, + updateValueControlAndData: function (data, type, dataType) { + var i; + if (this.tagControl instanceof jQuery && this.tagHiddenToLabel instanceof jQuery) { + if (type !== "datetime") { + this.model.attributes.data = data; + this.model.attributes.value = data["value"]; + if (this.model.attributes.hasOwnProperty("keyLabel")) { + this.model.attributes.keyLabel = data["label"]; + } + if (this.model.attributes.hasOwnProperty("keyValue")) { + this.model.attributes.keyValue = data["value"]; + } + if (type === "radio") { + this.tagControl.find("input[id='form\[" + this.model.get("id") + "\]'][value='" + data["value"] + "']").prop("checked", true); + } else if (type === "checkgroup" || type === "checkbox") { + this.tagControl.find("input[type='checkbox']").attr("checked", false); + for (i = 0; i < data["value"].length; i += 1) { + this.tagControl.find("input[id='form\[" + this.model.get("id") + "\][" + data["value"][i] + "]']").prop("checked", true); + } + this.model.attributes.labelsSelected = data["label"]; + } else { + this.tagControl.val(data["value"]); + } + if (type === "checkgroup") { + this.tagHiddenToLabel.val(JSON.stringify(data["label"])); + } else { + if (type === "link" || type === "annotation" || type === "title" || type === "subtitle" || + type === "button" || type === "submit") { + this.tagHiddenToLabel.html(data["label"]); + } else if (type === "image") { + this.setSrc(data["value"]); + } else { + this.tagHiddenToLabel.val(data["label"]); + } + } + if (this.validate) { + this.validate(); + } + } else { + this.$el.find("#datetime-container-control").data()["DateTimePicker"].date(new Date(data["value"])); + var label = this.$el.find("#datetime-container-control").data()["date"]; + var value = this.formatData(); + this.model.attributes.value = value; + this.model.attributes.data["value"] = value; + this.model.attributes.data["label"] = label; + this.model.attributes.keyLabel = label; + this.tagHiddenToLabel.val(this.model.get("data")["value"]); + } + } + return this; + }, + setValue: function () { + }, + getInfo: function () { + var info = this.model.toJSON(); + // validate if field has a data property + return typeof info.data !== "undefined" ? _.extend(info, {value: info.data.value || ""}) : info; + }, + setHref: function (value) { + }, + getDataType: function () { + return this.model.get("dataType") || null; + }, + getControlType: function () { + + }, + verifyData: function () { + }, + getData: function () { + return this.model.getData(); + }, + getDataLabel: function () { + return this.model.getKeyLabel(); + }, + getText: function () { + }, + getValue: function () { + return this.model.getValue(); + }, + disableValidation: function (col) { + var type, i, j; + var col = col; + type = this.model.get("type"); + if (type === "grid") { + if (col !== undefined) { + if (typeof col == "string") { + this.columnsModel.find(function (column, index) { + if (column.columnId === col) { + col = index + 1; + return; + } + }) + } + if ((col > 0 && col <= this.columnsModel.length)) { + this.domTitleHeader[col - 1].find(".pmdynaform-field-required").hide(); + for (i = 0; i < this.gridtable.length; i += 1) { + this.columnsModel[col - 1].enableValidate = false; + this.gridtable[i][col - 1].disableValidation(); + } + } else { + return null; + } + } else { + var i, j, row, cell; + for (i = 0; i < this.gridtable.length; i += 1) { + row = this.gridtable[i]; + for (j = 0; j < row.length; j += 1) { + cell = row[j]; + if (cell.model.get("enableValidate") !== undefined) { + cell.disableValidation(); + this.columnsModel[j].enableValidate = false; + this.domTitleHeader[j].find(".pmdynaform-field-required").hide(); + } + } + } + } + } + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (this.model.get("required")) { + this.$el.find(".pmdynaform-field-required").hide(); + } + this.model.attributes.enableValidate = false; + } + return this; + }, + enableValidation: function (col) { + var type, i, j, col = col; + type = this.model.get("type"); + if (type === "grid") { + if (col !== undefined) { + if (typeof col == "string") { + this.columnsModel.find(function (column, index) { + if (column.columnId === col) { + col = index + 1; + return; + } + }) + } + if (col > 0 && col <= this.columnsModel.length) { + this.domTitleHeader[col - 1].find(".pmdynaform-field-required").show(); + for (i = 0; i < this.gridtable.length; i += 1) { + this.columnsModel[col - 1].enableValidate = true; + this.gridtable[i][col - 1].enableValidation(); + } + } else { + return null; + } + } else { + var i, j, row, cell; + for (i = 0; i < this.gridtable.length; i += 1) { + row = this.gridtable[i]; + for (j = 0; j < row.length; j += 1) { + cell = row[j]; + if (cell.model.get("enableValidate") !== undefined) { + cell.enableValidation(); + this.columnsModel[j].enableValidate = true; + this.domTitleHeader[j].find(".pmdynaform-field-required").show(); + } + } + } + } + } + if (this.model.get("enableValidate") !== undefined) { + this.model.attributes.enableValidate = true; + if (this.model.get("group") === "form") { + this.$el.find(".pmdynaform-field-required").show(); + } + } + return this; + }, + /** + * Get Control HTML default + * @returns {Array} + */ + getControl: function () { + return this.model.getControl(); + }, + getLabelControl: function () { + + }, + getHref: function () { + return this.model.get("href"); + }, + setFocus: function () { + if (this.getControl().length) { + this.getControl().first().focus(); + } + }, + /* + This function change the values in the field formula associated, use with formulas + Render a new values in the field with formula + */ + onFieldAssociatedHandler: function () { + var i, + fieldsAssoc = this.formulaFieldsAssociated; + if (fieldsAssoc.length > 0) { + for (i = 0; i < fieldsAssoc.length; i += 1) { + if (fieldsAssoc[i].model.get("formulator") instanceof PMDynaform.core.Formula) { + this.model.addFormulaTokenAssociated(fieldsAssoc[i].model.get("formulator")); + this.model.updateFormulaValueAssociated(fieldsAssoc[i]); + } + } + } + return this; + }, + setData: function (data) { + var value, label; + if (this.model.get("type") !== "submit" && this.model.get("type") !== "button" && this.model.get("type") !== "panel") { + if (this.model.get("type") === "label") { + this.setValue(data); + } else { + value = data["value"]; + this.setValue(value); + } + } + return this; + }, + setOnFieldFocusCallback: function (callback) { + if (typeof callback === 'function' || callback === null) { + this.onFieldFocusCallback = callback; + } + return this; + }, + isDependent: function () { + return this.model.isDependent(); + }, + updateValueHiddenControl: function (value) { + var hidden; + hidden = this.$el.find("input[type='hidden']"); + if (value !== null && value !== undefined) { + if (hidden instanceof jQuery && hidden.length) { + hidden.val(value); + } + } + return this; + }, + /** + * Update the second hidden in the radio control + * @param {string} value + */ + updateValueRadioControl: function (value) { + var hidden; + hidden = this.$el.find("input[type='hidden']"); + if (value !== null && value !== undefined) { + if (hidden instanceof jQuery && hidden.length) { + hidden[1].value = value; + } + } + return this; + }, + show: function () { + if (this.el) { + this.el.style.display = ''; + } + this._hidden = false; + }, + hide: function () { + if (this.el) { + this.el.style.display = 'none'; + } + this._hidden = true; + }, + isHidden: function () { + return this._hidden; + }, + hideRequire: function () { + var tagRequired; + tagRequired = this.$el.find(".pmdynaform-field-required"); + tagRequired.hide(); + }, + showRequire: function () { + var tagRequired; + tagRequired = this.$el.find(".pmdynaform-field-required"); + tagRequired.show(); + }, + /** + * Default method clear File + */ + clearContent: function () { + }, + /** + * Gets the current language + * @returns {FieldView} + */ + initLanguage: function () { + var project = this.model.get('project'), + pmLang = project.getLanguage(); + this.language = moment.localeData(pmLang) ? pmLang : "en"; + moment.locale(this.language); + return this; + }, + /** + * Adds the spinner html component + * @chainable + */ + addSpinnerHTML: function () { + this.spinner = new PMDynaform.ui.Spinner(); + this.spinner.render(); + this.spinner.hide(); + if (this.model.get("parent") + && this.model.get("parent").get("type") === "grid") { + this.$el.find(".control-group").parent().append(this.spinner.$el); + } else { + this.$el.find(".pmdynaform-field-control").append(this.spinner.$el); + } + return this; + }, + /** + * Gets the is loading property of a field + * @returns {boolean} + */ + isLoading: function () { + return this.model.get("loading"); + }, + /** + * Shows spinner and hides the control + * @returns {DropdownModel} + */ + switchControlBySpinner: function () { + var control = this.getHTMLControl(); + if (this.spinner) { + control.hide(); + this.spinner.show(); + this.model.set({loading: true}); + } + return this; + }, + /** + * Show the spinner and hides the control + * @chainable + */ + switchSpinnerByControl: function () { + var control = this.getHTMLControl(); + if (this.spinner) { + this.spinner.hide(); + this.model.set({loading: false}); + } + if (control) { + control.show(); + } + return this; + }, + /** + * Shows the server fail message. + * @chainable + */ + showQueryFailMessage: function () { + var message = "There was an error when populating the values of field".translate(); + message = message + " " + this.model.get("label"); + message = 'Error: ' + message; + $.notify({ + // options + message: message + }, { + // settings + type: 'danger', + spacing: 10, + allow_dismiss: true, + delay: 6000, + timer: 1000, + placement: { + from: "top", + align: "center" + }, + animate: { + enter: 'animated fadeInDown', + exit: 'animated fadeOutUp' + } + }); + return this; + }, + /** + * Run all dependencies of a field. + */ + runDependency: function () { + var parent = this.parent, + data = {}, + i, + item, + dependency = []; + if (_.isArray(this.model.get("dependency")) && this.model.get("dependency").length) { + dependency = this.model.get("dependency"); + if (parent) { + for (i = 0; i < dependency.length; i += 1) { + if (parent.model.get("type") === "grid") { + this.switchControlBySpinner(); + item = parent.model.findCellInRow(this.model.get("row"), dependency[i]); + data[dependency[i]] = item.get("value") ? item.get("value") : ""; + } + this.model.recoveryRemoteOptions(data, true); + } + + } + } + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Field", FieldView); +}()); + +(function () { + var GridView = PMDynaform.view.Field.extend({ + block: true, + template: _.template($("#tpl-grid").html()), + templatePager: _.template($("#tpl-grid-pagination").html()), + templateTotal: _.template($("#tpl-grid-totalcolumn").html()), + templateEmptyGrid: _.template($("#tpl-grid-empty").html()), + colSpanLabel: 3, + colSpanControl: 9, + gridtable: [], + flagRow: 0, + dom: [], + row: [], + cols: [], + showPage: 1, + items: [], + numberRest: 0, + rest: 0, + priority: { + file: 1, + image: 2, + radio: 3, + checkbox: 4, + textarea: 5, + datetime: 6, + dropdown: 7, + text: 8, + button: 9, + link: 10, + defect: 0 + }, + section: 1, + titleHeader: [], + indexResponsive: "3%", + removeResponsive: "3%", + thereArePriority: 0, + columnsModel: [], + domCarousel: null, + tableBody: null, + pageSize: null, + paged: null, + rowDataAdd: null, + domTitleHeader: null, + totalWidtRow: 0, + colResponsiveTotalWidth: null, + hiddenColumns: [], + totalWidthStatic: 0, + minCellWidth: 200, + indexWidthStatic: 33, + _$gridHeader: null, + _gridHeader: null, + deleteButtonVisibility: true, + onDeleteRowCallback: function () { + }, + onAddRowCallback: function () { + }, + onBeforeAddRowCallback: function () { + }, + onClickPageCallback: function () { + }, + events: { + "click .pmdynaform-grid-newitem": "onClickNew", + "click .pagination li": "onClickPage" + }, + requireVariableByField: [ + "text", + "textarea", + "checkbox", + "radio", + "dropdown", + "datetime", + "suggest", + "link", + "hidden", + "label" + ], + factory: {}, + initialize: function (options) { + var factory = { + products: { + "text": { + model: PMDynaform.model.TextR, + view: PMDynaform.view.TextR + }, + "textarea": { + model: PMDynaform.model.TextAreaR, + view: PMDynaform.view.TextAreaR + }, + "checkbox": { + model: PMDynaform.model.CheckBox, + view: PMDynaform.view.CheckBox + }, + "radio": { + model: PMDynaform.model.Radio, + view: PMDynaform.view.Radio + }, + "dropdown": { + model: PMDynaform.model.DropdownR, + view: PMDynaform.view.DropdownR + }, + "button": { + model: PMDynaform.model.Button, + view: PMDynaform.view.Button + }, + "datetime": { + model: PMDynaform.model.DatetimeR, + view: PMDynaform.view.DatetimeR + }, + "suggest": { + model: PMDynaform.model.SuggestR, + view: PMDynaform.view.SuggestR + }, + "link": { + model: PMDynaform.model.Link, + view: PMDynaform.view.Link + }, + "file": { + model: PMDynaform.model.File, + view: PMDynaform.view.File + }, + "multiplefile": { + model: PMDynaform.file.MultipleFileModel, + view: PMDynaform.file.MultipleFileView + }, + "label": { + model: PMDynaform.model.Label, + view: PMDynaform.view.Label + }, + "hidden": { + model: PMDynaform.model.Hidden, + view: PMDynaform.view.Hidden + } + }, + defaultProduct: "text" + }, + k, + rows = parseInt(this.model.get("rows"), 10); + this.form = options.form ? options.form : null; + this.pageSize = this.model.get("pageSize"); + this.paged = this.model.get("pager"); + this.colResponsiveTotalWidth = 0; + this.items = []; + this.row = []; + this.dom = []; + this.cols = []; + this.showPage = 1; + this.gridtable = this.model.get("gridtable"); + this.titleHeader = []; + this.columnsModel = []; + this.checkColSpanResponsive(); + this.setFactory(factory); + this.rowDataAdd = []; + this.dom = []; + this.makeColumnModels(); + this.hiddenColumns = []; + this.model.attributes.titleHeader = this.titleHeader; + + }, + onClickNew: function (e) { + this.addRow(e); + return this; + }, + addRow: function (data, isHelper) { + var j, + row, + rowData, + currentRows, + flagRow; + currentRows = this.model.get("rows"); + this.rowDataAdd = []; + if (this.model.get("layout") === "static") { + flagRow = this.tableBody.find(".pmdynaform-static").last().children().length; + this.domCarousel = this.tableBody.find(".pmdynaform-static").last(); + } else { + flagRow = this.tableBody.children().last().children().length; + this.domCarousel = this.tableBody.children().last(); + } + if (flagRow === this.pageSize || flagRow === 0) { + this.block = true; + this.section = Math.ceil(this.dom.length / this.pageSize) + 1; + flagRow = 0; + } else { + this.block = false; + this.section = Math.ceil(this.dom.length / this.pageSize); + } + this.onBeforeAddRowCallback(this, this.model.attributes.rows, this.rowDataAdd); + if (data && jQuery.isArray(data) && data.length) { + this.rowDataAdd = data; + } + row = this.createHTMLRow(currentRows, this.rowDataAdd, [], flagRow, isHelper); + this.model.attributes.rows = parseInt(currentRows + 1, 10); + + //new carousel container fix a in active mode + if (this.model.get("rows") === 1) { + this.domCarousel.addClass('active'); + } + this.model.setPaginationItems(); + this.createHTMLPager("add"); + + this.model.attributes.gridFunctions.push(row.data); + + this.runningRowFormulator(row.view); + + for (j = 0; j < row.model.length; j += 1) { + if (row.model[j].get("type") !== "label" && row.model[j].get("operation") && row.model[j].get("operation").trim().length) { + row.view[j].onChangeCallbackOperation(); + } + if (row.model[j].get("type") == "label" && row.model[j].get("operation")) { + this.createHTMLTotal(); + } + } + if (typeof this.onAddRowCallback === "function") { + this.onAddRowCallback(this.gridtable[currentRows], this, this.gridtable.length); + } + this.validateGrid(); + return this.gridtable[currentRows]; + }, + runningRowFormulator: function (row) { + var fieldsAsocied; + for (var i = 0; i < row.length; i += 1) { + if (row[i].model.get("formula") && row[i].model.get("formula").trim().length) { + fieldsAsocied = row.filter(function (element) { + if (row[i].fieldValid.indexOf(element.model.get("id")) > -1) { + element.onFieldAssociatedHandler(); + } + }); + } + } + }, + removeRow: function (row) { + var currentRows = this.model.get("rows"), + itemRemoved; + + itemRemoved = this.gridtable.splice(row, 1); + this.model.detachRegisteredEvents(itemRemoved); + this.dom.splice(row, 1); + this.model.attributes.rows = parseInt(currentRows - 1, 10); + this.deleteFilesByRow(itemRemoved[0]); + return itemRemoved; + }, + makeColumnModels: function () { + var columns = this.model.get("columns"), + data = this.model.get("data"), + columnModel, + colSpanControl, + factory = this.factory, + product, + newNameField, + variableEnabled, + jsonFixed, + mergeModel, + i; + this.columnsModel = []; + for (i = 0; i < columns.length; i += 1) { + newNameField = ""; + mergeModel = columns[i]; + mergeModel.form = this.model.get("form") || null; + if (mergeModel.mode && mergeModel.mode === "parent") { + mergeModel.mode = this.model.get("mode"); + } + if ((mergeModel.originalType === "checkbox" || mergeModel.type === "checkbox") && mergeModel.mode === "view") { + mergeModel.mode = "disabled"; + mergeModel.disabled = true; + } + if ((mergeModel.originalType === "checkbox" || mergeModel.type === "checkbox") && mergeModel.mode === "disabled") { + mergeModel.mode = "disabled"; + mergeModel.disabled = true; + } + jsonFixed = new PMDynaform.core.TransformJSON({ + parentMode: this.model.get("parentMode"), + field: mergeModel + }); + if (jsonFixed.getJSON().type) { + product = factory.products[jsonFixed.getJSON().type.toLowerCase()] ? + factory.products[jsonFixed.getJSON().type.toLowerCase()] : factory.products[factory.defaultProduct]; + } else { + product = factory.products[factory.defaultProduct]; + } + colSpanControl = this.colSpanControlField(jsonFixed.getJSON().type, i); + columnModel = { + colSpanLabel: 4, + colSpanControl: (this.model.get("layout") === "form") ? 8 : colSpanControl, + colSpan: colSpanControl, + label: mergeModel.title, + title: mergeModel.title, + layout: this.model.get("layout"), + width: "200px", + project: this.model.get("project"), + namespace: this.model.get("namespace"), + mode: mergeModel.mode, + variable: (variableEnabled !== "NOT") ? this.getVariable(mergeModel.var_uid) : null, + _extended: { + name: mergeModel.name || PMDynaform.core.Utils.generateName("radio"), + id: mergeModel.id || PMDynaform.core.Utils.generateID(), + formula: mergeModel.formula || null + }, + group: "grid", + columnName: mergeModel.name || PMDynaform.core.Utils.generateName("radio"), + columnId: mergeModel.id, + originalType: mergeModel.type, + product: product, + formula: mergeModel.formula || "", + operation: mergeModel.operation || "", + columnWidth: mergeModel.columnWidth || "", + defaultValue: mergeModel.defaultValue || "", + sql: mergeModel.sql || "", + datasource: mergeModel.datasource || "", + required: mergeModel.required || false, + hint: mergeModel.hint || "", + format: mergeModel.format || null, + form: mergeModel.form || null, + options: mergeModel.options || [], + optionsSql: mergeModel.optionsSql || [], + defaultDate: mergeModel.defaultDate || null, + enableValidate: true, + parent: this.model + }; + jQuery.extend(true, columnModel, jsonFixed.getJSON()); + columnModel.row = this.gridtable.length; + columnModel.col = i; + if (this.model.get("layout") == "static") { + if (columnModel.columnWidth && jQuery.isNumeric(columnModel.columnWidth)) { + var width = parseInt(columnModel.columnWidth); + this.totalWidtRow = this.totalWidtRow + width; + } else { + this.totalWidtRow = this.totalWidtRow + 200; + } + } + this.columnsModel.push(columnModel); + } + if (this.model.get("layout") == "responsive") { + this.updateWidthResponsiveColumns(); + } + + return this; + }, + updateWidthResponsiveColumns: function () { + var i, totalWith = 0, width, undefinedWidth = []; + if (this.columnsModel.length) { + for (i = 0; i < this.columnsModel.length; i += 1) { + width = parseInt(this.columnsModel[i].columnWidth).toString(); + if (width !== "NaN") { + if (totalWith + Number(width) < 94) { + totalWith = totalWith + Number(width); + this.columnsModel[i].columnWidth = Number(width) + "%"; + } else { + if (94 - totalWith > 0) { + this.columnsModel[i].columnWidth = 94 - totalWith + "%"; + totalWith = totalWith + 94 - totalWith; + } else { + this.columnsModel[i].columnWidth = 0 + "%"; + undefinedWidth.push(this.columnsModel[i]); + } + } + } else { + this.columnsModel[i].columnWidth = 0 + "%"; + undefinedWidth.push(this.columnsModel[i]); + } + } + } + return this; + }, + setValuesGridFunctions: function (field) { + + if (this.model.attributes.functions) { + if (this.model.attributes.gridFunctions.length > 0) { + if (this.model.attributes.gridFunctions[field.row]) { + this.model.attributes.gridFunctions[field.row][field.col] = isNaN(parseFloat(field.data)) ? 0 : parseFloat(field.data); + } + this.model.applyFunction(); + } + } + return this; + }, + getVariable: function (var_uid) { + var i, + varSelected, + variables = this.model.get("variables"); + loop_variables: + if (_.isArray(variables)) { + for (i = 0; i < variables.length; i += 1) { + if (variables[i] && variables[i].var_uid === var_uid) { + varSelected = variables[i]; + break loop_variables; + } + } + } + return varSelected; + }, + checkColSpanResponsive: function () { + var i, + columns = this.model.get("columns"), + thereArePriority = 0, + layout = this.model.get("layout"); + + if (layout === "responsive" || layout === "form") { + this.numberRest = 10 % columns.length; + + if (this.numberRest > 0) { + for (i = 0; i < columns.length; i += 1) { + if (this.priority[columns[i].type] <= 6) { + thereArePriority += 1; + } + } + } + this.thereArePriority = thereArePriority; + } + return this; + }, + colSpanControlField: function (type, indexColumn) { + var itemsLength = this.model.get("columns").length, + layout = this.model.get("layout"), + defaultColSpan = 8; + if (this.numberRest > 0) { + if (this.priority[type] <= 6 && this.thereArePriority > 0) { + defaultColSpan = parseInt(10 / itemsLength) + 1; + this.numberRest -= 1; + this.thereArePriority -= 1; + } else { + if (this.numberRest >= parseInt(itemsLength - indexColumn)) { + defaultColSpan = parseInt(10 / itemsLength) + 1; + this.numberRest -= 1; + } else { + defaultColSpan = parseInt(10 / itemsLength); + } + } + } else { + defaultColSpan = parseInt(10 / itemsLength); + } + + return defaultColSpan; + }, + colSpanControlFieldResponsive: function () { + var columnWidth = 100, res; + res = parseInt(this.indexResponsive) + parseInt(this.removeResponsive); + columnWidth = parseInt((columnWidth - res) / (this.columnsModel.length - this.model.get("countHiddenControl"))); + return columnWidth - 1; + }, + /* + form[grid1][1][nombre] + form[grid1][2][nombre] + */ + changeIdField: function (nameform, row, column) { + return "[" + nameform + "][" + row + "][" + column + "]"; + }, + changeNameField: function (nameform, row, column) { + return "[" + nameform + "][" + row + "][" + column + "]"; + }, + updateNameFields: function (rowView) { + var i, + l, + formulaFields = ""; + for (i = 0; i < rowView.length; i += 1) { + formulaFields = rowView[i].model.get("_extended").formula; + if (typeof formulaFields === "string") { + for (l = 0; l < rowView.length; l += 1) { + if (i !== l) { + formulaFields = formulaFields.replace(new RegExp(rowView[l].model.get("_extended").id, 'g'), rowView[l].model.get("id")); + rowView[i].model.attributes.formula = formulaFields; + rowView[i].model.attributes.formulator.data = formulaFields; + } + } + } + } + return this; + }, + setFactory: function (factory) { + this.factory = factory; + return this; + }, + validate: function (event) { + var i, + k, + row = [], + validGrid = true, + gridpanel = this.gridtable, + itemCell; + if (!this.validateGrid()) { + return this; + } + for (i = 0; i < gridpanel.length; i += 1) { + row = []; + for (k = 0; k < gridpanel[i].length; k += 1) { + if (gridpanel[i][k].validate) { + if (event) { + gridpanel[i][k].validate(event); + if (!gridpanel[i][k].model.get("valid")) { + if (itemCell === undefined) { + itemCell = gridpanel[i][k]; + } + validGrid = gridpanel[i][k].model.get("valid"); + this.model.set("valid", validGrid); + validGrid = false; + } + } else { + gridpanel[i][k].validate(); + validGrid = gridpanel[i][k].model.get("valid"); + if (!validGrid) { + gridpanel[i][k].setFocus(); + this.model.attributes.valid = false; + } + } + } + } + } + if (itemCell) { + itemCell.setFocus(); + } + this.model.set("valid", validGrid); + return validGrid; + }, + onRemoveRow: function (event) { + var rowNumber; + if (event) { + rowNumber = $(event.target).data("row"); + this.deleteRow(rowNumber, event); + } + + return this; + }, + updateGridFunctions: function (rows, index) { + this.model.attributes.gridFunctions.splice(index - 1, 1); + this.model.applyFunction(); + this.createHTMLTotal(); + return this; + }, + deleteRow: function (index, event) { + var itemRemoved, + showPage, + removedSection, + initPage, + i; + showPage = Math.ceil(index / this.pageSize); + jQuery(this.dom[index - 1]).remove(); + if (index > 0) { + itemRemoved = this.removeRow(index - 1); + } else { + return this; + } + this.updateGridFunctions(itemRemoved, index); + this.updatePropertiesCell(index - 1); + if (this.model.attributes.pager) { + this.block = true; + this.flagRow = 0; + this.section = 0; + if (this.model.get("layout") === "static") { + for (var i = showPage; i < this.tableBody.find(".pmdynaform-static").length; i += 1) { + if (this.tableBody.find(".pmdynaform-static").eq(i).children().length) { + this.tableBody.find(".pmdynaform-static").eq(i - 1).append(this.tableBody.find(".pmdynaform-static").eq(i).children()[0]) + } + } + if (this.tableBody.find(".pmdynaform-static").eq(i - 1).children().length === 0) { + removedSection = this.tableBody.find(".pmdynaform-static").eq(i - 1).remove(); + if (i == 1) { + initPage = true; + } + } + if (!this.tableBody.find(".pmdynaform-static").eq(showPage - 1).children().length) { + if (this.tableBody.find(".pmdynaform-static").eq(showPage - 2).length) { + this.tableBody.find(".pmdynaform-static").eq(showPage - 2).addClass("active"); + } + } + } else { + for (i = showPage; i < this.tableBody.children().length; i += 1) { + if (this.tableBody.children().eq(i).children().length) { + this.tableBody.children().eq(i - 1).append(this.tableBody.children().eq(i).children()[0]) + } + } + if (this.tableBody.children().eq(i - 1).children().length === 0) { + removedSection = this.tableBody.children().eq(i - 1).remove(); + } + if (!this.tableBody.children().eq(showPage - 1).children().length) { + if (this.tableBody.children().eq(showPage - 2).length) { + this.tableBody.children().eq(showPage - 2).addClass("active"); + } + } + } + this.model.setPaginationItems(); + this.createHTMLPager("remove"); + if (removedSection && removedSection.length) { + this.showPage = showPage - 1; + if (initPage) { + this.showPage = 1; + } + } else { + this.showPage = showPage; + } + } + if (typeof this.onDeleteRowCallback === "function") { + this.onDeleteRowCallback(this, itemRemoved, index); + } + this.validateGrid(); + return this; + }, + /** + * Update Properties Model Cell. + * @param cell + * @param i + * @param j + */ + updateModelCell: function (cell, i, j) { + var index = i + 1, + name = "[" + this.model.get('name') + "][" + index + "][" + cell.model.get('columnName') + "]"; + + cell.model.set('name', name); + cell.model.set('id', name); + cell.model.set('nameToPostControl', this.createPostVariables(index, cell.model.get('columnName'))); + cell.model.set('nameToPostLabelControl', this.createPostVariables(index, cell.model.get('columnName'), '_label')); + if (cell.model.get('view').removeHiddens) { + cell.model.get('view').removeHiddens(); + } + }, + updatePropertiesCell: function (index) { + var i, + j, + k, + cell, + cells, + row, + rows, + element, + control, + container, + idContainer, + hiddenControls, + type, + nameHiddeControl = "", + nameControl = "", + idcontrol, + formulaExist = false; + rows = this.gridtable; + for (i = index; i < rows.length; i += 1) { + row = $(this.dom[i]); + row.find(".index-row span").text(i + 1); + row.find(".remove-row div").data("row", i + 1); + cells = rows[i]; + if (cells) { + for (j = 0; j < cells.length; j += 1) { + cell = cells[j]; + cell.model.attributes.row = i; + idContainer = this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + element = cell.$el; + container = element.find(".pmdynaform-" + cell.model.get("mode") + "-" + cell.model.get("type")); + container.attr({ + "id": idContainer + }); + type = cell.model.get("type"); + switch (type) { + case "checkbox": + control = $(cell.$el.find("input[type='checkbox']")); + hiddenControls = element.find("input[type='hidden']"); + if (this.model.get("variable") !== "") { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameControl.substring(0, nameControl.length - 1).concat("_label]"); + } + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + control.attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.attr({ + name: nameHiddeControl, + id: idcontrol + }); + this.updateModelCell(cell, i, j); + break; + case "suggest": + control = $(cell.$el.find(".form-control")); + hiddenControls = element.find("input[type='hidden']"); + if (this.model.get("variable")) { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameHiddeControl.substring(0, nameHiddeControl.length - 1).concat("_label]"); + } else { + nameControl = ""; + nameHiddeControl = "" + } + $(cell.getIdSelect()).select2('destroy'); + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + control.attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.attr({ + name: nameHiddeControl, + id: nameHiddeControl + }); + $(cell.getIdSelect()).select2(cell.initializeSelect2Query()); + this.updateModelCell(cell, i, j); + break; + case "label": + hiddenControls = element.find("input[type='hidden']"); + if (this.model.get("variable") !== "") { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameControl.substring(0, nameControl.length - 1).concat("_label]"); + } else { + nameControl = ""; + nameHiddeControl = ""; + } + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + hiddenControls.eq(0).attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.eq(1).attr({ + name: nameHiddeControl, + id: idcontrol + }); + this.updateModelCell(cell, i, j); + break; + case "file": + this.updateFileCell(cell, i, j); + // TODO need refactor + break; + case "multipleFile": + this.updateMultipleFileCell(cell, i, j); + break; + case "text": + // TODO need refactor Formula.js or update formulator with the index correct after update the model. PMC-762 + control = $(cell.$el.find(".form-control")); + hiddenControls = element.find("input[type='hidden']"); + if (this.model.get("variable") !== "") { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameControl.substring(0, nameControl.length - 1).concat("_label]"); + } else { + nameControl = ""; + nameHiddeControl = ""; + } + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + control.attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.attr({ + name: nameHiddeControl, + id: idcontrol + }); + for (k = 0; k < cells.length; k += 1) { + if (cells[k].model.get("formula")) { + formulaExist = true; + } + } + if (!formulaExist) { + this.updateModelCell(cell, i, j); + } + break; + default: + control = $(cell.$el.find(".form-control")); + hiddenControls = element.find("input[type='hidden']"); + if (this.model.get("variable") !== "") { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameControl.substring(0, nameControl.length - 1).concat("_label]"); + } else { + nameControl = ""; + nameHiddeControl = ""; + } + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + control.attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.attr({ + name: nameHiddeControl, + id: idcontrol + }); + this.updateModelCell(cell, i, j); + break; + } + } + } + } + return this; + }, + /** + * force to update the hidden tags to send that by POST method to server + * @param cell + * @param i + * @param j + */ + updateMultipleFileCell: function (cell, i, j) { + var files, + k; + + this.updateModelCell(cell, i, j); + files = cell.model.get("fileCollection"); + cell.model.get('view').removeHiddens(); + if (_.isArray(files.models)) { + for (k = 0; k < files.models.length; k += 1) { + cell.model.get('view').createHiddenByModel(files.models[k]); + } + } + + }, + /** + * Updates File cell when a row has been removed + * + * @param cell + */ + updateFileCell: function (cell, i, j) { + var element = cell.$el, + control = $(cell.$el.find(".form-control")), + hiddenControls = element.find("input[type='hidden']"), + fileControls = element.find("input[type='file']"), + nameControl, + nameHiddeControl, + idcontrol; + + if (this.model.get("variable") !== "") { + nameControl = "form" + this.changeIdField(this.model.get("name"), i + 1, cell.model.get("columnName")); + nameHiddeControl = nameControl.substring(0, nameControl.length - 1).concat("_label]"); + + } else { + nameControl = ""; + nameHiddeControl = ""; + } + idcontrol = "form" + this.changeIdField(this.model.get("id"), i + 1, this.columnsModel[j].id); + control.attr({ + name: nameControl, + id: idcontrol + }); + hiddenControls.attr({ + name: nameHiddeControl, + id: idcontrol + }); + + fileControls.attr({ + name: nameControl, + id: idcontrol + }); + this.updateModelCell(cell, i, j); + }, + + onClickPage: function (event) { + var objData = $(event.currentTarget.children).data(), + parentNode = $(event.currentTarget).parent(), + i, + index, + nextItemElement, + nextItem, + prevItem; + + /************************** pagination rotate ************************************/ + nextItem = $('
  • ...
  • '); + prevItem = $('
  • ...
  • '); + + if (!$.isNumeric($(event.currentTarget).find("a").text())) { + var $currentItem = parentNode.find('li.active'); + if ($(event.currentTarget).hasClass("toNextItem")) { + if ($currentItem.hasClass("toNext")) { + this.onClickNextSection($currentItem, parentNode, nextItem, prevItem); + } else { + if ($currentItem.next().attr("class") !== "toNextItem") { + parentNode.find('li').removeClass('active'); + $currentItem.next().addClass("active"); + $currentItem.next().find("a:eq(0)").trigger("click"); + } + } + } + if ($(event.currentTarget).hasClass("toPrevItem")) { + if ($currentItem.hasClass("toPrev")) { + this.onClickPrevSection($currentItem, parentNode, nextItem, prevItem); + } else { + if ($currentItem.prev().attr("class") !== "toPrevItem") { + parentNode.find('li').removeClass('active'); + $currentItem.prev().addClass("active"); + $currentItem.prev().find("a:eq(0)").trigger("click"); + } + } + } + if ($(event.currentTarget).hasClass("toLast")) { + var lastPosition = parseInt(parentNode.children().length) - 3; + if (!this.model.get("paginationRotate")) { + this.tableBody.find(".active").removeClass("active"); + var e = parentNode.find('li:eq(' + lastPosition + ')'); + if (parentNode.find("li.active a").text() != Math.ceil(this.gridtable.length / this.pageSize)) { + this.onClickNextSection(e, parentNode, nextItem, prevItem); + } + this.tableBody.children().last().addClass("active") + } + parentNode.find('.active').removeClass('active'); + lastPosition = parseInt(parentNode.children().length) - 3; + parentNode.find('li:eq(' + lastPosition + ')').addClass("active"); + return false; + } + if ($(event.currentTarget).hasClass("toFirst")) { + if (!this.model.get("paginationRotate")) { + var e = parentNode.find('li:eq(3)'); + if (parentNode.find("li.active a").text() !== "1") { + this.onClickPrevSection(e, parentNode, nextItem, prevItem); + } + } + parentNode.find('li').removeClass('active'); + parentNode.find('li:eq(2)').addClass("active"); + } + if ($(event.currentTarget).hasClass("toNext")) { + index = Number($(event.currentTarget).prev().text().trim()); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').removeClass("showItem"); + $(parentNode).find('.toPrev').remove(); + $(parentNode).find('.toNext').remove(); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').css({ + display: "none" + }); + if (((this.gridtable.length / this.pageSize) - index) > 5) { + for (i = index; i < index + 5; i += 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).before(nextItem); + } else { + for (i = index; i < (this.gridtable.length / this.pageSize); i += 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(index - 1).after(prevItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } + if ($(event.currentTarget).hasClass("toPrev")) { + index = Number($(event.currentTarget).prev().text().trim()); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').removeClass("showItem"); + $(parentNode).find('.toPrev').remove(); + $(parentNode).find('.toNext').remove(); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').css({ + display: "none" + }); + + if (index - 5 != 0) { + if (index - 5 > -1) { + for (i = index - 1; i >= index - 5; i -= 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + nextItemElement.after(nextItem); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).after(prevItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } else { + + for (i = 5 - 1; i >= 0; i -= 1) { + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + if ($(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(index - 1).length) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(index - 1); + } + $(parentNode).find(".showItem").last().after(prevItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } + } else { + for (i = index - 1; i > -1; i -= 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + nextItemElement.after(nextItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } + } + } else { + parentNode.children().removeClass('active'); + $(event.currentTarget).addClass("active"); + } + return this; + }, + onClickNextSection: function (currentTarget, parentNode, nextItem, prevItem) { + if ($(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').length - 1 > 5) { + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').removeClass("showItem"); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').css("display", "none"); + $(parentNode).find('.toPrev').remove(); + $(parentNode).find('.toNext').remove(); + var i, nextItemElement, length = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').length - 1; + for (i = length; i > length - 5; i -= 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).after(prevItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } + }, + onClickPrevSection: function (currentTarget, parentNode, nextItem, prevItem) { + if ($(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').length - 1 > 5) { + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').removeClass("showItem"); + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').css("display", "none"); + $(parentNode).find('.toPrev').remove(); + $(parentNode).find('.toNext').remove(); + var i, nextItemElement; + for (i = 0; i < 5; i += 1) { + if (!nextItemElement) { + nextItemElement = $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).css({ + display: "" + }).addClass("showItem"); + } + $(parentNode).children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(i).before(nextItem); + if (nextItemElement) { + nextItemElement.find("a").trigger("click"); + } + } + }, + + refreshButtonsGrid: function () { + var i, + tdNumber, + buttonRemove, + trs = this.dom, + element; + + for (i = 0; i < trs.length; i += 1) { + element = $(trs[i]).html(); + tdNumber = this.createRowNumber(i + 1); + buttonRemove = this.createRemoveButton(i); + $(trs[i].firstChild).replaceWith(tdNumber); + $(trs[i].lastChild).replaceWith(buttonRemove); + } + + return this; + }, + createRowNumber: function (index) { + var tdNumber = document.createElement("div"), + formgroup = document.createElement("div"), + divNumber = document.createElement("div"), + spanNumber = document.createElement("span"), + label = document.createElement("label"), + labelSpan = document.createElement("span"), + containerField = document.createElement("div"), + layout = this.model.get("layout"), + tdRemove; + if (layout === "form") { + tdNumber.className = "col-xs-12 col-sm-1 col-md-1 col-lg-1" + } + if (layout === "static") { + tdNumber.className = "pmdynaform-grid-field-static index"; + tdNumber.style.width = "33px"; + } + if (layout === "responsive") { + tdNumber.width = this.indexResponsive; + tdNumber.style.display = "inline-block"; + } + label.className = "hidden-lg hidden-md hidden-sm visible-xs control-label col-xs-4"; + labelSpan.innerHTML = "Nro"; + label.appendChild(labelSpan); + + divNumber.className = "col-xs-4 col-sm-12 col-md-12 col-lg-12 pmdynaform-grid-label rowIndex"; + spanNumber.innerHTML = index; + divNumber.appendChild(spanNumber); + if (layout === "form") { + containerField.appendChild(label); + + tdRemove = this.createRemoveButton(index - 1); + tdRemove.className = "col-xs-1 visible-xs hidden-sm hidden-md hidden-lg remove-row-form"; + tdRemove.style.cssText = "float: right; margin-right: 15%; padding: 5px"; + containerField.appendChild(tdRemove); + } + containerField.appendChild(divNumber); + formgroup.className = "row form-group"; + formgroup.appendChild(containerField); + tdNumber.appendChild(formgroup); + $(tdNumber).addClass("index-row"); + return tdNumber; + }, + createRemoveButton: function (index) { + var that = this, + tdRemove, + buttonRemove, + layout = this.model.get("layout"); + tdRemove = document.createElement("div"); + if (layout === "form") { + tdRemove.className = "pmdynaform-grid-removerow hidden-xs col-xs-1 col-sm-1 col-md-1 col-lg-1"; + } + if (layout === "static") { + tdRemove.className = "pmdynaform-grid-removerow-static"; + } + if (layout === "responsive") { + tdRemove.className = "pmdynaform-grid-removerow-responsive"; + tdRemove.style.display = "inline-block"; + } + buttonRemove = document.createElement("div"); + + buttonRemove.className = "glyphicon glyphicon-trash btn btn-danger btn-sm"; + buttonRemove.setAttribute("data-row", index); + buttonRemove.setAttribute("aria-label", this.model.get("removeAriaLabel") + " #" + index); + + $(buttonRemove).data("row", index); + $(buttonRemove).on("click", function (event) { + that.onRemoveRow(event); + }); + + tdRemove.appendChild(buttonRemove); + return tdRemove; + }, + createHTMLTitle: function () { + + var k, + dom, + title, + td, + colSpan, + label, + layout = this.model.get("layout"), + content, + hint, + spaceDelete; + this.domTitleHeader = []; + + dom = this.$el.find(".pmdynaform-grid-thead"); + td = document.createElement("div"); + content = document.createElement("div"); + label = document.createElement("span"); + + if (layout === "static") { + dom.addClass("pmdynaform-grid-thead-static"); + td.className = "pmdynaform-grid-field-static wildcard"; + td.style.minWidth = "33px"; + } + if (layout === "form") { + td.className = "col-xs-1 col-sm-1 col-md-1 col-lg-1 text-center wildcard"; + } + + if (layout === "responsive") { + //For the case: responsive and form + td.className = "text-center wildcard"; + td.style.display = "inline-block"; + td.style.width = this.indexResponsive; + } + td.appendChild(label); + dom.append(td); + for (k = 0; k < this.columnsModel.length; k += 1) { + if (this.columnsModel[k].type !== "hidden") { + colSpan = this.columnsModel[k].colSpan; + title = this.columnsModel[k].title; + td = document.createElement("div"); + label = document.createElement("span"); + label.className = "title-column"; + this.checkColSpanResponsive(); + + if (layout !== "responsive") { + colSpan = this.colSpanControlField(this.columnsModel, this.columnsModel[k].type, k); + td = this._createHtmlCell(this.columnsModel[k].type, colSpan, k); + } + label.innerHTML = title; + label.style.fontWeight = "bold"; + label.style.maginLeft = "2px"; + $(label).css({ + "text-overflow": "ellipsis", + "white-space": "nowrap", + "overflow": "hidden", + "display": "inline-block", + "width": "80%", + "text-align": "center" + }); + if (layout === "responsive") { + $(label).css({ + width: "70%", + display: "inline-block" + }); + $(td).css({ + width: this.colSpanControlFieldResponsive(this.columnsModel) + "%", + display: "inline-block" + }); + } + if (layout === "static") { + if (this.columnsModel[k]["columnWidth"] && Number(this.columnsModel[k]["columnWidth"]).toString() !== "NaN") { + $(td).css({ + "min-width": parseInt(this.columnsModel[k]["columnWidth"]) + }); + $(label).css({ + "width": parseInt(this.columnsModel[k]["columnWidth"]) - 40 + }); + } else { + $(td).css({ + "min-width": "200px" + }); + $(label).css({ + "width": "160px" + }); + } + } + if (layout === "responsive") { + $(td).css({ + "width": this.columnsModel[k].columnWidth + }); + } + label.title = title; + + td.appendChild(label); + if (this.columnsModel[k].required) { + if (parseInt(this.columnsModel[k].columnWidth) === 0) { + td.appendChild($("*")[0]); + label.style.display = "none"; + } else { + td.appendChild($("*")[0]); + } + } + + hint = document.createElement("span"); + if (this.columnsModel[k].hint && this.columnsModel[k].hint.trim().length) { + hint = document.createElement("span"); + hint.className = "glyphicon glyphicon-info-sign"; + hint.setAttribute("data-toggle", "tooltip"); + hint.setAttribute("data-container", "body"); + hint.setAttribute("data-placement", "bottom"); + hint.setAttribute("data-original-title", this.columnsModel[k]["hint"]); + hint.style.float = "inherit"; + $(hint).tooltip().click(function (e) { + $(this).tooltip('toggle'); + }); + if (layout === "responsive" || layout === "static" || layout === "form") { + td.appendChild(hint); + } else { + label.setAttribute("data-toggle", "tooltip"); + label.setAttribute("data-container", "body"); + label.setAttribute("data-placement", "bottom"); + label.setAttribute("data-original-title", this.columnsModel[k]["hint"]); + } + } + dom.append(td); + this.domTitleHeader.push($(td)); + } else { + this.domTitleHeader.push($("")); + } + } + if (layout === "static") { + spaceDelete = document.createElement("div"); + spaceDelete.className = "pmdynaform-grid-removerow-static"; + $(spaceDelete).css({ + "min-width": 38 + }); + dom.append(spaceDelete); + } + return this; + }, + createHTMLPager: function (behavior) { + var htmlPager, + pagerContainer, + activeIndex, + pager, + pagerItems, + elementList, + ellipsis; + pagerContainer = this.$el.find(".pmdynaform-grid-pagination"); + activeIndex = this.$el.find(".pagination").find("li.active"); + if (activeIndex.length) { + htmlPager = pagerContainer.children(); + pagerItems = htmlPager.children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').not('.toPrev').not('.toNext'); + if (behavior === "add") { + if (Math.ceil(this.gridtable.length / this.pageSize) > pagerItems.length) { + $(".sec_1").removeClass("showItem"); + $(".sec_1").addClass("showItem"); + elementList = jQuery("
  • " + Math.ceil(this.gridtable.length / this.pageSize) + "
  • "); + elementList.css({ display: "none" }); + if (htmlPager.find(".toNext").length === 0 && (Number(elementList.text().trim()) > 5)) { + ellipsis = jQuery('
  • ...
  • '); + htmlPager.find(".showItem").last().after(ellipsis); + ellipsis.after(elementList); + } else { + if (htmlPager.find(".toNext").length) { + htmlPager.find(".toNextItem").before(elementList); + } else { + elementList.css({ + display: "" + }).addClass("showItem"); + htmlPager.find(".showItem").last().after(elementList); + } + } + } + } + if (behavior === "remove") { + var itemRemoved; + if (Math.ceil(this.gridtable.length / this.pageSize) > 0 && Math.ceil(this.gridtable.length / this.pageSize) < pagerItems.length) { + if (pagerItems.eq(pagerItems.length - 1).hasClass("active")) { + pagerItems.eq(pagerItems.length - 1).prev().addClass("active"); + } + itemRemoved = pagerItems.eq(pagerItems.length - 1).remove(); + if (htmlPager.find(".active").hasClass("toPrev")) { + htmlPager.find(".active").trigger("click"); + htmlPager.find(".toNext").remove(); + } + if (htmlPager.find(".active").text().trim() == 5) { + htmlPager.find(".toPrev").remove(); + htmlPager.children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').css({ + display: "" + }); + } + if (Number(htmlPager.find(".showItem").last().text().trim()) <= (this.gridtable.length / 5)) { + htmlPager.find(".toNext").remove(); + } + } + } + } else { + pager = this.templatePager({ + id: this.model.get("id") + "-body", + paginationItems: this.model.get("paginationItems"), + paginationRotate: this.model.get("paginationRotate"), + itemsSections: Math.ceil(this.dom.length / this.pageSize) + }); + htmlPager = $(pager); + pagerItems = htmlPager.children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem'); + htmlPager.children().not(":first").not(':last').not('.toPrevItem').not('.toNextItem').eq(0).addClass("active"); + if (Math.ceil(this.gridtable.length / 5) > 5) { + pagerItems.eq(5 - 1).nextAll().not(':last').not('.toNextItem').css({ display: "none" }); + pagerItems.eq(5).prevAll().not(".toFirst").addClass("showItem"); + pagerItems.eq(5).before('
  • ...
  • '); + } else { + pagerItems.addClass("showItem"); + } + htmlPager.children('li:first').after('
  • '); + htmlPager.children('li:last').before('
  • '); + pagerContainer.append(htmlPager); + } + + return this; + }, + createHTMLTotal: function () { + var k, + dom, + title, + td, + operation, + colSpan, + label, + result, + icon, + totalrow = this.model.get("totalrow"), + layout = this.model.get("layout"), + iconTotal = { + sum: "∑", + avg: "Χ", + other: "ϝ" + }, + that = this; + if (totalrow.length) { + dom = this.$el.find(".pmdynaform-grid-functions"); + dom.children().remove(); + td = document.createElement("div"); + label = document.createElement("span"); + + if (layout === "static") { + dom.addClass("pmdynaform-grid-thead-static"); + if (this.$el.find(".pmdynaform-grid-static").length) { + dom.css({ + width: this.totalWidtRow + 77 + }); + } + } else { + //For the case: responsive and form + td.className = "col-xs-1 col-sm-1 col-md-1 col-lg-1 text-center"; + } + td.appendChild(label); + dom.append(td); + if (layout === "responsive") { + td.style.width = this.indexResponsive; + } else { + $(td).css({ + width: this.indexWidthStatic, + display: "inline-block" + }); + } + if (this.gridtable[0]) { + for (k = 0; k < this.gridtable[0].length; k += 1) { + colSpan = this.gridtable[0][k].model.get("colSpan"); + title = (totalrow[k] === null || totalrow[k] === undefined) ? '' : totalrow[k]; + td = document.createElement("div"); + label = document.createElement("span"); + result = document.createElement("input"); + result.style.width = "50%"; + jQuery(result).attr('readonly', true); + if (this.hiddenColumns.indexOf(k + 1) > -1) { + td.style.display = "none"; + } else if (layout === "form") { + this.checkColSpanResponsive(); + colSpan = this.colSpanControlField(this.gridtable[0], this.gridtable[0][k].model.get("type"), k); + td.className = "col-xs-12 col-sm-" + colSpan + " col-md-" + colSpan + " col-lg-" + colSpan; + } else { + if (layout === "static") { + $(td).css({ + display: "inline-block" + }); + if (this.gridtable[0][k].model.get("columnWidth") && Number(this.gridtable[0][k].model.get("columnWidth")).toString() !== "NaN") { + $(td).css({ + "width": parseInt(this.gridtable[0][k].model.get("columnWidth")) + }); + this.gridtable[0][k].$el.css({ + "width": parseInt(this.gridtable[0][k].model.get("columnWidth")) + }); + } else { + if (this.gridtable[0][k].model.get("type") !== "hidden") { + $(td).css({ + "min-width": this.minCellWidth + }); + this.gridtable[0][k].$el.css({ + "width": this.minCellWidth + }); + } + } + td.className = "pmdynaform-grid-field-static field-operation-result"; + } else { + if (parseInt(this.gridtable[0][k].model.get("columnWidth")) !== 0) { + $(td).css({ + "width": this.gridtable[0][k].model.get("columnWidth"), + display: "inline-block" + }); + } else { + $(td).css({ + "width": this.gridtable[0][k].model.get("columnWidth"), + display: "none" + }); + } + } + } + operation = this.gridtable[0][k].model.attributes.operation; + if (operation) { + $(td).addClass("total"); + icon = iconTotal[operation] ? iconTotal[operation] : iconTotal["other"]; + label.innerHTML = icon + ": "; + result.value = title; + result.id = (operation + "-" + this.model.get("name") + "-" + + this.gridtable[0][k].model.get("columnName")); + $(td).addClass("function-result-" + this.gridtable[0][k].model.get("columnName")); + td.appendChild(label); + td.appendChild(result); + } else { + label.innerHTML = ""; + result.value = ""; + } + dom.append(td); + } + if (this.model.get("layout") == "static") { + this.tableBody.on("scroll", function (e) { + that.$el.find(".containerStaticGrid")[0].scrollLeft = e.target.scrollLeft; + }); + } + } + } + this.showToolTip(); + return this; + }, + /** + * Creates the html row + * @param numberRow + * @param dataRow + * @param sectionAffected + * @returns {{model: Array, view: Array, data: (*|Array)}} + */ + createHTMLRow: function (numberRow, dataRow, rowsDataSchema, sectionAffected, isHelper) { + var tr = this._createHtmlRow(), + td, + k, + tdRemove, + tdNumber, + element, + colSpan, + product, + cellModel, + nameCell, + cloneModel, + idCell, + cellView, + row = [], + rowModel = [], + rowView = [], + rowData, + i, + that = this, + nameToPostControl, + nameToPostLabelControl, + keyEvent = PMDynaform.core.Utils.generateID(); + + if (sectionAffected) { + this.flagRow = sectionAffected; + } + tdNumber = this.createRowNumber(numberRow + 1); + tr.appendChild(tdNumber); + for (k = 0; k < this.columnsModel.length; k += 1) { + cloneModel = jQuery.extend(true, {}, this.columnsModel[k]); + cellModel = null; + product = cloneModel.product; + nameToPostControl = this.createPostVariables(numberRow + 1, cloneModel.name); + nameToPostLabelControl = this.createPostVariables(numberRow + 1, cloneModel.name, '_label'); + cloneModel["nameToPostControl"] = nameToPostControl; + cloneModel["nameToPostLabelControl"] = nameToPostLabelControl; + cloneModel["row"] = numberRow; + cloneModel["col"] = k; + cloneModel["keyEvent"] = keyEvent; + cloneModel["dataForDependent"] = {}; + cellModel = new product.model(cloneModel); + if (this.model.get("variable").trim().length === 0) { + nameCell = ""; + idCell = this.changeIdField(this.model.get("id"), numberRow + 1, cellModel.get("_extended").name); + } else { + nameCell = this.changeNameField(this.model.get("name"), numberRow + 1, cellModel.get("_extended").name); + idCell = this.changeIdField(this.model.get("id"), numberRow + 1, cellModel.get("_extended").name); + } + cellModel.attributes.name = nameCell; + cellModel.attributes.id = idCell; + rowModel.push(cellModel); + } + for (i = 0; i < rowModel.length; i += 1) { + product = this.columnsModel[i].product; + cellView = null; + cellView = new product.view({ + model: rowModel[i], + form: this.form + }); + + cellView.setColumnIndex(i); + cellView.setOnFieldFocusCallback(function () { + that.scrollToColumn(this.columnIndex); + }); + rowModel[i].set("view", cellView); + cellView.project = this.project; + cellView.parent = this; + colSpan = rowModel[i].attributes.colSpan; + element = cellView.render().el; + if (this.model.get("layout") === "responsive") { + if ($(element).find(".form-control")[0]) { + var elementParent = $(element).find(".form-control")[0].parentNode; + elementParent.style.padding = "0px"; + } + td = document.createElement("div"); + td.className = "grid-cell-responsive"; + td.style.display = "inline-block"; + } else { + td = this._createHtmlCell(rowModel[i].attributes.type, colSpan, i); + } + if (this.hiddenColumns.indexOf(i + 1) > -1) { + $(td).hide(); + } + if (cellView.model.get("type") !== "hidden" && this.model.get("layout") === "static") { + if (cellView.model.get("columnWidth") && Number(cellView.model.get("columnWidth")).toString() !== "NaN") { + $(td).css({ + "min-width": parseInt(cellView.model.get("columnWidth")), + "max-width": parseInt(cellView.model.get("columnWidth")) + }); + cellView.$el.css({ + "width": parseInt(cellView.model.get("columnWidth")) + }); + } else { + $(td).css({ + "min-width": "200px", + "max-width": "200px" + }); + } + } + + if (this.model.get("layout") === "responsive") { + if (parseInt(cellView.model.get("columnWidth")) !== 0) { + $(td).css({ + "width": cellView.model.get("columnWidth") + }); + } else { + $(td).css({ + "width": cellView.model.get("columnWidth"), + display: "none" + }); + } + } + + $(element).addClass("row form-group"); + td.appendChild(element); + tr.appendChild(td); + row.push(cellView); + rowView.push(cellView); + } + rowData = this.prepareNewRow(row, dataRow); + this.updateNameFields(row); + for (var k = 0; k < row.length; k += 1) { + if (row[k].model.get("formula")) { + row[k].model.attributes.formulaAssociatedObject = []; + row[k].onFormula(row); + } + } + if (this.model.get("mode") === "edit") { + if (this.model.get("deleteRow")) { + tdRemove = this.createRemoveButton(numberRow + 1); + $(tdRemove).addClass("remove-row"); + tr.appendChild(tdRemove); + } + } + if (this.model.get("layout") === "responsive") { + jQuery(tdNumber).css({ width: this.indexResponsive }); + jQuery(tdRemove).css({ width: this.removeResponsive }); + } + this.flagRow += 1; + if (this.paged) { + this._createHTLMCarucel(); + this.domCarousel.append(tr); + this.tableBody.append(this.domCarousel); + } else { + this.tableBody.append(tr); + } + if (!this.deleteButtonVisibility) { + this.hideButton("delete"); + } + this.gridtable.push(row); + this.dom.push(tr); + this._executeDependenciesByRow(row, rowsDataSchema, isHelper); + return { + model: rowModel, + view: rowView, + data: rowData + }; + }, + /** + * Prepare the data for the grid row + * @param row + * @param dataRow + * @returns {Array} + */ + prepareNewRow: function (row, dataRow) { + var cellView, + that = this, + rowData = []; + + this.setRowData(row, dataRow); + if (_.isArray(row)) { + for (var i = 0; i < row.length; i += 1) { + cellView = row[i]; + if (cellView.model.get("operation") !== "") { + cellView.on("changeValues", function () { + that.setValuesGridFunctions({ + row: this.model.attributes.row, + col: this.model.attributes.col, + data: this.model.get("data").value + }); + that.createHTMLTotal(); + }); + } + if (row[i].model.get("operation")) { + if (!isNaN(parseFloat(row[i].model.get("value")))) { + rowData.push(parseFloat(row[i].model.get("value"))); + } else { + rowData.push(0); + } + } + } + } + return rowData; + }, + /** + * Sets data in the cells identifying the mode (view, edit and disabled) + * @param {array|number} row: is a index of array + * @param {[type]} rowData : is a set of data + */ + setRowData: function (row, rowData) { + if (typeof row === "number") { + row = this.gridtable[row]; + } + this._populateRow(row, rowData); + return this; + }, + /** + * Populate the grid row data. + * @param {Array} row + * @param {Array} rowData + */ + _populateRow: function (row, rowData) { + var i; + if (_.isArray(row) && _.isArray(rowData)) { + for (i = 0; i < row.length; i += 1) { + if (rowData[i]) { + this._completeRowData(row[i], rowData[i]); + } + } + } + }, + /** + * After the data was populated we need execute dependencies + * @param {Array} row + * @param {Array|undefined} rowsDataSchema + * @param {boolean|undefined} isHelper + */ + _executeDependenciesByRow: function (row, rowsDataSchema, isHelper) { + var i; + if (_.isArray(row)) { //Only works in new Row in GridTable + for (i = 0; i < row.length; i += 1) { + if (rowsDataSchema && rowsDataSchema[i] + && row[i].model.get("isDependent") + && row[i].setValueWithoutTriggerDependencies + && (!rowsDataSchema[i].defined || isHelper)) { + row[i].setValueWithoutTriggerDependencies(row[i].model.get("data").value); + } + } + } + }, + /** + * Set the data to a grid cell. + * @param {*} cell + * @param {*} data + */ + _completeRowData: function (cell, data) { + var type = cell.model.get("originalType"), + viewMode = cell.model.get("mode"); + if (type !== "multipleFile") { + (viewMode === "edit" || viewMode === "disabled") ? + this._setDataToEditMode(cell, data) : this._setDataToViewMode(cell, data); + } + return this; + }, + _setDataToViewMode: function (cell, data) { + if (cell && data !== undefined && data !== null) { + if (typeof cell.setData === "function") { + cell.setData(data); + } + } + return this; + }, + _setDataToEditMode: function (cell, data) { + var fixedData; + if (cell && data !== undefined && data !== null && data.value) { + // Sanitizing the data because from helper arrives only the value and row works wit value and label + fixedData = { + value: data.value || '', + label: data.label || data.value || '' + }; + cell.model.set('addRowValue', fixedData.value || null); + switch (cell.model.get('type')) { + case 'checkbox': + case 'link': + cell.setValue(fixedData.value); + break; + case 'file': + fixedData.value = fixedData.value === 'string' ? [] : fixedData.value; + cell.setData(fixedData); + break; + case 'text': + cell.model.set({ "data": fixedData }, { silent: true }); + cell.model.set({ "value": fixedData.value }, { silent: true }); + cell.model.set("toDraw", true); + break; + case 'dropdown': + cell.model.set({ "data": fixedData }, { silent: true }); + cell.model.set("toDraw", true); + break; + default: + // Only from addRow arrive a empty label, + // here the dependent event need to be fired + if (!data.label) { + cell.setData(fixedData); + } else { + cell.model.set({ "data": fixedData }, { silent: true }); + cell.model.set({ "value": fixedData.value }, { silent: true }); + cell.model.set("toDraw", true); + } + break; + } + } + return this; + }, + _createHTLMCarucel: function () { + if (this.block === true) { + this.domCarousel = document.createElement("div"); + this.domCarousel.className = "pmdynaform-grid-section_" + this.section; + if (this.model.get("layout") === "static") { + this.domCarousel.className += " pmdynaform-static"; + } + this.domCarousel = $(this.domCarousel); + } + if (this.section === this.showPage) { + this.domCarousel.addClass("item active"); + } else { + this.domCarousel.addClass("item"); + } + if (this.flagRow == this.pageSize) { + this.block = true; + this.section += 1; + this.flagRow = 0; + } else { + this.block = false; + } + return this; + }, + _createHtmlRow: function () { + var tr; + tr = document.createElement("div"); + tr.className = "pmdynaform-grid-row row form-group show-grid"; + if (this.model.get("layout") === "static") { + tr.className += " pmdynaform-grid-static" + } + return tr; + }, + _createHtmlCell: function (typeControl, colSpan, index) { + var td, colSpan; + td = document.createElement("div"); + if (this.model.attributes.layout === "form") { + if (typeControl !== "hidden") { + this.checkColSpanResponsive(); + colSpan = this.colSpanControlField(typeControl, index); + td.className = "col-xs-12 col-sm-" + colSpan + " col-md-" + colSpan + " col-lg-" + colSpan; + } else { + jQuery(td).css({ + width: 0 + "%", + display: "inline-block" + }); + } + } else if (this.model.attributes.layout === "static") { + if (typeControl !== "hidden") { + td.className = "pmdynaform-grid-field-static"; + } + } else { + if (typeControl !== "hidden") { + td.className = "col-xs-" + colSpan + " col-sm-" + colSpan + " col-md-" + colSpan + " col-lg-" + colSpan; + jQuery(td).css({ + width: this.colSpanControlFieldResponsive() + "%", + display: "inline-block" + }); + } else { + jQuery(td).css({ + width: 0 + "%", + display: "inline-block" + }); + } + } + return td; + }, + setData: function (data) { + var col, + i, + j, + cloneData = data, + grid = this.gridtable; + + if (typeof data === "object") { + if (cloneData.length) { + for (j in cloneData) { + if (cloneData.hasOwnProperty(j)) { + for (col = 0; col < grid[0].length; col += 1) { + if (!_.isEmpty(grid[0][col].model.attributes.variable)) { + if (grid[0][col].model.attributes.variable.var_name === j) { + if (cloneData[j] instanceof Array) { + for (i = 0; i < grid.length; i += 1) { + + if (!this.gridtable[i][col].model.get("formulator")) { + grid[i][col].model.set("value", cloneData[j][i]); + if (this.gridtable[i][col].onFieldAssociatedHandler) { + this.gridtable[i][col].onFieldAssociatedHandler() + } + } + } + } + } + } + } + } + } + } + } else { + //console.log("Error, The 'data' parameter is not valid. Must be an array."); + } + return this; + }, + getData: function () { + var i, + k, + gridpanel, + fields, + rowData = [], + gridData = [], + gridFieldData = { + name: this.model.get("name"), + gridtable: [] + }, + data = this.model.getData(); + + gridpanel = this.gridtable; + for (i = 0; i < gridpanel.length; i += 1) { + rowData = []; + for (k = 0; k < gridpanel[i].length; k += 1) { + if ((typeof gridpanel[i][k].getData === "function") && + (gridpanel[i][k] instanceof PMDynaform.view.Field)) { + rowData.push(gridpanel[i][k].getData()); + } + } + gridData.push(rowData); + } + gridFieldData.gridtable = gridData; + + return gridFieldData; + }, + renderGridTable: function (newItem) { + var i, + j, + rows, + rowsData, + rowData, + row, + rowsDataSchema, + rowDataSchema; + this.tableBody = this.$el.find(".pmdynaform-grid-tbody"); + rows = this.model.get("rows"); + rowsData = this.model.get("data"); + rowsDataSchema = this.model.get("dataSchema"); + if (this.model.get("layout") === "static") { + this.tableBody.addClass("pmdynaform-static"); + } + this.model.attributes.gridFunctions = []; + if (!newItem) { + this.dom = []; + for (j = 0; j < rows; j += 1) { + rowData = rowsData[j + 1]; + rowDataSchema = rowsDataSchema[j + 1]; + row = this.createHTMLRow(j, rowData, rowDataSchema); + if (row && row.data) { + this.model.attributes.gridFunctions.push(row.data); + for (i = 0; i < row.model.length; i += 1) { + if (row.model[i].get("operation") && row.model[i].get("operation").trim().length) { + row.view[i].onChangeCallbackOperation(); + } + if (row.model[i].get("type") === "label" && row.model[i].get("operation")) { + this.createHTMLTotal(); + } + } + } + } + } else { + row = this.createHTMLRow(this.gridtable.length - 1); + if (row && row.data) { + this.model.attributes.gridFunctions.push(row.data); + } + } + this.model.setPaginationItems(); + this.createHTMLPager(); + return this; + }, + /** + * @Event + * @param Event This must be an event valid + * @param Function Callback for the event + **/ + on: function (e, fn) { + var allowEvents = { + remove: "setOnDeleteRowCallback", + add: "setOnAddRowCallback", + pager: "setOnClickPageCallback", + beforeAdd: "setOnBeforeAddCallback" + }; + + if (allowEvents[e]) { + this[allowEvents[e]](fn); + } else { + throw new Error("The event must be a valid event.\n The events available are remove, add and pager"); + } + + return this; + }, + setOnDeleteRowCallback: function (fn) { + if (typeof fn === "function") { + this.onDeleteRowCallback = fn; + } else { + throw new Error("The callback must be a function"); + } + return this; + }, + setOnAddRowCallback: function (fn) { + if (typeof fn === "function") { + this.onAddRowCallback = fn; + } else { + throw new Error("The callback must be a function"); + } + return this; + }, + setOnBeforeAddCallback: function (fn) { + if (typeof fn === "function") { + this.onBeforeAddRowCallback = fn; + } else { + throw new Error("The callback must be a function"); + } + return this; + }, + setOnClickPageCallback: function (fn) { + if (typeof fn === "function") { + this.onClickPageCallback = fn; + } else { + throw new Error("The callback must be a function"); + } + + return this; + }, + afterRender: function () { + this.showToolTip(); + }, + /** + * this method get data in json formated, of this field. + * The suports controls are: + * - text + * - textarea + * - dropdown + * - hidden + * - checkbox + * - suggest + * - datetime + * @return {object} json + */ + getData2: function () { + var validControls, + gridpanel, + cellName, + rowData, + cell, + data = {}, + key, + k, + i; + validControls = ["text", "textarea", "dropdown", "hidden", "checkbox", "datetime", "suggest", "multipleFile"]; + gridpanel = this.gridtable; + for (i = 0; i < gridpanel.length; i += 1) { + data[i + 1] = {}; + rowData = {}; + for (k = 0; k < gridpanel[i].length; k += 1) { + cell = gridpanel[i][k].model; + if (validControls.indexOf(cell.get("originalType")) > -1) { + cellName = cell.get("columnName"); + rowData[cellName] = cell.get("data")["value"]; + rowData[cellName + "_label"] = cell.get("data")["label"]; + } + } + data[i + 1] = rowData; + } + return data; + }, + /** + * Get deleted files into a grid + * @returns {Object} + */ + getDeletedData: function () { + var validControls, + gridpanel, + cellName, + rowDeletedData, + cell, + deletedData = {}, + k, + i; + validControls = ["text", "textarea", "dropdown", "hidden", "checkbox", "datetime", "suggest", "multipleFile"]; + gridpanel = this.gridtable; + for (i = 0; i < gridpanel.length; i += 1) { + rowDeletedData = {}; + for (k = 0; k < gridpanel[i].length; k += 1) { + cell = gridpanel[i][k].model; + if (validControls.indexOf(cell.get("originalType")) > -1) { + cellName = cell.get("columnName"); + documentDelete = cell.makeVariableDocumentDelete ? cell.makeVariableDocumentDelete() : {}; + if (!_.isEmpty(documentDelete) && !_.isEmpty(documentDelete[cell.get("name")])) { + rowDeletedData[cellName] = documentDelete[cell.get("name")]; + } + } + } + if (!_.isEmpty(rowDeletedData)) { + deletedData[i + 1] = rowDeletedData; + } + + } + return deletedData; + }, + setData2: function (data) { + var rowIndex, grid, dataRow, + colIndexm, cols, colIndex, + cellModelItem, cellViewItem, + modeItem, dataItem, newItem, value, richi, option, options, i; + grid = this.gridtable; + for (rowIndex in data) { + if (parseInt(rowIndex, 10) > this.gridtable.length) { + newItem = this.addRow(); + this.renderGridTable(); + this.onAddRowCallback(newItem, this); + } + cols = grid[parseInt(rowIndex, 10) - 1].length; + for (colIndex = 0; colIndex < cols; colIndex += 1) { + cellViewItem = grid[parseInt(rowIndex, 10) - 1][colIndex]; + cellModelItem = grid[parseInt(rowIndex, 10) - 1][colIndex].model; + modeItem = cellModelItem.get("mode"); + for (dataItem in data[rowIndex]) { + if (cellModelItem.get("columnName") === dataItem) { + if (modeItem === "edit" || modeItem === "disabled") { + if (cellModelItem.get("type") === "suggest") { + + for (richi = 0; richi < cellModelItem.get("localOptions").length; richi += 1) { + option = cellModelItem.get("localOptions")[richi].value; + if (option === data[rowIndex][dataItem]) { + value = cellModelItem.get("localOptions")[richi].label; + break; + } + } + if (value && !value.length) { + for (richi = 0; richi < cellModelItem.get("options").length; richi += 1) { + option = cellModelItem.get("options")[richi].value; + if (option === data[rowIndex][dataItem]) { + value = cellModelItem.get("options")[richi].label; + break; + } + } + } + + $(cellViewItem.el).find(":input").val(value); + cellModelItem.attributes.value = data[rowIndex][dataItem]; + } else if (cellModelItem.get("type") === "checkbox") { + options = cellModelItem.get("options"); + if (cellModelItem.get("dataType") === "boolean") { + if (data[cellModelItem.get("name")] === options[0].value) { + options[1].selected = false; + options[0].selected = true; + } else { + delete options[0].selected; + options[1].selected = true; + options[0].selected = false; + } + } else { + for (i = 0; i < options.length; i += 1) { + delete options[i].selected; + if (data[rowIndex][dataItem].indexOf(options[i]) > -1) { + options[i].selected = true; + } + } + } + cellModelItem.set("options", options); + cellModelItem.initControl(); + cellModelItem.set("value", [data[rowIndex][dataItem]]) + } else { + cellModelItem.set("value", data[rowIndex][dataItem]); + } + } + if (modeItem === "view") { + if (cellModelItem.get("originalType") === "checkbox") { + cellModelItem.set("fullOptions", data[rowIndex][dataItem]); + } else if (cellModelItem.get("originalType") === "dropdown") { + value = []; + for (richi = 0; richi < cellModelItem.get("localOptions").length; richi += 1) { + option = cellModelItem.get("localOptions")[richi].value; + if (option === data[rowIndex][dataItem]) { + value.push(cellModelItem.get("localOptions")[richi].label); + cellModelItem.set("fullOptions", value); + break; + } + } + if (!value.length) { + for (richi = 0; richi < cellModelItem.get("options").length; richi += 1) { + option = cellModelItem.get("options")[richi].value; + if (option === data[rowIndex][dataItem]) { + value.push(cellModelItem.get("options")[richi].label); + cellModelItem.set("fullOptions", value); + break; + } + } + } + } else { + value = []; + value.push(data[rowIndex][dataItem]); + cellModelItem.set("fullOptions", value); + } + } + } + } + } + } + return this; + }, + render: function () { + var that = this, + bodyGrid; + + this.$el.html(this.template(this.model.toJSON())); + this.createHTMLTitle(); + this.renderGridTable(false); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + + this._$gridHeader = this.$el.find(".pmdynaform-grid-thead"); + this._gridHeader = this._$gridHeader.get(0); + + if (this.model.get("layout") === "static") { + bodyGrid = this.$el.find(".pmdynaform-grid-tbody"); + bodyGrid.css("overflow", "auto"); + bodyGrid.scroll(function (event) { + that._$gridHeader.scrollLeft(bodyGrid.scrollLeft()); + event.stopPropagation(); + }); + } + if (!this.model.get("addRow")) { + this.$el.find(".pmdynaform-grid-new").find("button").hide(); + } + if (this.model.get("layout") === "responsive") { + var size = { + "1200": 5, + "992": 4, + "768": 3, + "767": 2 + }; + + $(window).resize(function () { + var j, + k, + width = $(window).width(); + + if (width >= 1200) { + //console.log("1200"); + } + if (width >= 992 && width < 1200) { + //console.log("992"); + } + if (width >= 768 && width < 992) { + //console.log(">768"); + } + if (width < 768) { + //console.log("<768"); + } + + }); + } + + this.attachListeners(); + if (this._hidden) { + this.hide(); + } else { + this.show(); + } + return this; + }, + scrollToColumn: function (columnIndex) { + // We add 1 because the columnIndezx is ignoring the column for row number. + var gridBody = this.$el.find('.pmdynaform-grid-tbody').get(0), + gridBodyBR = gridBody.getBoundingClientRect(), + columnHeader, + headerIndex = 0; + if (this.model.get("layout") === "static") { + columnHeader = this.$el.find('.pmdynaform-grid-thead') + .find('.pmdynaform-grid-field-static').eq(columnIndex + 1); + if (columnHeader.get(headerIndex)) { + columnHeader = columnHeader.get(headerIndex).getBoundingClientRect(); + if (columnHeader.left < gridBodyBR.left) { + gridBody.scrollLeft -= gridBodyBR.left - columnHeader.left; + } + } + } + }, + setValue: function (value, row, col) { + if (value !== undefined) { + if (row !== undefined && col !== undefined) { + if ((row > 0 && col > 0) && row <= this.gridtable.length && col <= this.columnsModel.length) { + return this.gridtable[row - 1][col - 1].setValue(value); + } else { + return null; + } + } + } + return this; + }, + /** + * Method to set Value Async in grid field + * @param {*} value + * @param {*} row + * @param {*} col + * @param {*} fn + */ + setValueAsync: function (value, row, col, fn) { + if (value !== undefined) { + if (row !== undefined && col !== undefined) { + if ((row > 0 && col > 0) && row <= this.gridtable.length && col <= this.columnsModel.length) { + return this.gridtable[row - 1][col - 1].setValueAsync(value, fn); + } else { + return null; + } + } + } + return this; + }, + /** + * Method to set Text Async in grid field + * @param {*} text + * @param {*} row + * @param {*} col + * @param {*} fn + */ + setTextAsync: function (text, row, col, fn) { + if (text !== undefined) { + if (row !== undefined && col !== undefined) { + if ((row > 0 && col > 0) && row <= this.gridtable.length && col <= this.columnsModel.length) { + return this.gridtable[row - 1][col - 1].setTextAsync(text, fn); + } else { + return null; + } + } + } + return this; + }, + getValue: function (row, col) { + return this.model.getValue(row, col); + }, + /** + * Create grid variables to send by AJAX to the server side + * using the native form action to send via POST. + * @param rowIndex index number + * @param columnName column number + * @param suffix when the field has _label suffix + * @returns {string} + */ + createPostVariables: function (rowIndex, columnName, suffix) { + var index = this.model.get("variable") || this.model.get("id"), + suffix = suffix || ''; + return "form[" + index + "][" + rowIndex + "][" + columnName + suffix + "]"; + }, + + getColumnHeader: function (index) { + var cols; + if (this._gridHeader) { + cols = this.model.getHiddensBeforeColumn(index - 1); + return this._$gridHeader.find('> *').eq(index - cols.length); + } + return null; + }, + hideColumn: function (col) { + var field = this, + table, + row, + cell, + i, + label; + table = field.gridtable; + if (col > 0 && col <= field.columnsModel.length) { + if (field.hiddenColumns.indexOf(col) === -1) { + field.hiddenColumns.push(col); + } + for (i = 0; i < table.length; i += 1) { + row = table[i]; + cell = row[col - 1]; + if (cell.model.get("type") !== "hidden") { + cell.$el.hide(); + if (cell.$el.parent().length) { + cell.$el.parent().hide(); + } + if (cell.model.get("operation") !== "") { + field.$el.find("." + "function-result-" + cell.model.get("columnName")).hide(); + } + } + } + if (field.$el.find(".field-operation-result") && field.columnsModel[col - 1].type !== "hidden") { + field.$el.find(".field-operation-result").eq(col - 1).hide(); + this.getColumnHeader(col).hide(); + } + } + }, + showColumn: function (col) { + var field = this, + table, + row, + cell, + label, + i, + index; + table = field.gridtable; + if (col > 0 && col <= field.columnsModel.length) { + index = field.hiddenColumns.indexOf(col); + if (index > -1) { + field.hiddenColumns.splice(index, 1); + } + for (i = 0; i < table.length; i += 1) { + row = table[i]; + cell = row[col - 1]; + if (cell.model.get("type") !== "hidden") { + cell.$el.show(); + if (cell.$el.parent().length) { + cell.$el.parent().show(); + } + } + } + if (cell) { + if (cell.model.get("operation") !== "") { + field.$el.find("." + "function-result-" + cell.model.get("columnName")).show(); + } + if (field.$el.find(".field-operation-result") && field.columnsModel[col - 1].type !== "hidden") { + field.$el.find(".field-operation-result").eq(col - 1).show(); + this.getColumnHeader(col).show(); + } + } + } + }, + /** + * Hide Buttons "NewRow" or "deleteRow" + * @param buttonText + * @returns {GridView} + */ + hideButton: function (buttonText) { + var itemNewButton = this.$el.find(".pmdynaform-grid-newitem"), + itemDeleteButton = this.$el.find("button.glyphicon.glyphicon-trash"); + switch (buttonText) { + case "add": + if (this.model.get("addRow") && itemNewButton.is(":visible")) { + itemNewButton.hide(); + } + break; + case "delete": + if (this.model.get("deleteRow") && itemDeleteButton.is(":visible")) { + this.deleteButtonVisibility = false; + itemDeleteButton.hide(); + } + break; + } + return this; + }, + /** + * Show Buttons "NewRow" or "deleteRow" + * @param buttonText + * @returns {GridView} + */ + showButton: function (buttonText) { + var itemNewButton = this.$el.find(".pmdynaform-grid-newitem"), + itemDeleteButton = this.$el.find("button.glyphicon.glyphicon-trash"); + switch (buttonText) { + case "add": + if (this.model.get("addRow") && !itemNewButton.is(":visible")) { + itemNewButton.show(); + } + break; + case "delete": + if (this.model.get("deleteRow") && !itemDeleteButton.is(":visible")) { + this.deleteButtonVisibility = true; + itemDeleteButton.show(); + } + break; + } + return this; + }, + getNumberRows: function () { + return this.gridtable.length; + }, + /** + * this method execute, when the grid undergoes a change that requires validation check + * @returns {boolean} + */ + validateGrid: function () { + var valid = true; + if (this.validator) { + this.validator.$el.remove(); + } + valid = this.model.isValid(); + if (!valid) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".pmdynaform-grid").parent().append(this.validator.el); + this.$el.find(".pmdynaform-grid").addClass("has-error"); + } else { + this.$el.find(".pmdynaform-grid").removeClass("has-error"); + } + if (this.model.get("rows") === 0) { + this.renderEmptyGrid(); + } else { + this.removeEmptyGrid(); + } + return valid; + }, + /** + * this template is append when the rows not exist in the grid + * @returns {GridView} + */ + renderEmptyGrid: function () { + var emptyTag, + container = this.$el.find("#" + this.model.get("id") + "-body"); + emptyTag = this.$el.find(".grid-empty"); + if (emptyTag instanceof jQuery && emptyTag.length === 0) { + emptyTag = this.templateEmptyGrid({ + message: this.model.get("emptyMessage") + }); + container.prepend(emptyTag); + } + return this; + }, + /** + * this template is removed when the rows exist in the grid + * @returns {GridView} + */ + removeEmptyGrid: function () { + this.$el.find(".grid-empty").remove(); + return this; + }, + attachListeners: function () { + var grid = this.$el.find('.pmdynaform-grid-tbody'), + that = this; + + if (grid.length) { + grid.on('scroll', function () { + if (that.project) { + that.project.hideCalendars(); + } + }); + } + }, + getColumnToId: function (id) { + var column, colIndex, cell = {}; + column = this.columnsModel.find(function (column, index) { + if (column.columnId === id) { + colIndex = index + 1; + return column; + } + }); + if (colIndex) { + cell = { + colIndex: colIndex, + column: column + } + } + return cell; + }, + getSummary: function (col) { + var result = null, column, colIndex; + column = parseInt(col); + if (_.isNaN(column)) { + column = this.getColumnToId(col); + colIndex = column['colIndex'] ? column['colIndex'] : -1; + } else { + colIndex = column; + } + if (colIndex > 0 && colIndex <= this.columnsModel.length) { + column = this.columnsModel[colIndex - 1]; + if (column && column.operation) { + result = this.model.get("totalrow")[colIndex - 1]; + } + } + return !!result ? result : 0; + }, + validateRowCol: function (row, col) { + var rowAux = Math.floor(row), + colAux = Math.floor(col), + sw = false; + + if (!_.isNaN(rowAux) && !_.isNaN(col)) { + if (rowAux > 0 && colAux > 0 && rowAux <= this.gridtable.length && colAux <= this.columnsModel.length) { + sw = true; + } + } + return sw; + }, + getItemGrid: function (row, col) { + var itemGrid = null; + if (this.validateRowCol(row, col)) { + itemGrid = this.gridtable[row - 1][col - 1]; + } + return itemGrid; + }, + getText: function (row, col) { + var itemGrid = this.getItemGrid(row, col); + return itemGrid ? itemGrid.getText() : null; + }, + /** + * Get Control HTML from Field + * @param row + * @param col + * @returns {Array} + */ + getControl: function (row, col) { + var htmlControl = []; + if (row && col) { + if (this.model.isRowInRange(row) && this.model.isColumnInRange(col)) { + htmlControl = this.gridtable[row - 1][col - 1].getControl(); + } + } + return htmlControl; + }, + /** + * Create Tooltip and show in the event hover + * and hide in the event blur or make scrolling in Body of the Datatable + */ + showToolTip: function () { + var dataTableResult = $(".pmdynaform-grid-functions").find("input"), + toolTipVar = new PMDynaform.view.ToolTipView(); + + if (dataTableResult) { + dataTableResult.hover(function (e) { + toolTipVar.show($(this), $(this).val(), "bottom"); + e.stopPropagation(); + e.preventDefault(); + }); + + dataTableResult.mouseout(function (e) { + toolTipVar.hide($(this)); + e.stopPropagation(); + e.preventDefault(); + }); + } + }, + /** + * Set the columnId to know the column delete file + * @returns {number} + */ + getColumnFileDelete: function (columnId, nameRow) { + return this.model.getColumnFileDelete(columnId, nameRow); + }, + /** + * Clear Content File Grid + * @param row + * @param col + * @returns {GridView} + */ + clearContent: function (row, col) { + var viewFile; + if (row && col) { + if (this.model.isRowInRange(row) && this.model.isColumnInRange(col)) { + viewFile = this.gridtable[row - 1][col - 1]; + if (viewFile && viewFile.model.get("type") === "file") { + viewFile.clearContent(); + } + } + } + return this; + }, + /** + * Delete a files in a row of grid + * @param row + * @returns {GridView} + */ + deleteFilesByRow: function (row) { + var index; + for (index = 0; index < row.length; index += 1) { + if (row[index].model.get("originalType") === "multipleFile") { + row[index].model.deleteFiles(); + } + } + return this; + }, + /** + * Clear all grid's row. + */ + clearAllRows: function () { + var totalItems = this.gridtable.length, + mode = this.model.get('mode'); + if (mode === "edit") { + while (totalItems >= 0) { + this.deleteRow(totalItems); + totalItems -= 1; + } + } + }, + /** + * Gets all fields that was not already uploaded. + * @returns {array} + */ + getFilesNotUploaded: function () { + var i, + j, + filesError = [], + row, + rows = this.model.get("gridtable"); + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + for (j = 0; j < row.length; j += 1) { + if (row[j].model.get("type") === "multipleFile") { + filesError = filesError.concat(row[j].getFilesNotUploaded()); + } + } + } + return filesError; + }, + /** + * Gets the loading value into the grid fields + * @returns {boolean} + */ + isLoading: function () { + var i, + j, + row, + rows = this.model.get("gridtable"); + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + for (j = 0; j < row.length; j += 1) { + if (row[j].model.get("type") !== "multipleFile") { + if (row[j].model.get("loading")) { + return true; + } + } + } + } + return false; + } + + }); + PMDynaform.extendNamespace("PMDynaform.view.GridPanel", GridView); +}()); + +(function () { + var ButtonView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-button").html()), + events: { + "keydown": "preventEvents" + }, + tagControl: null, + tagLabel: null, + initialize: function () {}, + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + on: function (e, fn) { + var that = this; + if (this.tagControl.length) { + this.tagControl.on(e, function (event) { + fn(event, that); + event.stopPropagation(); + }); + } + return this; + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + this.tagControl = this.$el.find("button"); + this.tagLabel = this.$el.find("button span"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setValue: function (text) { + if (text) { + this.model.set("label", text); + this.tagLabel.text(text); + } + return this; + }, + getText: function () { + var label = this.model.get("label"); + return label ? label : null; + }, + getValue: function () { + return this.model.getValue(); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Button", ButtonView); +}()); +(function () { + var DropDownView = PMDynaform.view.Field.extend({ + events: { + "change select": "changeSelectEvent", + "keydown select": "preventEvents", + "focus select": "focusSelectEvent" + }, + clicked: false, + jsonData: {}, + firstLoad: true, + dirty: false, + previousValue: "", + triggerCallback: false, + template: _.template($("#tpl-dropdown").html()), + templateOptions: _.template($("#tpl-dropdown-options").html()), + existHTML: false, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + this.form = options.form ? options.form : null; + this.previousValue = this.getValue(); + this.formulaFieldsAssociated = []; + this.model.on("change:options", this.redrawOptions, this); + this.model.on("change:toDraw", this.refreshHTML, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + this.model.on("change:disablePlaceholder", this.removePlaceholder, this); + }, + /** + * removePlaceholder(), this method remove placeholder option, + * when is change option. + * @return {object} + */ + removePlaceholder: function () { + this.tagControl.find("#placeholder-option").remove(); + return this; + }, + /** + * Default function + */ + onChangeCallback: null, + /** + * Sets onChangeCallback function + * @param fn {function} + * @returns {DropDownView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + setValueDefault: function () { + var val = $(this.el).find(":selected").val(); + if (val != undefined && val != null) { + this.model.set("value", val); + } else { + this.model.set("value", ""); + } + }, + validate: function () { + var drpValue; + drpValue = this.$el.find("select").val() || ""; + this.model.set({ value: drpValue }, { validate: true }); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator"), + domain: false + }); + this.$el.find("select").parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + on: function (e, fn) { + var that = this, + control = this.$el.find("select"); + if (control) { + control.on(e, function (event) { + fn(event, that); + event.stopPropagation(); + }); + } + return this; + }, + /** + * Get the html control using its class identifier + * @returns {Object} + */ + getHTMLControl: function () { + return this.$el.find("select"); + }, + /** + * Refresh dropdown in grids + * @return {DropDownView} + */ + refreshHTML: function () { + if (this.existHTML && this.model.get("group") === "grid") { + if (!this.model.findValueInOptions(this.model.get("data")["value"])) { + this._setOptions([this.model.get("data")]); + this.tagHiddenToLabel.val(this.model.get("data")["label"]); + } else { + this.render(); + } + } + return this; + }, + /** + * Render the field View + * @return {DropDownView} + */ + render: function () { + var hidden, + name; + this.existHTML = true; + this.$el.html(this.template(this.model.toJSON())); + this.$el.find("input[type='hidden']").val(this.model.get("data")["label"]); + // Only works in Mobile grid + if (PMDynaform.core.ProjectMobile && this.model.get("parentField")) { + this._setDataOption(); + } + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + } + if (this.model.get("hint")) { + this.enableTooltip(); + } + this.setValueToDomain(); + if (this.model.get("name").trim().length === 0) { + this.$el.find("select").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.$el.find(".content-print").text(this.model.get("data")["label"]); + this.tagControl = this.$el.find("select"); + this.tagControl.val(this.model.get("data")["value"].toString() || ""); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Set options in html control + * @param {*} options + * @return {DropDownView} + */ + _setOptions: function (options) { + var htmlOptions, + placeholderOption = {}, + selectControl = this.$el.find("select"), + therePlaceholder = this.model.get("therePlaceholder"); + if (therePlaceholder) { + placeholderOption = this.model.get("placeholderOption"); + } + selectControl.empty(); + htmlOptions = this.templateOptions({ + options: options, + therePlaceholder: therePlaceholder, + placeholderOption: placeholderOption + }); + selectControl.append(htmlOptions); + return this; + }, + /** + * Set data in options + * @return {DropDownView} + */ + _setDataOption: function () { + var data = this.model.get("data"); + if (data && data["value"]) { + this._setOptions([data]); + } + return this; + }, + /** + * Returns a label from model + * @return {*} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Returns the value model + * @return {String} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Returns the control field + * @return {*} + */ + getControl: function () { + var htmlControl = this.$el.find("select"); + return htmlControl; + }, + /** + * redrawOptions, Draw component options + * @chainable + */ + redrawOptions: function () { + if (this.existHTML) { + this.firstLoad = false; + this._setOptions(this.model.get("options")); + this.tagHiddenToLabel.val(this.model.get("data")["label"]); + } + return this; + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @return {DropDownView} + */ + changeSelectEvent: function (event, value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + that.validate(); + }); + return this; + }, + /** + * When the source of change is a helper + * @param {*} value + * @param {*} fn + * @return {DropDownView} + */ + changeHelperEvent: function (value, fn) { + var dt, that = this; + this.tagControl.val(value); + dt = this.updateView(function () { + that.executeChangeCallback(); + if (_.isFunction(fn)) { + fn(); + } + }); + return this; + }, + + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @param {*} fn + * @return {DropDownView} + */ + updateView: function (fn) { + var dt = { + value: "", + label: "" + } + dt = this.updateFieldView(); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + //The validation works with the model data: value-label, in this moment the model data is correct + this.validate(); + return this; + }, + /** + * Update the view + * @return {*} + */ + updateFieldView: function () { + var hiddenInput, + label, + option; + if (this.model.get("therePlaceholder")) { + this.removePlaceholder(); + } + option = this.tagControl.find(":selected"); + if (this.tagControl) { + this.tagControl.children().removeAttr("selected"); + option.prop("selected", true); + option.attr("selected", "selected"); + label = option.text().trim(); + hiddenInput = this.$el.find("input[type='hidden']"); + hiddenInput.val(label); + value = this.tagControl.val(); + } + this.$el.find(".content-print").text(label); + this.clicked = false; + return { + value: value, + label: label + }; + }, + /** + * Helper setValue + * @param {*} value + * @param {*} fn + * @return {DropDownView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Helper setText + * @param {*} txt + * @return {DropDownView} + */ + setText: function (txt) { + var opt = this.model.findTextInOptions(txt); + if (opt) { + this.setValue(opt["value"]); + } + return this; + }, + /** + * Helper setText async mode + * @param {*} txt + * @param {function} fn + * @return {DropDownView} + */ + setTextAsync: function (txt, fn) { + var that = this, + callback, + currentValue = this.model.get("data").value; + if (txt) { + this.previousValue = currentValue; + callback = function () { + var opt = that.model.findTextInOptions(txt); + if (opt && opt["value"]) { + that.changeHelperEvent(opt && opt["value"] ? opt["value"] : "", fn); + that.firstLoad = false; + } + that.switchSpinnerByControl(); + }; + this.switchControlBySpinner(); + if (txt !== currentValue && this.firstLoad) { + this.model.getRemoteOptions(callback); + } else { + callback(); + } + } + return this; + }, + /** + * Helper SetValueAsync + * @param {*} value + * @param {*} fn + * @return {DropDownView} + */ + setValueAsync: function (value, fn) { + var that = this, + callback, + currentValue = this.model.get("data").value; + if (value !== undefined) { + this.previousValue = currentValue; + callback = function () { + that.changeHelperEvent(value, fn); + that.firstLoad = false; + that.switchSpinnerByControl(); + }; + this.switchControlBySpinner(); + if (value !== currentValue && this.firstLoad) { + this.model.getRemoteOptions(callback); + } else { + callback(); + } + } + return this; + }, + /** + * SetValue, get Remote options, update the view and model but not trigger the dependencies without execute onchangecallbacks + * @param {*} value + * @param {*} fn + * @return {DropDownView} + */ + setValueWithoutTriggerDependencies: function (value, fn) { + var that = this, + dataOption, + criteria = "value"; + if (value !== undefined && value !== null) { + this.model.getRemoteOptions(function (data, err) { + dataOption = that.model.findOption(value, criteria); + that.model.setFirstOptionInData(); + if (dataOption) { + that.model.set("data", dataOption); + that.refreshHTML(); + } + if (_.isFunction(fn)) { + fn(); + } + }); + } + return this; + }, + /** + * Prevents bubble events in dropdown + * @param {*} event + * @return {DropDownView} + */ + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + /** + * Event focus in Select, trigger the remote options + * @return {DropDownView} + */ + focusSelectEvent: function () { + var value, that = this; + if (this.firstLoad && this.model.get("sql")) { + this.tagControl.empty(); + //Save the value older to set when exeecute query for remote options + value = this.model.get("data").value || ""; + this.model.set("showDependentSpinners", false); + this.model.getRemoteOptions(function (data, err) { + that.tagControl.val(value); + that.switchSpinnerByControl(); + }); + if (PMDynaform.core.ProjectMobile) { + this.model.trigger("change:options"); // Only display with old data in dropdown + } + } + return this; + }, + /** + * Change the hidden view in Dropdown field + * @return {DropDownView} + */ + changeHidden: function () { + var data = this.model.get("data"), + hiddenInput = this.tagHiddenToLabel; + if (data.hasOwnProperty("label")) { + hiddenInput.val(data.label); + } + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + dependencyDidUpdateView: function () { + this.changeHidden(); + this.switchSpinnerByControl(); + this.validate(); + }, + /** + * Execute the change callback on view + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + if (paramsValue.current !== paramsValue.previous) { + if (_.isFunction(this.onChangeCallback)) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + } + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + this.onFieldAssociatedHandler(); + this.switchSpinnerByControl(); + }, + setData: function (data) { + var value, label; + if (this.model.get("type") !== "submit" && this.model.get("type") !== "button" && this.model.get("type") !== "panel") { + if (this.model.get("type") === "label") { + this.setValue(data); + } else { + value = data["value"]; + this.setValue(value); + } + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.DropdownR", DropDownView); + +}()); +(function () { + var RadioView = PMDynaform.view.Field.extend({ + clicked: false, + previousValue: null, + template: _.template($("#tpl-radio").html()), + templateOptions: _.template($("#tpl-radio-options").html()), + existHTML: false, + events: { + "change input": "changeRadioEvent", + "keydown input": "preventEvents" + }, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + this.form = options.form ? options.form : null; + this.previousValue = this.getValue(); + // this property have a control of formulas field + this.formulaFieldsAssociated = []; + this.model.on("change:options", this.redrawOptions, this); + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + }, + /** + * Prevent propagation + * @param {*} event + * @returns {RadioView} + */ + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallback function + * @param fn + * @returns {RadioView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Render the view + * @returns {RadioView} + */ + render: function () { + this.existHTML = true; + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint")) { + this.enableTooltip(); + } + this.setValueToDomain(); + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='radio']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.$el.find(".content-print").text(this.getText()); + this.tagControl = this.$el.find(".pmdynaform-radio-items"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Validate the model and update the view with the validators + * @returns {RadioView} + */ + validate: function () { + this.model.set({}, { validate: true }); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".pmdynaform-control-radio-list").parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + /** + * Update accessibility HTML attributes + * @param {Object} params + * @chainable + */ + updateAccessibility: function (params) { + if (this.model.get("ariaLabelVisible")) { + this.$el.find("input[type='radio']").removeAttr("aria-label"); + params.tagOption.attr("aria-label", params.ariaLabel); + } + return this; + }, + /** + * Gets the html control using its class identifier + * @returns {Object} + */ + getHTMLControl: function () { + return this.$el.find(".pmdynaform-control-radio-list"); + }, + /** + * Helper getText + * @returns {Object} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Helper getValue + * @returns {Object} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Render the options model + * @returns {RadioView} + */ + renderOptions: function () { + var htmlOptions, + contendControl, + config; + contendControl = this.$el.find(".pmdynaform-radio-items"); + contendControl.empty(); + + if (_.isArray(this.model.get("options"))) { + config = { + name: this.model.get("name"), + id: this.model.get("id"), + type: this.model.get('type'), + namespace: this.model.get("namespace"), + disabled: this.model.get("disabled"), + options: this.model.get("options") + }; + htmlOptions = this.templateOptions(config); + contendControl.append(htmlOptions); + } + return this; + }, + /** + * Returns the html control + * @returns {*} + */ + getControl: function () { + return this.$el.find("input[type='radio']"); + }, + /** + * redrawOptions, Draw component options + * @chainable + */ + redrawOptions: function () { + var data = this.model.get("data"); + if (this.existHTML) { + this.renderOptions(); + this.updateValueHiddenControl(data["label"] || ""); + } + return this; + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @returns {RadioView} + */ + changeRadioEvent: function (event, value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + }); + return this; + }, + /** + * When the source of change is a helper + * @param {*} value + * @param {*} fn + * @returns {RadioView} + */ + changeHelperEvent: function (value, fn) { + var that = this; + this.updateView(function () { + that.executeChangeCallback(); + if (_.isFunction(fn)) { + fn(); + } + }, value); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of checkgroup + * @param {*} value + * @param {*} fn + * @returns {RadioView} + */ + updateView: function (fn, value) { + var dt = { + value: "", + label: "" + } + dt = this.updateFieldView(value); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.validate(); + return this; + }, + /** + * Update the view radio items + * @param {*} value + * @returns {*} + */ + updateFieldView: function (value) { + var tagOption, option, selectedHTMLOption; + this.clicked = true; + if (typeof value !== "undefined") { + option = this.model.findOption(value, "value"); + if (option !== null) { + selectedHTMLOption = this.tagControl.find('input[type=radio][value="' + option.value + '"]'); + } + if (selectedHTMLOption && selectedHTMLOption.length) { + selectedHTMLOption[0].checked = true; + this.updateValueHiddenControl(option.label); + this.updateValueRadioControl(option.value); + } else { + this.tagControl.find('input[type=radio]').attr('checked', false); + option = {label: "", value: ""}; + this.model.set("data", option); + this.updateValueHiddenControl(option.label); + this.updateValueRadioControl(option.value); + } + this.$el.find(".content-print").text(this.model.get("data")["label"]); + } else { + tagOption = $(event.target); + value = tagOption.val(); + option = this.model.findOption(value, "value"); + if (option && option.value) { + this.$el.find(".content-print").text(option.label); + this.updateAccessibility({ ariaLabel: option.label, tagOption: tagOption }); + this.updateValueHiddenControl(option.label); + this.updateValueRadioControl(option.value); + } + } + if (option) { + this.clicked = false; + } + return option; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + dependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate").error && this.model.get("dependencyDidUpdate").error !== "abort") { + this.showQueryFailMessage(); + } + this.switchSpinnerByControl(); + this.validate(); + }, + /** + * Executes onChangeCallBack function + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + // For execute the formula field associated + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + this.onFieldAssociatedHandler(); + }, + /** + * Sets value and update previousValue + * @param value + * @returns {RadioView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Sets value and update previousValue + * @param value + * @returns {RadioView} + */ + setValueAsync: function (value, fn) { + var that = this, + currentValue = this.model.get("data").value; + if (value !== undefined) { + this.previousValue = currentValue; + that.changeHelperEvent(value, fn); + } + return this; + }, + /** + * Helper setText + * @param {*} txt + * @returns {RadioView} + */ + setText: function (txt) { + var opt = this.model.findTextInOptions(txt); + if (opt) { + this.setValue(opt["value"]); + } + return this; + }, + /** + * Helper setText async mode + * @param {*} txt + * @returns {RadioView} + */ + setTextAsync: function (txt, fn) { + var opt = this.model.findTextInOptions(txt); + if (opt) { + this.setValueAsync(opt["value"], fn); + } + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.RadioR", RadioView); +}()); + +(function () { + var SubmitView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-submit").html()), + events: { + "keydown": "preventEvents" + }, + tagControl: null, + tagLabel: null, + initialize: function () {}, + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + on: function (e, fn) { + var that = this; + if (this.tagControl.length) { + this.tagControl.on(e, function (event) { + fn(event, that); + event.stopPropagation(); + }); + } + return this; + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + this.tagControl = this.$el.find("button"); + this.tagLabel = this.$el.find("button span"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setValue: function (text) { + if (text) { + this.model.set("label", text); + this.tagLabel.text(text); + } + return this; + }, + getText: function () { + var label = this.model.get("label"); + return label? label : null; + }, + getValue: function () { + return this.model.getValue(); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Submit", SubmitView); +}()); +(function () { + var TextareaView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-textarea").html()), + validator: null, + keyPressed: false, + previousValue: "", + events: { + "change textarea": "changeInputEvent", + "keydown textarea": "refreshBinding" + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallback function + * @param fn {function} + * @returns {TextareaView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Initializes Textarea properties + * @param options + */ + initialize: function (options) { + // this property have a control of formulas field + this.form = options.form ? options.form : null; + this.formulaFieldsAssociated = []; + this.model.on("change:data", this.updateValueInput, this); + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + }, + /** + * Update the keypressed property + * @returns {TextareaView} + */ + refreshBinding: function () { + this.keyPressed = true; + return this; + }, + /** + * Updates the values in the inputs controls nodes + * @returns {TextareaView} + */ + updateValueInput: function () { + var textInput, hiddenInput; + textInput = this.$el.find("textarea"); + hiddenInput = this.$el.find("input[type='hidden']"); + if (this.model.get("data")) { + textInput.val(this.model.get("data")["label"]); + hiddenInput.val(this.model.get("data")["label"]); + } + return this; + }, + /** + * Render method + * @returns {TextareaView} + */ + render: function () { + var hidden, name; + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + } + this.previousValue = this.model.get("value"); + + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='textarea']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.$el.find(".content-print").text(this.model.get("data")["label"]); + this.tagControl = this.$el.find("textarea"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Validate the model and views validators + * @param {*} event + * @returns {TextareaView} + */ + validate: function (event) { + var originalValue; + originalValue = this.tagControl.val(); + this.model.set("validate", true); + this.model.attributes.value = originalValue; + this.model.validate(); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.tagControl.parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + this.keyPressed = false; + // For execute the formula field associated + this.onFieldAssociatedHandler(); + return this; + }, + /** + * Suscribe listeners in field + * @returns {TextareaView} + */ + on: function (e, fn) { + var that = this, + control = this.$el.find("textarea"); + + if (control) { + control.on(e, function (event) { + fn(event, that); + + event.stopPropagation(); + }); + } + + return this; + }, + /** + * Gets HTML textarea of the control + * @returns {*} + */ + getHTMLControl: function () { + return this.$el.find("textarea"); + }, + /** + * Calls setValue of the TextareaModel + * @param value + * @returns {TextareaView} + */ + setValue: function (value) { + if (value !== undefined && value !== null) { + this.previousValue = this.getValue(); + this.form.model.set("isSync", true); + this.model.setValue(value); + this.form.model.set("isSync", false); + } + return this; + }, + /** + * Gets label of data + * @returns {null} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Gets value of data + * @returns {*} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Returns the html control + * @returns {*} + */ + getControl: function () { + return this.$el.find("textarea"); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @returns {TextareaView} + */ + updateView: function (fn, val) { + var dt = { + value: "", + label: "" + } + dt = this.updateFieldView(val); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.validate(); + return this; + }, + /** + * Update the view and return the data to update the model + * @param {*} val + */ + updateFieldView: function (val) { + var label = "", + textInput = this.getControl(), + hiddenInput = this.$el.find("input[type='hidden']"); + if (val && val != "") { + textInput.val(val); + } + hiddenInput.val(textInput.val()); + this.$el.find(".content-print").text(textInput.val()); + this.clicked = false; + return { + value: textInput.val(), + label: textInput.val() + } + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @returns {TextareaView} + */ + changeInputEvent: function (event, value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + }); + return this; + }, + /** + * When the source of change is a helper + * @param {*} value + * @param {*} fn + * @returns {TextareaView} + */ + changeHelperEvent: function (value, fn) { + var dt, that = this; + this.tagControl.val(value); + dt = this.updateView(function () { + that.executeChangeCallback(); + if (_.isFunction(fn)) { + fn(); + } + }, value); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + dependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate").error && this.model.get("dependencyDidUpdate").error !== "abort") { + this.showQueryFailMessage(); + } + this.switchSpinnerByControl(); + }, + /** + * Executes onChangeCallBack function + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + if (this.model.get("group") === "grid" && this.onChangeCallbackOperation) { + if (typeof this.onChangeCallbackOperation === "function") { + this.onChangeCallbackOperation(); + } + } + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + this.onFieldAssociatedHandler(); + }, + /** + * Helper SetValueAsync + * @param {*} value + * @param {*} fn + * @returns {TextareaView} + */ + setValueAsync: function (value, fn) { + var that = this, + currentValue = this.model.get("data").value; + if (value !== undefined && currentValue.toString() !== value.toString()) { + this.previousValue = currentValue; + that.changeHelperEvent(value, fn); + } + return this; + }, + /** + * Helper SetValueAsync + * @param {*} value + * @param {*} fn + * @returns {TextareaView} + */ + setTextAsync: function (value, fn) { + var that = this, + currentValue = this.model.get("data").value; + if (value !== undefined) { + this.previousValue = currentValue; + that.changeHelperEvent(value, fn); + } + return this; + }, + /** + * Helper setValue + * @param {*} value + * @param {*} fn + * @returns {TextareaView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Helper setText + * @param {*} txt + * @returns {TextareaView} + */ + setText: function (txt) { + this.setValue(txt); + return this; + }, + /** + * SetValue, get Remote options, update the view and model but not trigger the dependencies without execute onchangecallbacks + * @param {*} value + * @param {*} fn + * @return {TextAreaView} + */ + setValueWithoutTriggerDependencies: function (value, fn) { + var that = this, + dataOption, + criteria = "value"; + if (value !== undefined && value !== null) { + this.model.getRemoteOptions(function (data, err) { + dataOption = that.model.findOption(value, criteria); + if (dataOption) { + that.updateFieldView(dataOption.value); + } else { + that.model.setFirstOptionInData(); + } + if (_.isFunction(fn)) { + fn(); + } + }); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.TextAreaR", TextareaView); +}()); + +(function () { + var TextView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-text").html()), + validator: null, + keyPressed: false, + fieldValid: [], + previousValue: null, + firstLoad: false, + formulaFieldsAssociated: [], + jsonData: {}, + spinner: null, + events: { + "change input": "changeInputEvent", + "keydown input": "refreshBinding" + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallBack function + * @param fn {function} + * @returns {TextView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Initializes field properties + * @param options {object} + */ + initialize: function (options) { + var that = this; + this.form = options.form ? options.form : null; + this.previousValue = this.model.get("value"); + this.formulaFieldsAssociated = []; + this.model.on("change:data", this.updateValueInput, this); + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + }, + /** + * Prevent Events + * @param {*} event + * @returns {TextView} + */ + refreshBinding: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + this.keyPressed = true; + return this; + }, + /** + * Merge remote options + * @param {*} remoteOptions + * @param {*} click + */ + mergeOptions: function (remoteOptions, click) { + var item; + if (remoteOptions.length) { + item = remoteOptions[0]; + if (item.hasOwnProperty("value")) { + this.model.setValue(item["value"]); + } else { + this.model.setValue(""); + } + } else { + this.model.setValue(""); + } + }, + /** + * Validate the view + * @param {*} event + * @param {*} b + * @param {*} c + * @returns {TextView} + */ + validate: function (event, b, c) { + this.keyPressed = true; + this.model.set("validate", true); + this.model.validate(); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.tagControl.parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + this.keyPressed = false; + return this; + }, + /** + * Executes formula associated + * @returns {TextView} + */ + onFieldAssociatedHandler: function () { + var i, + fieldsAssoc = this.formulaFieldsAssociated; + if (fieldsAssoc.length > 0) { + for (i = 0; i < fieldsAssoc.length; i += 1) { + if (fieldsAssoc[i].model.get("formulator") instanceof PMDynaform.core.Formula) { + this.model.addFormulaTokenAssociated(fieldsAssoc[i].model.get("formulator")); + this.model.updateFormulaValueAssociated(fieldsAssoc[i]); + } + } + } + return this; + }, + /** + * Turns text value to uppercase or lowercase + * @param val + * @returns {TextView} + */ + onTextTransform: function (val) { + var transformed, + transform = this.model.get("textTransform"), + availables = { + upper: function () { + return val.toUpperCase(); + }, + lower: function () { + return val.toLowerCase(); + }, + none: function () { + return val; + }, + capitalizePhrase: function () { + return val.charAt(0).toUpperCase() + val.slice(1); + }, + titleCase: function () { + return val.capitalize(); + } + }; + if (transform) { + transformed = (availables[transform]) ? availables[transform]() : availables["none"](); + this.$el.find("input[type='text']").val(transformed); + } + return this; + }, + /** + * Validates fields supported on formula + * @param fields + * @returns {{}} + */ + checkFieldsValidForFormula: function (fields) { + var validFields = ["text", "label", "dropdown", "suggest", "textarea", "radio"], + responseObject = {}, + itemField, + i; + for (i = 0; i < fields.length; i += 1) { + itemField = fields[i]; + if (validFields.indexOf(itemField.model.get("type")) > -1) { + responseObject[itemField.model.get("id")] = itemField; + } + } + return responseObject; + }, + /** + * Event to process the formula + * @param rows + * @returns {TextView} + */ + onFormula: function (rows) { + var fieldsList, + that = this, + allFieldsView, + formulaField = this.model.get("formula"), + idFields = {}, + fieldFormula, + fieldAdded = [], + group = this.model.get("group"); + fieldsList = group === "grid" ? rows : this.parent.items; + allFieldsView = (fieldsList instanceof Array) ? fieldsList : fieldsList.asArray(); + idFields = this.checkFieldsValidForFormula(allFieldsView); + fieldFormula = formulaField.replace(/\s/g, '').split(/[\-(,|+*/\)]+/); + if (this.model.get("group") === "grid") { + for (var k = 0; k < rows.length; k += 1) { + if (fieldFormula.indexOf(rows[k].model.get("id")) > -1) { + rows[k].onFieldAssociatedHandler(); + } + } + } + this.fieldValid = fieldFormula.filter(function existElement(element) { + var result = false; + if ((idFields[element] !== undefined) && ($.inArray(element, fieldAdded) === -1)) { + fieldAdded.push(element); + result = true + } + return result; + }); + //Insert the Formula object to fields selected + for (var obj = 0; obj < this.fieldValid.length; obj += 1) { + this.model.addFormulaFieldName(this.fieldValid[obj]); + idFields[this.fieldValid[obj]].formulaFieldsAssociated.push(that); + if (this.model.get("group") === "grid") { + if (idFields.hasOwnProperty(this.fieldValid[obj])) { + this.formulaFieldsAssociated.push(idFields[this.fieldValid[obj]]); + } + } + } + return this; + }, + /** + * Gets HTML input of the control + * @returns {*} + */ + getHTMLControl: function () { + return this.$el.find("input"); + }, + /** + * Render method + * @returns {TextView} + */ + render: function () { + var hidden, + name; + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + hidden.value = this.model.get("data").value; + } + if (this.model.get("group") === "form" && this.model.get("formula")) { + this.onFormula(); + } + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='text']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.$el.find(".content-print").text(this.getText()); + this.tagControl = this.$el.find("input[type='text']"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + this.onTextTransform(this.tagControl.val()); + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Gets label of data + * @returns {null} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Gets value of data + * @returns {*} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Gets HTML control + * @returns {*} + */ + getControl: function () { + return this.$el.find(":input:not([type=hidden])") //hidden is not considered + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @param {*} fn + * @param {*} val + * @returns {TextView} + */ + updateView: function (fn, val) { + var dt = { + value: "", + label: "" + } + this.form.model.set("rootField", this.model); + dt = this.updateFieldView(val); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.validate(); + return this; + }, + /** + * Update the field view :: if exist val, the execution comes from helper + * @param {*} val + * @returns {*} + */ + updateFieldView: function (val) { // ATTENTION:: With any change verify the fix with helpers, change input, the hidden update and the textTransform method + var textInput = this.getControl(), + hiddenInput = this.$el.find("input[type='hidden']"); + if (!val) { + // The execution comes from change in input + val = textInput.val(); + } + this.onTextTransform(val); + hiddenInput.val(val); + this.$el.find(".content-print").text(textInput.val()); + this.clicked = false; + return { + value: val, + label: val + } + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @returns {TextView} + */ + changeInputEvent: function (event, value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + }); + return this; + }, + /** + * When the source of change is a helper + * @param {*} value + * @param {*} fn + * @returns {TextView} + */ + changeHelperEvent: function (value, fn) { + var dt, that = this; + this.tagControl.val(value); + dt = this.updateView(function () { + that.executeChangeCallback(); + if (_.isFunction(fn)) { + fn(); + } + }, value); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + dependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate").error && this.model.get("dependencyDidUpdate").error !== "abort") { + this.showQueryFailMessage(); + } + this.onFieldAssociatedHandler(); + this.switchSpinnerByControl(); + }, + /** + * Executes onChangeCallBack function + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + if (this.model.get("group") === "grid" && this.onChangeCallbackOperation) { + if (typeof this.onChangeCallbackOperation === "function") { + this.onChangeCallbackOperation(); + } + } + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + this.onFieldAssociatedHandler(); + }, + /** + * Helper SetValueAsync + * @param {*} value + * @param {*} fn + * @returns {TextView} + */ + setValueAsync: function (value, fn) { + var that = this, + currentValue = this.model.get("data").value; + if (value !== undefined && currentValue.toString() !== value.toString()) { + this.previousValue = currentValue; + that.changeHelperEvent(value, fn); + } + return this; + }, + /** + * Helper Set Text in Async mode + * @param {*} value + * @param {*} fn + * @returns {TextView} + */ + setTextAsync: function (value, fn) { + var that = this, + currentValue = this.model.get("data").value; + if (value !== undefined) { + this.previousValue = currentValue; + that.changeHelperEvent(value, fn); + } + return this; + }, + /** + * Helper setValue + * @param {*} value + * @returns {TextView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Helper setText + * @param {*} txt + * @returns {TextView} + */ + setText: function (txt) { + this.setValue(txt); + return this; + }, + /** + * Suscribe listeners to field + * @param {*} e + * @param {*} fn + * @returns {TextView} + */ + on: function (e, fn) { + var that = this, + control, + localEvents = { + "changeValues": "setOnChangeCallbackOperation" + }; + if (localEvents[e]) { + this[localEvents[e]](fn); + } else { + control = this.$el.find("input"); + if (control) { + control.on(e, function (event) { + fn(event, that); + event.stopPropagation(); + }); + } else { + throw new Error("Is not possible find the HTMLElement associated to field"); + } + } + return this; + }, + /** + * Updates the values in the inputs controls nodes + * @returns {TextView} + */ + updateValueInput: function () { + var currentLabel = this.getText(), + textInput = this.getControl(), + hiddenInput = this.$el.find("input[type='hidden']"); + textInput.val(currentLabel); + hiddenInput.val(currentLabel); + return this; + }, + /** + * Sets onChangeCallbackOperation this is used in functions (SUM, AVG) + * @param fn {function} + * @returns {TextView} + */ + setOnChangeCallbackOperation: function (fn) { + if (typeof fn === "function") { + this.onChangeCallbackOperation = fn; + } + return this; + }, + /** + * SetValue, get Remote options, update the view and model but not trigger the dependencies without execute onchangecallbacks + * @param {*} value + * @param {*} fn + * @return {TextView} + */ + setValueWithoutTriggerDependencies: function (value, fn) { + var that = this, + dataOption, + criteria = "value"; + if (value !== undefined && value !== null) { + this.model.getRemoteOptions(function (data, err) { + dataOption = that.model.findOption(value, criteria); + if (dataOption) { + that.updateFieldView(dataOption.value); + } else { + that.model.setFirstOptionInData(); + } + if (_.isFunction(fn)) { + fn(); + } + }); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.TextR", TextView); +}()); + +(function () { + var File = PMDynaform.view.Field.extend({ + item: null, + isIE: false, + template: _.template($("#tpl-file").html()), + filesLength: 0, + events: { + "click .pmdynaform-file-container .form-control": "onClickButton" + }, + /** + * Default function + */ + onChange: function () { + }, + initialize: function (options) { + var auxiliarValue = this.getText(); + this.form = options.form ? options.form : null; + this.model.addLabelToStack(auxiliarValue.length > 0 ? auxiliarValue[0] : ""); + if (_.isArray(this.model.get("value"))) { + this.filesLength = this.model.get("value").length; + } + if (!this.model.get("cleaned")) { + this.model.on("change:data", this.render, this); + } + }, + onClickButton: function (event) { + if (!PMDynaform.core.ProjectMobile) { + this.$el.find("input").trigger("click"); + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + /** + * Sets the callback onChange function + * @param callback + */ + setOnChange: function (callback) { + if (_.isFunction(callback)) { + this.onChange = callback; + } + return this; + }, + render: function () { + var that = this, + hidden, + nameDefault = this.model.get("name"), + name, + fileButton, + title = 'Allowed file extensions: '.translate() + this.model.get('extensions'), + link, + i, + data = this.model.get("data"), + label = data.label; + + this.$el.html(this.template(this.model.toJSON())); + fileButton = that.$el.find("button[type='button']"); + + if (PMDynaform.core.ProjectMobile) { + fileButton.attr("disabled", "disabled"); + } + link = this.$el.find("a.pmdynaform-control-file"); + fileButton.text(title); + fileButton[0].title = title; + hidden = this.$el.find("input[type='hidden']"); + + if (this.model.get("hint")) { + this.enableTooltip(); + } + + if (link.length > 0 && label.length > 0) { + for (i = 0; i < label.length; i += 1) { + link.children()[i].title = label[i]; + } + } + $(hidden).val(JSON.stringify(label)); + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = nameDefault.substring(0, nameDefault.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + hidden.value = this.model.get("value"); + } + if (nameDefault.trim().length === 0) { + this.$el.find("input[type='file']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.eventChangeFile(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + this.$el.find(".content-print").text(this.model.get("data")["label"]); + return this; + }, + /** + * Get File Type + * @param file + * @returns {{type: *, fileTarget: *}} + */ + getFileType: function (file) { + var type, + fileTarget; + if (file.files) { + if (file.files[0]) { + type = file.files[0].name.substring(file.files[0].name.lastIndexOf(".") + 1); + fileTarget = file.files[0].name; + } + } else { + if (file.value.trim().length) { + type = file.value.split("\\")[2].substring(file.value.split("\\")[2].lastIndexOf(".") + 1); + fileTarget = file.value; + } + } + return { + type: type, + fileTarget: fileTarget + } + }, + /** + * Check File + * @param file + * @returns {boolean} + */ + isValid: function (file) { + var validated = false, + maxSize, + type, + that = this, + errorType = {}, + extensions = this.model.get("extensions"), + getType = that.getFileType(file), + validatorModel = this.model.get('validator'), + tagFile = this.$el.find("input[type='file']")[0], + fileButton = that.$el.find("button[type='button']"), + title = 'Allowed file extensions: '.translate() + extensions, + maxSizeInt = parseInt(this.model.get("size"), 10), + sizeUnity = this.model.get("sizeUnity"); + + extensions = _.isString(extensions) ? extensions.toLowerCase() : ""; + type = (_.isObject(getType) && _.isString(getType.type)) ? getType.type.toLowerCase() : ""; + + if (this.model.get("sizeUnity").toLowerCase() !== "kb") { + maxSize = maxSizeInt * 1024; + } else { + maxSize = maxSizeInt; + } + if (extensions === "*" || extensions === ".*") { + validated = true; + } else { + if (extensions.indexOf(type) > -1) { + validated = true; + } else { + errorType = { + type: 'support', + message: 'The file extension is not supported. Supported extension(s): ' + + extensions + }; + validatorModel.set('fileOnly', errorType); + fileButton.text(title); + fileButton[0].title = title; + validated = false; + } + } + if (validated && file.files) { + if (file.files[0] && (file.files[0].size / 1024 <= maxSize)) { + validated = true + } else { + errorType = { + type: 'size', + message: "The file size exceeds the limit. Max allowed limit is: ".translate() + maxSizeInt + sizeUnity + }; + validatorModel.set('fileOnly', errorType); + fileButton.text(title); + fileButton[0].title = title; + validated = false; + } + } + if (validated) { + validatorModel.set('fileOnly', null); + this.updateValue(file.value); + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + this.$el.removeClass('has-warning has-feedback'); + } + } else { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + this.$el.removeClass('has-warning has-feedback'); + } + if (!this.model.isValid() && validatorModel.get('fileOnly') !== null) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + $(tagFile).prev().append(this.validator.el); + if (this.model.get('validator').get('fileOnly')) { + this.applyStyleWarning(); + this.validator.$el.children().removeClass('alert'); + this.validator.$el.children().addClass('warning'); + } + validatorModel.set('fileOnly', null); + this.model.set({value: []}, {silent: true}); + } + } + return validated; + }, + /** + * Validate Field File + * @param e + * @returns {boolean} + */ + validate: function (e) { + var tagFile = this.$el.find("input[type='file']")[0], + validated = true; + if (this.model.get("mode") == "view" || this.model.get("mode") == "disabled") { + return true; + } + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + this.$el.removeClass('has-warning has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + $(tagFile).prev().append(this.validator.el); + this.applyStyleError(); + this.model.get('validator').get('fileOnly', null); + validated = false; + this.model.attributes.valid = false; + } else { + validated = true; + this.model.attributes.valid = true; + } + } else { + this.model.attributes.valid = true; + } + return validated; + }, + /** + * Event change listener for update data file + * @returns {File} + */ + eventChangeFile: function () { + var that = this, + fileControl = this.$el.find("input[type='file']"), + file; + if (fileControl) { + fileControl.on("change", function (event) { + file = event.target; + if (file.value && that.isValid(file)) { + that.changeFile(file.files); + } + }); + } + return this; + }, + /** + * Change File and update data + * @param files + */ + changeFile: function (files) { + var nameFileLoad = "", + index = 0; + if (files && files.length > 0) { + nameFileLoad = files[index] ? files[index].name : nameFileLoad; + } + this.updateValueButton(nameFileLoad); + this.model.addLabelToStack(nameFileLoad); + this.updateHidden(nameFileLoad); + this.checkBinding(); + }, + /** + * Update Text Button + * @param nameFileLoad + * @returns {File} + */ + updateValueButton: function (nameFileLoad) { + var index = 0, + fileButton = this.$el.find("button[type='button']"); + if (_.isObject(fileButton) && !_.isEmpty(fileButton)) { + fileButton.text(nameFileLoad); + fileButton[index].title = nameFileLoad; + } + return this; + }, + /** + * Update Hidden Value + * @returns {File} + */ + updateHidden: function (nameFileLoad) { + var hidden, + nameFile = "[]", + id; + if (this.model.get("group") === "form") { + id = "form[" + this.model.get("name") + "_label]"; + hidden = this.$el.find("input[type='hidden'][id='" + id + "']"); + if (hidden) { + nameFile = "[" + '"' + nameFileLoad + '"' + "]"; + $(hidden).val(nameFile); + } + } + return this; + }, + /** + * Updates the values of the value of the model + * @param {string} pathFile the new path to update + * @return {this} + */ + updateValue: function (pathFile) { + var value = this.model.get("value"); + if (pathFile && _.isArray(value)) { + value.push(pathFile); + if (value.length === this.filesLength + 1) { + this.model.attributes.value = value; + } else { + value.splice(this.filesLength, 1); + this.model.attributes.value = value; + } + } + return this; + }, + /** + * Gets Text File + * @returns {null} + */ + getText: function () { + return this.model.getText(); + }, + /** + * Gets Value File + * @returns {*} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Gets Html Control of the File + * @returns {*} + */ + getControl: function () { + var htmlControl = this.$el.find("button").eq(0); + return htmlControl; + }, + /** + * Clear Content File + * @returns {File} + */ + clearContent: function () { + var controlFileHtml = this.$el.find(".pmdynaform-field-file"), + valueControlFile = this.model.getValue(), + appDocUID = this.model.getAppDocUID(), + name; + appDocUID = _.isArray(appDocUID) && !_.isEmpty(appDocUID) ? appDocUID[0] : null; + if (valueControlFile && controlFileHtml && controlFileHtml.length > 0 && this.model.get("mode") !== "view") { + name = this.createNameForHidden(); + this.model.clearContent(); + this.clearDomFile(); + if (appDocUID) { + this.appendHiddenInput(name, appDocUID); + } + this.model.clearStackLabels(); + } + return this; + }, + /** + * Clear DOM File Control + */ + clearDomFile: function () { + var extension = this.model.get('extensions'), + text = 'Allowed file extensions: '.translate() + extension; + this.$el.find("input[type=file]").val(""); + this.$el.find("input[type=hidden]").val("[]"); + this.$el.find("button").text(text); + this.$el.find("button").prop("title", text); + }, + /** + * Append Hidden Fields + * @param name + * @param appDocUid + */ + appendHiddenInput: function (name, appDocUid) { + var hiddenDocUid = [], + hiddenVersion = [], + inputType = "hidden", + versionDefault = "1"; + hiddenDocUid = $("", { + name: name + "[appDocUid]", + type: inputType, + value: appDocUid + }); + hiddenVersion = $("", { + name: name + "[version]", + type: inputType, + value: versionDefault + }); + this.$el.append(hiddenDocUid); + this.$el.append(hiddenVersion); + }, + /** + * Create Name for Files Deleted + * @returns {string|*} + */ + createNameForHidden: function () { + var varName = "form[__VARIABLE_DOCUMENT_DELETE__]", + idFile; + idFile = this.model.get("id"); + varName = varName + "[" + idFile + "]"; + return varName; + }, + /** + * Executes onChange function + */ + checkBinding: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.model.getCurrentNameFile(), + previous: this.model.getPreviousNameFile() + }; + if (paramsValue.current !== paramsValue.previous) { + this.onChange(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + } + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.File", File); +}()); + +(function () { + var CheckGroupView = PMDynaform.view.Field.extend({ + item: null, + template: _.template($("#tpl-checkgroup").html()), + templateOptions: _.template($("#tpl-checkgroup-options").html()), + previousValue: null, + firstLoad: false, + /** + * @param {boolean} existHTML: If html exists the value changes to true + */ + existHTML: false, + events: { + "change input": "changeSelectEvent", + "keydown input": "preventEvents" + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallback function + * @param fn {function} + * @returns {CheckGroupView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + this.form = options.form ? options.form : null; + this.model.on("change:options", this.redrawOptions, this); + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + }, + /** + * Stop the propagation events + * @param {*} event + * @returns {CheckGroupView} + */ + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + /** + * Render the field view + * @returns {CheckGroupView} + */ + render: function () { + var hidden, + name; + this.existHTML = true; + this.$el.html(this.template(this.model.toJSON())); + this.$el.find(".form-control").css({ + height: "auto" + }); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + this.setValueToDomain(); + this.$el.find("input[type='hidden']")[0].name = "form[" + this.model.get("name") + "_label]"; + this.setValueHideControl(); + this.previousValue = this.model.get("data").value; + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='checkbox']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.tagControl = this.$el.find(".pmdynaform-checkbox-items"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Update accessibility HTML attributes + * @param {Object} params + * @chainable + */ + updateAccessibility: function (params) { + var i; + if (this.model.get("ariaLabelVisible")) { + this.$el.find("input[type='checkbox']").removeAttr("aria-label"); + for (i = 0; i < params.data.values.length; i += 1) { + this.$el.find("input[type='checkbox'][value='" + PMDynaform.escapeSelector(params.data.labels[i]) + "']").attr("aria-label", params.data.labels[i]); + } + } + return this; + }, + /** + * Return the array of options checked + * @returns {*} + */ + getDataChecked: function () { + var dataChecked = { + values: [], + labels: [] + }, + checkedControls = this.$el.find("input[type='checkbox']:checked"); + checkedControls.each(function (index, element) { + dataChecked.values.push(element.value); + dataChecked.labels.push($(element).next().text()); + }); + return dataChecked; + }, + /** + * Verify if exist a check in options + * @param {*} item + * @returns {boolean} + */ + checkValueInOptions: function (item) { + var options, + i; + options = this.model.get("options"); + for (i = 0; i < options.length; i += 1) { + if (options[i]["value"] === item) { + return { + value: options[i]["value"], + label: options[i]["label"], + index: i + } + } + } + return false; + }, + /** + * Gets the html control using its class identifier + * @returns {Object} + */ + getHTMLControl: function () { + return this.$el.find(".pmdynaform-control-checkbox-list"); + }, + /** + * Update the input hidden + * @returns {CheckGroupView} + */ + setValueHideControl: function () { + var control; + control = this.$el.find("input[type='hidden']"); + $(control).val(this.model.get("data").label); + return this; + }, + /** + * Helper get Text + * @returns {*} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Helper getValue + * @returns {array} + */ + getValue: function () { + return this.model.get("data").value; + }, + /** + * Return the control html object + * @returns {*} + */ + getControl: function () { + var htmlControl = this.$el.find("input[type='checkbox']"); + return htmlControl; + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @returns {CheckGroupView} + */ + changeSelectEvent: function (event, value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + that.validate(); + }); + return this; + }, + /** + * When the source of change is a helper + * @param {*} value + * @param {*} fn + * @returns {CheckGroupView} + */ + changeHelperEvent: function (value, fn) { + var that = this; + this.updateView(function () { + that.executeChangeCallback(); + if (_.isFunction(fn)) { + fn(); + } + }, value); + return this; + }, + /** + * Execute the onChangeCallback after the executes de dependencies + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: JSON.stringify(this.model.get("data").value), + previous: JSON.stringify(this.previousValue) + }; + + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(this.model.get("data").value, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.model.get("data").value; + } + }, + /** + * Populate Checkgroup in print mode + * @param arrayItems + */ + populateItemsPrintMode: function (arrayItems) { + var i, + max, + containerPrint = this.$el.find(".content-print"); + containerPrint.empty(); + for (i = 0, max = arrayItems.length; i < max; i += 1) { + containerPrint.append("
  • " + arrayItems[i] + "
  • "); + } + + }, + /** + * Render options from model + * @returns {CheckGroupView} + */ + renderOptions: function () { + var htmlOptions, + contendControl, + config; + contendControl = this.$el.find(".pmdynaform-checkbox-items"); + contendControl.empty(); + + if (_.isArray(this.model.get("options"))) { + config = { + name: this.model.get("name"), + id: this.model.get("id"), + type: "checkbox", + namespace: this.model.get("namespace"), + disabled: this.model.get("disabled"), + options: this.model.get("options") + }; + htmlOptions = this.templateOptions(config); + contendControl.append(htmlOptions); + } + return this; + }, + /** + * redrawOptions, Draw component options + * @chainable + */ + redrawOptions: function () { + if (this.existHTML) { + this.renderOptions(); + } + return this; + }, + /** + * Method for validate the model and update the view with validators + * @returns {CheckGroupView} + */ + validate: function () { + this.model.set({ value: this.model.get("data").value }, { validate: true }); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".pmdynaform-control-checkbox-list").parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * method UPDATE very IMPORTANT + * Update only view of checkgroup + * @param {function} fn + * @param {string} value + * @returns {CheckGroupView} + */ + updateView: function (fn, value) { + var dt = { + value: "", + label: "" + } + dt = this.updateFieldView(value); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.validate(); + return this; + }, + /** + * Method for update the view in this field and return the data to update the model + * @param {*} values + * @returns {*} + */ + updateFieldView: function (values) { + var i, + dataChecked = { + values: [], + labels: [] + }, + item, + elements, + data, + inputsTag; + + if (values && _.isArray(values)) { + inputsTag = this.$el.find("input[type='checkbox']"); + inputsTag.attr("checked", false); + elements = this.$el.find("input[type='checkbox']"); + for (i = 0; i < values.length; i += 1) { + item = values[i]; + data = this.checkValueInOptions(item); + if (data) { + elements[data["index"]].checked = true; + dataChecked.values.push(data['value']); + dataChecked.labels.push(data['label']); + } + } + } else { + dataChecked = this.getDataChecked(); + } + this.updateAccessibility({ data: dataChecked }); + this.populateItemsPrintMode(this.getKeyLabels()); + this.$el.find("input[type='hidden']").val(JSON.stringify(dataChecked.labels)); + return { + value: dataChecked.values, + label: JSON.stringify(dataChecked.labels) + }; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + */ + dependencyDidUpdateView: function () { + this.validate(); + }, + /** + * Sets value and update previousValue + * @param value + * @returns {CheckGroupView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Sets value and update previousValue + * @param value + * @param callback + * @returns {CheckGroupView} + */ + setValueAsync: function (value, fn) { + if (value && $.isArray(value)) { + this.previousValue = this.getValue(); + this.changeHelperEvent(value, fn); + this.switchSpinnerByControl(); + } + return this; + }, + /** + * Set text + * @param txt + * @param fn + * @returns {CheckGroupView} + */ + setTextAsync: function (txt, fn) { + var options = this.model.get("options"), + arrayDataValue = [], arrayDataLabel = []; + for (i = 0; i < options.length; i += 1) { + options[i].selected = false; + if (txt.indexOf(options[i].label) > -1) { + options[i].selected = true; + arrayDataLabel.push(options[i].label); + arrayDataValue.push(options[i].value); + } + } + data = { + value: arrayDataValue, + label: arrayDataLabel + }; + this.setValueAsync(data["value"], fn); + return this; + }, + /** + * Return an array with the items selected. + * @returns {Array} + */ + getKeyLabels: function () { + var i, + j, + arrayItems = [], + values = this.getDataChecked().values, + options = this.model.get("options"); + for (i = 0; i < options.length; i += 1) { + for (j = 0; j < values.length; j += 1) { + if (values[j] === options[i].value) { + arrayItems.push(options[i].label); + } + } + } + return arrayItems; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.CheckGroupR", CheckGroupView); +}()); + +(function () { + var CheckBoxView = PMDynaform.view.Field.extend({ + item: null, + template: _.template($("#tpl-checkbox_yes_no").html()), + templateView: _.template($("#tpl-checkbox_view_mode").html()), + previousValue: null, + /** + * This property is a handler the events + * change input: when the change the control input type checkbox is fired the method handler event Listener + */ + events: { + "change input": "eventListener", + "keydown input": "preventEvents" + }, + firstLoad: false, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallback function + * @param fn + * @returns {CheckBoxView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + this.form = options.form ? options.form : null; + this.previousValue = this.getValue(); + this.model.on("change:value", this.eventListener, this); + this.model.on("change:toDraw", this.render, this); + }, + /** + * Listens to change event + * @param event + * @param value + */ + eventListener: function (event, value) { + this.onChange(event, value); + this.checkBinding(); + }, + /** + * Executes onChangeCallback function + * @returns {CheckBoxView} + */ + checkBinding: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: JSON.stringify(this.getValue()), + previous: JSON.stringify(this.previousValue) + }; + + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + }, + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + render: function () { + var hidden, + name; + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + this.setValueToDomain(); + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + } else { + this.$el.find("input[type='hidden']")[0].name = "form[" + this.model.get("name") + "_label]"; + } + if (this.model.get("options").length) { + this.$el.find("input[type='checkbox']").eq(0).data({ + value: this.model.get("options")[0]["value"], + label: this.model.get("options")[0]["label"] + }); + this.$el.find("input[type='checkbox']").eq(1).data({ + value: this.model.get("options")[1]["value"], + label: this.model.get("options")[1]["label"] + }); + } + this.setValueHideControl(); + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='checkbox']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.updateAccessibility({ ariaLabel: this.model.get("data")["label"] }); + this.$el.find(".content-print").text(this.model.get("data")["label"]); + this.tagControl = this.$el.find(".pmdynaform-checkbox-items"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.keyLabelControl = this.$el.find("input[type='hidden']"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Render checkbox only, it's works in grid mobile + */ + renderView: function () { + this.$el.html(this.templateView(this.model.toJSON())); + }, + /** + * Update accessibility HTML attributes + * @param {Object} params + * @chainable + */ + updateAccessibility: function (params) { + // for accessibilty arial label + if (this.model.get("ariaLabelVisible") && this.model.get("value") === "1") { + this.$el.find("input[type='checkbox']").eq(0).attr("aria-label", params.ariaLabel); + } else { + this.$el.find("input[type='checkbox']").eq(0).removeAttr("aria-label"); + } + return this; + }, + validate: function () { + this.model.set({}, { validate: true }); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".pmdynaform-control-checkbox-list").parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + /** + * This method is fired when the property value is changed + * @param event: is the event target tag + * @param value: is the change model when use set method + */ + onChange: function (event, value) { + this.updateValues(event, value); + if (!this.firstLoad) { + this.validate(); + } + return this; + }, + /** + * Gets the html control using its class identifier + * @returns {Object} + */ + getHTMLControl: function () { + return this.$el.find(".pmdynaform-control-checkbox-list"); + }, + setValueHideControl: function () { + var control; + control = this.$el.find("input[type='hidden']"); + if (this.model.get("dataType") === "boolean") { + $(control).val(this.model.get("data")["label"].toString()); + } else { + try { + $(control).val(JSON.stringify(this.model.get("data")["label"])); + } catch (e) { + console.error(e); + } + } + return this; + }, + updateValues: function (event, value) { + var controlHtml = this.$el.find("input[type='checkbox']"), + firstCheckbox = controlHtml.eq(0), + secondCheckbox = controlHtml.eq(1), + newValue = "0", + valuesForTrue = [1, true, "1", "true"], + data; + if (!value) { + if (firstCheckbox.prop("checked")) { + secondCheckbox.prop("checked", false); + newValue = "1"; + } else { + secondCheckbox.prop("checked", true); + newValue = "0"; + } + this.model.set({ value: newValue }, { silent: true }); + } else { + newValue = value; + if (valuesForTrue.indexOf(newValue) !== -1) { + firstCheckbox.prop("checked", true); + secondCheckbox.prop("checked", false); + } else { + firstCheckbox.prop("checked", false); + secondCheckbox.prop("checked", true); + } + } + this.updateDataModel(newValue); + data = this.model.get("data"); + firstCheckbox.val(data.value); + this.updateAccessibility({ ariaLabel: data.label }); + this.$el.find(".content-print").text(data.label); + this.$el.find("input[type='hidden']").val(data.label); + return this; + }, + /** + * Update data of checkbox model + * @param value + * @returns {CheckBoxView} + */ + updateDataModel: function (value) { + this.model.setData(value); + return this; + }, + /** + * Call to setValue of Model + * @param value + * @returns {CheckBoxView} + */ + setValue: function (value) { + this.previousValue = this.getValue(); + this.model.setValue(value); + this.firstLoad = false; + return this; + }, + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + getValue: function () { + return this.model.getValue(); + }, + getControl: function () { + var htmlControl = this.$el.find("input[type='checkbox']"); + return htmlControl; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.CheckBox", CheckBoxView); +}()); + +(function () { + var SuggestView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-suggest2").html()), + templateViewMode: _.template($("#tpl-label-extension").html()), + validator: null, + input: null, + makeFlag: false, + keyPressed: false, + pointerItem: 0, + orientation: "under", + stackItems: [], + stackRow: 0, + clicked: false, + firstLoad: true, + dirty: false, + jsonData: {}, + previousValue: "", + previousLabel: "", + prevValueprevValue: "", + prevValue: "", + numberOfOptions: 10, + containerOpened: false, + events: { + 'change': function (event) { + this.changeSuggestEvent(this.getDataSelect2('change')); + } + }, + stamp: null, + /** + * @param {Number} timeToWait - is the timer required to trigger an action data request + * if the value is 0, does not perform cancellation requests, if the value is not 0, + * this will be the time to waiting before making a request + */ + timeToWait: 0, + timeoutHandler: null, + xhr: null, + remoteOptions: [], + scrollTop: 0, + controlSuggest: null, + showVisibleElements: 5, + heightItem: 40, + /** + * @param {Array} - navigationKeys are valid navigation keys for selecting an item from the list + */ + navigationKeys: [38, 40, 13], + /** + * @param {Array} invalidEnterKeys - is the list of keyboard events captured incorrect not to execute queries + */ + invalidEnterKeys: [16, 17, 18, 20, 37, 39, 9], + /** + * This method is called for cancellation of writing board per share + * when the value of "timeToWait" is 0 this method is not call + * @private + */ + selectedListItem: null, + iconLoadingActive: true, + keyNavigatorPress: false, + /** + * Abort the xhr jquery + */ + _abortRequest: function () { + if (this.xhr) { + this.xhr.abort(); + } + clearTimeout(this.timeoutHandler); + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets onChangeCallback function + * @param fn {function} + * @returns {SuggestView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + var defaultLimit = 10; + this.form = options.form ? options.form : null; + this.formulaFieldsAssociated = []; + this.numberOfOptions = parseInt(this.model.get('resultsLimit')) || defaultLimit; + this.setTimeToWait(parseInt(this.model.get("delay"))); + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + }, + /** + * Get ID Select2 Control + * @returns {string} + */ + getIdSelect: function () { + return '#' + this.$el.find('select').attr('id').replace(/(:|\.|\[|\]|,|=|@)/g, "\\$1"); + }, + /** + * set the time to wait + * @param time + * @returns {boolean} + */ + setTimeToWait: function (time) { + if (!isNaN(time)) { + this.timeToWait = time; + } + return this; + }, + /** + * Updates value dom + * @returns {SuggestView} + */ + updateValueInput: function () { + var textInput, + hiddenInput; + textInput = this.$el.find("input[type='suggest']"); + hiddenInput = this.$el.find("input[type='hidden']"); + if (this.model.get("data")) { + textInput.val(this.model.get("data")["label"]); + hiddenInput.val(this.model.get("data")["value"]); + } + return this; + }, + /** + * Update the Hidden Input + * @param data + * @returns {SuggestView} + */ + updateHiddenInput: function (data) { + var hiddenInput = this.$el.find("input[type='hidden']"); + hiddenInput.val(data.label); + return this; + }, + /** + * Validate the model and validator views + * @param event + * @returns {SuggestView} + */ + validate: function (event) { + if (event && (event.which === 9) && (event.which !== 0)) { //tab key + this.keyPressed = true; + } + this.model.attributes.validator.set("valid", true); + this.model.validate(this.model.toJSON()); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error has-feedback'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find("select").parent().parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + /** + * Show the Suggest control + * @returns {SuggestView} + */ + render: function () { + var self = this; + if (this.model.get("mode") == "view") { + this.renderViewMode(); + } else { + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get('hint') !== '') { + this.enableTooltip(); + } + this.setNameHiddenControl(); + setTimeout(function () { + if (self.model.get('project')) { + $(self.getIdSelect()).select2(self.initializeSelect2Query()); + self.afterRenderSelect2(); + } + }, 0); + this.model.set({ "toDraw": false }, { silent: true }); + } + return this; + }, + /** + * Render the field in view Mode + */ + renderViewMode: function () { + this.$el.html(this.templateViewMode(this.model.toJSON())); + if (this.model.get('hint') !== '') { + this.enableTooltip(); + } + this.setNameHiddenControl(); + this.model.set({ "toDraw": false }, { silent: true }); + }, + /** + * Initialize select2 Query + * @returns {Object} + */ + initializeSelect2Query: function () { + var prj, + options, + variable, + uidModal = (this.model.get('nameModalSuggest')) ? $('#' + this.model.get('nameModalSuggest')) : null, + data = this.model.buildDataForQuery({}); + prj = this.model.get("project"); + if (this.model.get("group") === "grid") { + variable = this.model.get("columnName"); + } else { + if (this.model.get("variable") !== "") { + variable = this.model.get("variable"); + } else { + variable = this.model.get("id"); + } + } + return prj.webServiceManager.executeSuggestSelect2(data, variable, uidModal, this); + }, + /** + * Set in the control suggest the Data of the Case Data + * @returns {SuggestView} + */ + afterRenderSelect2: function () { + var data = this.model.get('data'), + id = this.getIdSelect(), + newOption; + this.previousValue = data.value || ''; + this.previousLabel = data.label || ''; + if (data.value !== '' && data.label !== '') { + if ($(id).find("option[value='" + data.value + "']").length) { + $(id).val(data.value); + } else { + this.setOption(data); + } + } + this.firstLoad = false; + this.$el.find(".content-print").text(this.previousLabel); + this.$el.find(".select2.select2-container").attr("aria-label", this.model.get("ariaLabel")); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Execute the executeSuggest query from Helpers + * @param data + * @param callback + * @returns {SuggestView} + */ + executeSelect2Query: function (data, callback) { + var dt, that = this; + this.model.executeQuery(data, function (response, err) { + if (response) { + dt = that.afterExecuteQuery(response, data); + that.updateViewFromHelper(function () { + that.executeChangeCallback(); + if (_.isFunction(callback)) { + callback(response); + } + }, dt); + } + }); + return this; + }, + /** + * Deselect the items in DOM html + * @returns {SuggestView} + */ + deselectItems: function () { + if (this.containerOpened) { + this.containerList.find("li").removeClass("pmdynaform-suggest-list-keyboard"); + } + return this; + }, + /** + * Return the html control + * @returns {*} + */ + getHTMLControl: function () { + return this.$el.find("input[type='suggest']"); + }, + /** + * Abstract method + * @returns {SuggestView} + */ + afterRender: function () { + return this; + }, + /** + * Update the name in hidden associated + * @returns {SuggestView} + */ + setNameHiddenControl: function () { + var hidden, + name; + if (this.el) { + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = "form" + name; + hidden.id = "form" + name; + } + } + return this; + }, + /** + * Set text + * @param value + * @returns {SuggestView} + */ + setText: function (value) { + if (value !== undefined && this.model.get("mode") !== "disabled") { + this.form.model.set("isSync", true); + this.executeSelect2Query({ + value: value, + typeSearch: 'text', + callback: this.afterExecuteQuery + }); + this.form.model.set("isSync", false); + } + return this; + }, + /** + * Set text async mode + * @param value + * @param fn + * @returns {SuggestView} + */ + setTextAsync: function (value, fn) { + if (value) { + this.executeSelect2Query({ + value: value, + typeSearch: 'text' + }, fn); + } + return this; + }, + /** + * Sets value in view + * @param value {string} + * @returns {SuggestView} + */ + setValue: function (value) { + this.form.model.set("isSync", true); + this.setValueAsync(value, null); + this.form.model.set("isSync", false); + return this; + }, + /** + * Sets value Async and updates previousValue + * @param value {string} + * @param fn {function} + * @returns {SuggestView} + */ + setValueAsync: function (value, fn) { + if (value !== undefined && this.model.get("mode") !== "disabled") { + this.previousValue = this.getValue(); + this.executeSelect2Query({ + value: value, + typeSearch: 'val' + }, fn); + } + return this; + }, + /** + * Callback executed after the server returns a response + * @param response + * @param xhr + * @param options + * @returns {SuggestView} + */ + afterExecuteQuery: function (response, options) { + var option = this._findOption(response, options.typeSearch, options.value), + id, + data; + data = this._forceSelectionIsConfigurated(option, options); + data = { + value: data.id, + label: data.text + }; + this.updateHiddenInput(data); + if (this.model.get("mode") != "view") { + id = this.getIdSelect(); + this.setOption(data); + } else { + this.model.set({ + data: data + }, { silent: true }); + this.model.set({ "toDraw": true }); + } + return data; + }, + /** + * Look up the value and the text + * @param response + * @param typeSearch + * @param value + * @returns {*} + * @private + */ + _findOption: function (response, typeSearch, value) { + var newOpt, + dataMerge = response.concat(this.model.get('options')); + if (typeSearch === 'text') { + //if the setText helper is executed + newOpt = _.find(dataMerge, function (item) { + var text = item.label || item.text; + return text.toUpperCase() === value.toUpperCase(); + }); + } else { + //if the setValue helper is executed + newOpt = _.find(dataMerge, function (item) { + return item.value.toUpperCase() === value.toUpperCase(); + }); + } + return newOpt; + }, + /** + * If forceSelection is configured + * @param option + * @param value + * @returns {{id: string, text: string}} + * @private + */ + _forceSelectionIsConfigurated: function (option, options) { + var dataOption = { + id: '', + text: '' + }, + value = options.value, + type = options.typeSearch; + if (this.model.get('forceSelection')) { + if (option) { + dataOption.id = option.value; + dataOption.text = option.text || option.label; + } + } else if (type !== "text") { + dataOption.id = (option) ? option.value : value; + dataOption.text = (option) ? option.text || option.label : value; + } else { + dataOption.id = (option) ? option.value : value; + dataOption.text = (option) ? option.text || option.label : value; + } + return dataOption; + }, + /** + * Update data model property + * @param {*} data + * @returns {SuggestView} + */ + setData: function (data) { + var dataObject; + if (typeof data === "object") { + dataObject = { + value: data['value'] !== undefined ? data['value'] : "", + label: data['label'] !== undefined ? data['label'] : "" + }; + this.setValue(data['value']); + this.render(); + } + return this; + }, + /** + * Helper getText + * @returns {*} + */ + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + /** + * Helper getValue + * @returns {*} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * Return the control object html + * @returns {*} + */ + getControl: function () { + return this.$el.find(".select2-selection__rendered"); + }, + /** + * PreparePostData, Prepares the additional data to execute the service to execute the query + * @returns data {object} + */ + preparePostData: function () { + var data; + data = this.jsonData || {}; + if (this.model.get("group") === "grid") { + data["field_id"] = this.model.get("columnName"); + } else { + data["field_id"] = this.model.get("id"); + } + if (this.model.get("form")) { + if (this.model.get("form").get("form")) { + data["dyn_uid"] = this.model.get("form").get("form").get("id"); + } else { + data["dyn_uid"] = this.model.get("form").get("id"); + } + } + return data; + }, + /** + * Get data control suggest + * @param type + * @returns {{label: string, value: string}} + */ + getDataSelect2: function (type) { + var dataSelected, + data, + index = 0, + id = this.getIdSelect(); + + dataSelected = ($(id).data('select2')) ? $(id).select2('data')[index] : null; + data = { + label: dataSelected ? dataSelected.text : '', + value: dataSelected ? dataSelected.id : '' + }; + if (!dataSelected) { + $(id).find("option").remove(); + } + return data; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @param fn + * @param val + * @returns {SuggestView} + */ + updateView: function (fn, val) { + var dt = { + value: "", + label: "" + } + dt = this.updateFieldView(val); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.onFieldAssociatedHandler(); + this.validate(); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @param fn + * @param dt + * @returns {SuggestView} + */ + updateViewFromHelper: function (fn, dt) { + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + this.validate(); + return this; + }, + /** + * Update view method and return a data to update the model + * @param {*} data + * @returns {*} + */ + updateFieldView: function (data) { + var id = this.getIdSelect(), + hiddenInput = this.$el.find("input[type='hidden']"); + //Update hidden input + hiddenInput.val(data.label); + //Update select2 + if (!data.value) { + $(id).val(null); + } + this.$el.find(".content-print").text(data.label); + this.keyNavigatorPress = false; + return data; + }, + /** + * When The select control change value + * @param {*} event + * @param {*} value + * @returns {SuggestView} + */ + changeSuggestEvent: function (value) { + var that = this, dt; + dt = this.updateView(function () { + that.executeChangeCallback(); + }, value); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of text + */ + dependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate").error && this.model.get("dependencyDidUpdate").error !== "abort") { + + } + this.setOption(this.model.get("data")); + this.onFieldAssociatedHandler(); + }, + /** + * Executes onChangeCallBack function + */ + executeChangeCallback: function () { + //If the key is not pressed, executes the render method + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + this.previousLabel = this.getText(); + } + this.onFieldAssociatedHandler(); + }, + /** + * Set option force in suggest + * @param {*} data + */ + setOption: function (data) { + var option = new Option(data.label, data.value, true, true); + $(this.getIdSelect()).empty().append(option); + $(this.getIdSelect()).trigger({ + type: 'change.select2', + params: { + data: { id: data.value, text: data.label } + } + }); + } + + }); + + PMDynaform.extendNamespace("PMDynaform.view.SuggestR", SuggestView); +}()); + +(function () { + var LinkView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-link").html()), + validator: null, + initialize: function (options) { + this.form = options.form ? options.form : null; + this.model.on("change", this.render, this); + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + this.$el.find(".content-print").text(this.model.get("data")["label"]); + this.tagControl = this.tagHiddenToLabel = this.$el.find(".pmdynaform-control-link span"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setText: function (value) { + if (value !== undefined) { + this.model.set("text", value); + } + return this; + }, + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : ""; + }, + updateValues: function (value) { + this.$el.find(".pmdynaform-control-link span").text(value); + this.model.set("data", { + value: value, + label: value + }); + return this; + }, + validationURL: function (url) { + return this.model.validationURL(url); + }, + reformatURL: function (url) { + return this.model.reformatURL(url); + }, + setHref: function (href) { + if (href !== undefined) { + this.model.setHref(href); + } + return this; + }, + setValue: function (value) { + return this.setHref(value); + }, + getValue: function () { + return this.model.getValue(); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Link", LinkView); +}()); + +(function () { + var Label = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-label").html()), + template_showLabels: _.template($("#tpl-label-fullOptions").html()), + validator: null, + singleControl: [], + fieldValid: [], + formulaFieldsAssociated: [], + initialize: function () { + this.formulaFieldsAssociated = []; + this.specialHiddens = ["dropdown", "radio", "suggest", "checkbox", "datetime"]; + this.model.on("change:value", this.eventListener, this); + this.model.on("change:fullOptions", this.updateViewControls, this); + this.model.on("change:toDraw", this.render, this); + this.initLanguage(); + }, + /** + * updateViewControls, redrawing the labels of the component, is call when the fulloptions is change + * @chainable + */ + updateViewControls: function () { + var labelSpan, + valueHidden = this.$el.find(".value-hidden"), + labelHidden = this.$el.find(".label-hidden"), + data = this.model.get("data"), + originalType = this.model.get("originalType"), + formControlContent = this.$el.find(".form-control"); + + labelSpan = this.$el.find(".label-" + originalType); + labelSpan.remove(); + labelSpan = this.template_showLabels({ + originalType: originalType, + fullOptions: this.model.get("fullOptions") + }); + formControlContent.prepend(labelSpan); + this.model.get("fullOptions"); + valueHidden.val(data["value"]); + labelHidden.val(data["label"]); + return this; + }, + eventListener: function (event) { + this.onChange(event); + this.onFieldAssociatedHandler(); + return this; + }, + /** + * On change handler + * @param {Object} event + * @chainable + */ + onChange: function (event) { + var newData, + originalType = this.model.get("originalType"), + data = this.model.get("data"); + switch (originalType) { + case "checkbox": + newData = this.model.getCheckBoxData(data.value); + break; + case "checkgroup": + newData = this.model.getCheckGroupData(data.value); + break; + case "dropdown": + newData = this.model.getDropDownData(data.value); + break; + case "datetime": + newData = this.model.getDateTimeData(data.value); + break; + case "radio": + newData = this.model.getRadioData(data.value); + break; + case "suggest": + newData = this.model.getSuggestData(data.value); + break; + default: + newData = this.model.getTextBoxData(data.value); + break; + } + if (newData["label"] !== undefined && newData["label"] !== null) { + this.model.setFullOptions(newData["label"]); + } + return this; + }, + /** + * Set the default option or first option. + * @returns {Label} + */ + setFirstOption: function () { + var data = this.model.get("data"), + optionsArray = this.model.get("options"), + defaultValue = this.model.get("defaultValue"), + fullOptions = this.model.get("fullOptions"), + optionDefault = data, + auxiliarOption, + index = 0; + if (fullOptions.length && !fullOptions[index]) { + if (_.isArray(optionsArray) && optionsArray.length) { + if (defaultValue) { + auxiliarOption = this.model.findOption(defaultValue, "value"); + optionDefault = { + value: auxiliarOption.value, + label: auxiliarOption.label + }; + } else { + optionDefault = { + value: optionsArray[index].value, + label: optionsArray[index].label + } + } + } + this.model.set({ "data": optionDefault }, { silent: true }); + this.model.set({ "value": optionDefault.value }, { silent: true }); + this.model.set("fullOptions", [optionDefault.label]); + } + return this; + }, + render: function () { + var hidden, name, newDateTime, $textAreaContent, msie; + this.setFirstOption(); + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + if (this.model.get("originalType") === "datetime") { + newDateTime = this.renderDataTimeViewMode(); + } + this.setDataInHiddenControls(this.model.get("originalType")); + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("]"); + hidden.name = hidden.id = "form" + name; + + hidden.name = hidden.id = "form" + name; + hidden = this.$el.find("input[type = 'hidden']")[1]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + } else { + this.onFormula(); + } + this.tagControl = this.$el.find("input[type='hidden']").eq(0); + this.keyLabelControl = this.$el.find("input[type='hidden']").eq(1); + if (newDateTime) { + this.keyLabelControl.val(newDateTime); + this.model.set('keyValue', newDateTime); + } + + $textAreaContent = this.$el.find("span.label-textarea"); + if ($textAreaContent.length) { + $textAreaContent.html(this.model.get('value').replace(/(?:\r\n|\r|\n)/g, "
    ")); + } + // Append Spinner + this.addSpinnerHTML(); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * render datetime field at view mode + * + **/ + renderDataTimeViewMode: function () { + var formatedText = '', data; + data = this.model.get('data'); + if (this.model.get("format") && data['value']) { + formatedText = moment(data['value']).format(this.model.get('format')); + } else { + formatedText = this.model.get("data")['label']; + } + this.$el.find(".label-" + this.model.get("originalType")).text(formatedText); + return formatedText; + }, + setDataInHiddenControls: function (type) { + type = (type && type.trim()) || null; + if (type && this.specialHiddens.indexOf(type) !== -1) { + switch (type) { + case 'suggest': + case 'dropdown': + case 'radio': + case 'datetime': + this.$el.find("input[type='hidden']")[1].value = this.model.get("data")["label"]; + break; + } + this.$el.find("input[type='hidden']")[0].value = this.model.get("data")["value"]; + } + return this; + }, + /** + * Executes formula associated + * @returns {Label} + */ + onFieldAssociatedHandler: function () { + var i, + fieldsAssoc = this.formulaFieldsAssociated; + if (fieldsAssoc.length > 0) { + for (i = 0; i < fieldsAssoc.length; i += 1) { + if (fieldsAssoc[i].model.get("formulator") instanceof PMDynaform.core.Formula) { + this.model.addFormulaTokenAssociated(fieldsAssoc[i].model.get("formulator")); + this.model.updateFormulaValueAssociated(fieldsAssoc[i]); + } + } + } + return this; + }, + setOnChangeCallbackOperation: function (fn) { + if (typeof fn === "function") { + this.onChangeCallbackOperation = fn; + } + return this; + }, + on: function (e, fn) { + var that = this, + control, + localEvents = { + "changeValues": "setOnChangeCallbackOperation" + }; + if (localEvents[e]) { + this[localEvents[e]](fn); + } else { + control = this.$el.find("input"); + if (control) { + control.on(e, function (event) { + fn(event, that); + event.stopPropagation(); + }); + } else { + throw new Error("Is not possible find the HTMLElement associated to field"); + } + } + return this; + }, + /** + * Validates fields supported on formula + * @param fields + * @returns {{}} + */ + checkFieldsValidForFormula: function (fields) { + var validFields = ["text", "label", "dropdown", "suggest", "textarea", "radio"], + responseObject = {}, + itemField, + i; + for (i = 0; i < fields.length; i += 1) { + itemField = fields[i]; + if (validFields.indexOf(itemField.model.get("type")) > -1) { + responseObject[itemField.model.get("id")] = itemField; + } + } + return responseObject; + }, + /** + * Event to process formula + * @param rows + * @returns {Label} + */ + onFormula: function (rows) { + var fieldsList, + that = this, + allFieldsView, + formulaField = this.model.get("formula"), + idFields = {}, + fieldFormula, + fieldAdded = [], + group = this.model.get("group"); + fieldsList = group === "grid" ? rows : this.parent.items; + allFieldsView = (fieldsList instanceof Array) ? fieldsList : fieldsList.asArray(); + idFields = this.checkFieldsValidForFormula(allFieldsView); + fieldFormula = formulaField.replace(/\s/g, '').split(/[\-(,|+*/\)]+/); + if (this.model.get("group") === "grid") { + for (var k = 0; k < rows.length; k += 1) { + if (fieldFormula.indexOf(rows[k].model.get("id")) > -1) { + rows[k].onFieldAssociatedHandler(); + } + } + } + this.fieldValid = fieldFormula.filter(function existElement(element) { + var result = false; + if ((idFields[element] !== undefined) && ($.inArray(element, fieldAdded) === -1)) { + fieldAdded.push(element); + result = true + } + return result; + }); + //Insert the Formula object to fields selected + for (var obj = 0; obj < this.fieldValid.length; obj += 1) { + this.model.addFormulaFieldName(this.fieldValid[obj]); + idFields[this.fieldValid[obj]].formulaFieldsAssociated.push(that); + if (group === "grid") { + if (idFields.hasOwnProperty(this.fieldValid[obj])) { + this.model.attributes.formulaAssociatedObject.push(idFields[this.fieldValid[obj]]); + } + } + } + return this; + }, + getValue: function () { + return this.model.getValue(); + }, + setValue: function (value) { + this.model.setValue(value); + return this; + }, + setText: function (text) { + var originalType = this.model.get("originalType"), + newData; + switch (originalType) { + case "text": + case "textarea": + newData = this.model.getTextBoxData(text); + break; + case "suggest": + newData = this.model.getSuggestData(text); + break; + case "dropdown": + newData = this.setDropdownText(text); + break; + case "checkgroup": + newData = this.setChekgroupTexts(text); + break; + case "checkbox": + newData = this.setCheckboxText(text); + break; + case "radio": + newData = this.setRadioText(text); + break; + case "datetime": + newData = this.model.getDateTimeData(text); + break; + } + if (newData) { + this.model.setNewData(newData); + } + return this; + }, + setRadioText: function (text) { + var data; + data = this.model.findOption(text, "label"); + return data ? data : { label: "", value: "" }; + }, + setDropdownText: function (text) { + var data; + data = this.model.findOption(text, "label"); + return data ? data : { label: "", value: "" }; + }, + setChekgroupTexts: function (texts) { + var data, + resultOptions; + if (_.isArray(texts)) { + resultOptions = this.model.findOptions(texts, "label"); + data = this.model.returnOptionsData(resultOptions); + } + return { + value: data["value"], + label: data["label"] + }; + }, + setCheckboxText: function (text) { + var data; + data = this.model.findOption(text, "label"); + return data ? data : { label: "", value: "" }; + }, + updateTextData: function (data) { + if (data && data.hasOwnProperty("value")) { + this.model.set("data", { + value: data["value"], + label: data["value"] + }); + this.model.set("value", data["value"]); + } else { + this.model.set("value", ""); + this.model.set("data", { value: "", label: "" }); + } + return this; + }, + updateDropdownData: function (data) { + var options = this.model.get("options"); + if (data === null) { + if (options.length > 0) { + data = { + value: options[0].value, + label: options[0].label + } + } else { + data = { + value: "", + label: "" + } + } + } + this.model.setData(data); + return this; + }, + updateCheckgroupData: function (data) { + if (!_.isArray(data['value']) || data['value'].length === 0) { + data = { + value: [], + label: JSON.stringify([]) + } + } + this.model.setData(data); + return this; + }, + updateRadioData: function (data) { + var options = this.model.get("options"); + if (!data) { + data = { + value: "", + label: "" + } + } + this.model.setData(data); + return this; + }, + findDefValueInOptions: function (defVal) { + var data = { + value: "", + label: "" + }, + originalType, + i, + items, + options, + firstOption = 0, + option; + originalType = this.model.get("originalType"); + switch (originalType) { + case 'checkgroup': + items = this.model.findOptions(defVal, "value"); + if (_.isArray(items)) { + data = { + value: [], + label: [] + }; + for (i = 0; i < items.length; i += 1) { + data["value"].push(items[i].value); + data["label"].push(items[i].label); + } + data["label"] = JSON.stringify(data["label"]); + } + break; + case 'radio': + option = this.model.findOption(defVal, "value"); + if (option) { + data = option; + } + break; + case 'text': + case 'textarea': + case 'dropdown': + option = this.model.findOption(defVal, "value"); + if (option) { + data = option; + } else { + options = this.model.get("options"); + if (_.isArray(options) && options.length) { + data = options[firstOption] || data; + } + } + break; + } + return data; + }, + mergeOptions: function (remoteOptions) { + var data, + originalType = this.model.get("originalType") || ""; + if (_.isArray(remoteOptions) && remoteOptions.length) { + this.model.mergeOptions(remoteOptions); + data = this.findDefValueInOptions(this.model.get("defaultValue")); + switch (originalType) { + case "text": + case "textarea": + case "suggest": + this.updateTextData(data); + break; + case "dropdown": + this.updateDropdownData(data) + break; + case "checkgroup": + this.updateCheckgroupData(data); + break; + case "radio": + this.updateRadioData(data); + break; + } + } else { + this.model.set("data", { value: "", label: "" }); + this.model.set("value", ""); + } + return this; + }, + + /** + * Set data and set value + * @param data + * @returns {Label} + */ + setData: function (data) { + var value; + this.model.set("data", data); + if (this.model.get("originalType") === "suggest") { + this.setValue(data); + } else { + this.setValue(data["value"]); + } + return this; + }, + getText: function () { + var data = this.model.get("data"); + return data && data["label"] ? data["label"] : null; + }, + /** + * Gets the html control using its class identifier + * @returns {Object} + */ + getHTMLControl: function () { + return this.$el.find(".pmdynaform-label-options"); + }, + /** + * SetValue, get Remote options, update the view and model but not trigger the dependencies without execute onchangecallbacks + * @param {*} value + * @param {*} fn + * @return {Label} + */ + setValueWithoutTriggerDependencies: function (value, fn) { + var that = this, + dataOption; + if (value !== undefined && value !== null) { + this.model.getRemoteOptions(function (data, err) { + dataOption = that.findDefValueInOptions(value) + if (dataOption) { + that.updateFieldView(dataOption); + } else { + that.model.setFirstOptionInData(); + } + if (_.isFunction(fn)) { + fn(); + } + }); + } + return this; + }, + /** + * Update the field view + * @param {Object} data + * @returns {Label} + */ + updateFieldView: function (data) { + var originalType = this.model.get("originalType") || ""; + switch (originalType) { + case "text": + case "textarea": + case "suggest": + this.updateTextData(data); + break; + case "dropdown": + this.updateDropdownData(data) + break; + case "checkgroup": + this.updateCheckgroupData(data); + break; + case "radio": + this.updateRadioData(data); + break; + } + this.model.set("fullOptions", [this.model.get("data").label]); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.Label", Label); +}()); + +(function () { + var Title = PMDynaform.view.Field.extend({ + template: null, + validator: null, + etiquette: { + title: _.template($("#tpl-label-title").html()), + subtitle: _.template($("#tpl-label-subtitle").html()) + }, + tagControl: null, + tagLabel: null, + initialize: function () { + this.template = this.etiquette[this.model.get("type")]; + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("type") === "title") { + this.tagControl = this.$el.find("h4"); + } else { + this.tagControl = this.$el.find("h5"); + } + this.tagLabel = this.tagControl.find("p span"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setValue: function (text) { + if (text !== undefined) { + this.model.set("label", text); + this.tagLabel.text(text); + } + }, + /** + * SetValueAsync works as SetValue + * @param text + * @param fn + */ + setValueAsync: function (text, fn) { + if (text !== undefined) { + this.model.set("label", text); + this.tagLabel.text(text); + if (_.isFunction(fn)) { + fn(); + } + } + }, + getText: function () { + var label = this.model.get("label"); + return label ? label : null; + }, + getValue: function () { + return this.model.getValue(); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Title", Title); +}()); + +(function () { + var Empty = Backbone.View.extend({ + item: null, + template: _.template($("#tpl-empty").html()), + render: function () { + this.$el.html(this.template(this.model.toJSON())); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.Empty", Empty); + +}()); +(function () { + var HiddenView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-hidden").html()), + onChangeCallback: null, + initialize: function (options) { + this.model.on("change:value", this.eventListener, this); + }, + /** + * + * @param fn + * @returns {HiddenView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Listener change value + */ + eventListener: function () { + this.checkBinding(); + }, + /** + * Execute onchangecallback + * @returns {HiddenView} + */ + checkBinding: function () { + var form = this.parent; + if (typeof this.onChangeCallback === "function") { + this.onChangeCallback(this.getValue(), this.model.previous("value")); + } + if (form && typeof form.onChangeCallback === "function") { + form.onChangeCallback(this.model.get("id"), this.getValue(), this.model.previous("value")); + } + return this; + }, + render: function (isConsole) { + var data = {}, + hidden; + if (isConsole) { + data["value"] = this.model.get("value"); + data["label"] = this.model.get("value"); + this.model.attributes.data = data; + } + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("group") === "grid") { + hidden = this.$el.find("input[type = 'hidden']")[1]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + hidden.name = hidden.id = "form" + name; + hidden.value = this.model.get("value"); + } + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='hidden']").attr("name", ""); + } + this.tagControl = this.$el.find("input[type='hidden']").eq(0); + this.keyLabelControl = this.$el.find("input[type='hidden']").eq(1); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']").eq(1); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Sets value and data + * @param value + * @returns {HiddenView} + */ + setValue: function (value) { + this.model.setValue(value); + this.updateValues(value); + return this; + }, + /** + * Updates dom values + * @param value + * @returns {HiddenView} + */ + updateValues: function (value) { + if (value !== undefined && value !== null) { + this.tagControl.val(value); + this.$el.find("input[type='hidden']").eq(1).val(value); + } + return this; + }, + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + getValue: function () { + return this.model.getValue(); + }, + getControl: function () { + var htmlControl = this.$el.find("input[type='hidden']").eq(0); + return htmlControl; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.Hidden", HiddenView); + +}()); + +(function () { + var ImageView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-image").html()), + events: { + "keydown": "preventEvents" + }, + initialize: function () { + this.model.on("change", this.render, this); + }, + preventEvents: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + return this; + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + this.tagControl = this.tagHiddenToLabel = this.$el.find("img"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + getSrc: function () { + return this.model.get("src"); + }, + setSrc: function (value) { + this.model.set("src", value); + this.tagControl.attr("src", value); + return this; + }, + setValue: function (phat) { + if (phat !== undefined) { + this.setSrc(phat); + this.model.attributes.value = phat; + this.model.set("data", { + value: phat, + label: phat + }); + } + return this; + }, + getText: function () { + return this.getSrc(); + }, + getValue: function () { + return this.model.getValue(); + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.Image", ImageView); + +}()); + +(function () { + var SubFormView = Backbone.View.extend({ + template: _.template($('#tpl-form').html()), + formView: null, + defaultElement: "empty", + availableElements: null, + parent: null, + /** + * Sets Onchange function of the subForm. + * @param callback + * @returns {SubFormView} + */ + setOnChange: function (callback) { + this.formView.setOnChange(callback); + return this; + }, + /** + * Initialize sproperties + * @param options + */ + initialize: function (options) { + var availableElements = [ + "text", + "textarea", + "checkbox", + "checkgroup", + "radio", + "dropdown", + "button", + "datetime", + "fieldset", + "suggest", + "link", + "hidden", + "title", + "subtitle", + "label", + "empty", + "file", + "image", + "grid", + "panel", + "videomobile", + "audiomobile", + "imagemobile", + "signature", + "scannercode", + "multiplefile", + "location" + ]; + this.availableElements = availableElements; + if (options.project) { + this.project = options.project; + } + this.checkItems(); + this.makeSubForm(); + }, + checkItems: function () { + var i, + j, + newItems = [], + row = [], + json = this.model.toJSON(); + + if (json.items) { + for (i = 0; i < json.items.length; i += 1) { + row = []; + for (j = 0; j < json.items[i].length; j += 1) { + if (json.items[i][j].type) { + if ($.inArray(json.items[i][j].type.toLowerCase(), this.availableElements) >= 0) { + row.push(json.items[i][j]); + } + } else { + json.items[i][j].type = this.defaultElement; + row.push(json.items[i][j]); + } + } + if (row.length > 0) { + newItems.push(row); + } + } + } + + json.items = newItems; + this.model.set("modelForm", json); + + return this; + }, + makeSubForm: function () { + var panelmodel = new PMDynaform.model.FormPanel(this.model.get("modelForm")); + this.model.set("formModel", panelmodel); + this.formView = new PMDynaform.view.FormPanel({ + model: panelmodel, + project: this.project + }); + + return this; + }, + validate: function (event) { + this.isValid(event); + }, + getItems: function () { + return this.formView.items.asArray(); + }, + /** + * Returns all the fields in the subformform including the ones in any nested subform. + * @returns {Array.PMDynaform.view.Field} + */ + getAllFields: function () { + var items = this.getItems(), + subformFields = [], + fields; + + fields = items.filter(function (i) { + // The second expression is necessary since Grid for Mobile doesn't inherit from PMDynaform.view.Field. + if (i instanceof PMDynaform.view.Field + || (PMDynaform.view.GridMobile && i instanceof PMDynaform.view.GridMobile)) { + return true; + } else if (i instanceof PMDynaform.view.SubForm) { + subformFields = subformFields.concat(i.getAllFields()); + } + return false; + }); + + return fields.concat(subformFields); + }, + /** + * Validate and set the subform valid property. + * @param event + * @returns {boolean} + */ + isValid: function (event) { + var i, + formValid = true, + formItems = this.formView.getFields(), + item, + itemField; + + if (_.isArray(formItems)) { + for (i = 0; i < formItems.length; i += 1) { + item = formItems[i]; + if (item.validate) { + if (item.firstLoad) { + item.firstLoad = false; + } + // Validate field + item.validate(event); + if (!item.model.get("valid")) { + formValid = item.model.get("valid"); + // Save the first field to set the focus, that field must be distinct to grid + itemField = (itemField === undefined && item.model.get("type") !== "grid") ? item: itemField; + } + } + } + if (itemField) { + itemField.setFocus(); + } + } + // Finally set valid value to data model + this.model.set("valid", formValid); + return formValid; + }, + + /** + * Gets all files that was not uploaded completely + * @returns {array} + */ + getFilesNotUploaded: function () { + var i, + field, + formItems = this.formView.getFields(), + filesNoUploaded = []; + for (i = 0; i < formItems.length; i += 1) { + field = formItems[i]; + if (field.getFilesNotUploaded) { + filesNoUploaded = filesNoUploaded.concat(field.getFilesNotUploaded()); + } + } + return filesNoUploaded; + }, + /** + * Gets the loading value into the subfom fields + * @returns {boolean} + */ + isLoading: function () { + var i, + field, + formItems = this.formView.getFields(); + for (i = 0; i < formItems.length; i += 1) { + field = formItems[i]; + if (field.isLoading && (typeof field.isLoading === 'function') && field.isLoading()) { + return true; + } + } + return false; + }, + setData: function (data) { + //using the same method of PMDynaform.view.FormPanel + this.formView.setData(data); + + return this; + }, + /** + * Gets data of the form. + * @returns {{}} + */ + getData: function () { + var formView = this.getFormView(), + fields = formView.getFields(), + formData = {}, + item, + dataField, + i; + for (i = 0; i < fields.length; i += 1) { + item = fields[i]; + if (item.model.get("type") === "grid") { + dataField[item.model.get("name")] = item.getData2(); + } else { + dataField = item.model.getAppData(); + } + $.extend(true, formData, dataField); + } + return formData; + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + this.$el.find(".pmdynaform-field-form").append(this.formView.render(true).el); + + return this; + }, + afterRender: function () { + this.formView.afterRender(); + return this; + }, + /** + * Calls to running formulator method + * @returns {SubFormView} + */ + runningFormulator: function () { + this.formView.runningFormulator(); + return this; + }, + /** + * Gets the formView(FormPanel View) related to SubForm. + * @returns {null} + */ + getFormView: function () { + return this.formView; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.SubForm", SubFormView); + +}()); + +(function () { + + var GeoMapView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-map").html()), + validator: null, + events: { + "click .pmdynaform-map-fullscreen button": "applyFullScreen" + }, + $hiddens: [], + initialize: function (options) { + this.$hiddens = []; + this.form = options.form ? options.form : null; + var that = this; + }, + onLoadGeoLocation: function () { + var appData = this.project.mobileDataControls, + that = this; + if (appData && appData[this.model.get("name")]) { + this.model.set("altitude", appData[this.model.get("name")]["altitude"]); + this.model.set("latitude", appData[this.model.get("name")]["latitude"]); + this.model.set("longitude", appData[this.model.get("name")]["longitude"]); + this.createHiddens(appData[this.model.get("name")]); + } else { + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition(function (position) { + var pos = position.Geoposition ? position.Geoposition : position; + that.model.set("latitude", pos.coords.latitude || 0); + that.model.set("longitude", pos.coords.longitude || 0); + that.model.set("altitude", 0); + that.onLoadLocation(); + }); + } + } + this.onLoadLocation(); + return this; + }, + onLoadLocation: function () { + var that = this, + coords, + mapOptions, + map, + marker, + canvasHTML = that.$el.find(".pmdynaform-map-canvas")[0]; + coords = new google.maps.LatLng(this.model.get("latitude"), this.model.get("longitude")); + mapOptions = { + zoom: this.model.get("zoom"), + center: coords, + panControl: this.model.get("panControl"), + zoomControl: this.model.get("zoomControl"), + scaleControl: this.model.get("scaleControl"), + streetViewControl: this.model.get("streetViewControl"), + overviewMapControl: this.model.get("overviewMapControl"), + mapTypeControl: this.model.get("mapTypeControl"), + navigationControlOptions: { + style: google.maps.NavigationControlStyle.SMALL + }, + mapTypeId: google.maps.MapTypeId.ROADMAP + }; + + map = new google.maps.Map(canvasHTML, mapOptions); + this.model.set("googlemap", map); + + marker = new google.maps.Marker({ + position: coords, + map: map, + draggable: this.model.get("dragMarker"), + title: "" + }); + google.maps.event.addListener(marker, 'dragend', function (event) { + that.model.set("latitude", event.latLng.lat().toFixed(that.model.get("decimals"))); + that.model.set("longitude", event.latLng.lng().toFixed(that.model.get("decimals"))); + + }); + this.model.set("marker", marker); + + return this; + }, + applyFullScreen: function () { + if (this.fullscreen.supported) { + this.fullscreen.toggle(); + } else { + this.$el(".pmdynaform-map-fullscreen").hide(); + } + return this; + }, + render: function () { + var that = this; + + that.$el.html(that.template(that.model.toJSON())); + this.loadAsyncData(1000); + if (this.model.get("fullscreen")) { + this.fullscreen = new PMDynaform.core.FullScreen({ + element: this.$el.find(".pmdynaform-map-canvas")[0], + onReadyScreen: function () { + setTimeout(function () { + that.$el.find(".pmdynaform-map-canvas").css("height", $(window).height() + "px"); + }, 500); + }, + onCancelScreen: function () { + setTimeout(function () { + that.$el.find(".pmdynaform-map-canvas").css("height", ""); + }, 500); + } + }); + } + if (this.model.get("hint")) { + this.enableTooltip(); + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Load the map in async mode + * @param time + * @returns {GeoMapView} + */ + loadAsyncData: function (time) { + var that = this; + if (_.isNumber(time)) { + setTimeout(function () { + that.onLoadGeoLocation(); + }, time); + } + return this; + }, + /** + * Create the hiddens input for the field + * @param obj + * @returns {GeoMapView} + */ + createHiddens: function (obj) { + var prop, + hidden, + name; + if (_.isObject(obj) && _.isArray(this.$hiddens)) { + for (prop in obj) { + if (obj.hasOwnProperty(prop)) { + name = this.createNameforHidden(prop); + hidden = $("", {name: name, type: "hidden", value: obj[prop]}); + this.$el.append(hidden); + this.$hiddens.push(hidden); + } + } + } + return this; + } + , + /** + * Create names form the hidden input + * @param prop + * @returns {string} + */ + createNameforHidden: function (prop) { + var name = ""; + if (_.isString(prop)) { + name = "form[" + this.model.get("variable") + "]" + "[" + prop + "]"; + } + return name; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.GeoMap", GeoMapView); +}()); + +(function () { + var Annotation = PMDynaform.view.Field.extend({ + validator: null, + template: _.template($("#tpl-annotation").html()), + tagControl: null, + tagLabel: null, + initialize: function () { + this.model.set("type", "label"); + }, + render: function () { + this.$el.html(this.template(this.model.toJSON())); + this.tagControl = this.$el.find("span"); + this.tagLabel = this.tagControl.find("p span"); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setValue: function (text) { + if (text !== undefined) { + this.model.set("label", text); + this.tagLabel.text(text); + } + return this; + }, + setText: function (text) { + this.setValue(text); + }, + getText: function () { + var label = this.model.get("label"); + return label ? label : null; + }, + getValue: function () { + return this.model.getValue(); + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Annotation", Annotation); +}()); + +/** + * The Datetime class was developed with the help of DateBootstrap plugin + */ +(function () { + var DatetimeView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-datetime2").html()), + validator: null, + keyPressed: false, + previousValue: null, + datePickerObject: null, + timeFormatRegEx: /[hHmsSaAZ]/, + navigatorKeys: [37, 38, 39, 40], + events: { + "blur input": "onBlurInput", + "keydown input": "refreshBinding", + 'focus .form-control': 'onFieldFocus' + }, + /** + * Initializes properties + * @param options + */ + initialize: function (options) { + this.form = options.form ? options.form : null; + this.model.on("change:toDraw", this.render, this); + this.model.on("change:dependencyDidUpdate", this.afterDependencyDidUpdateView, this); + this.initLanguage(); + this.previousValue = this.getValue(); + }, + /** + * Gets standard date + * @param date + * @returns {string} + */ + getStandardFormat: function (date) { + if (date !== undefined && date !== null && moment(date).isValid()) { + //TODO: This method isn't the best form to get the standard date and it will be resolved on the ticket FBI-2254. + return moment(date).hasOwnProperty("_i") ? moment(date)._i : ""; + } + }, + /** + * onBlurInput helper to force to update the hidden with the real data + * @param event + */ + onBlurInput: function (event) { + var localeDate = this.datePickerObject.date(), + defaultFormatted = this.prepareFormatValue(localeDate); + if (moment(defaultFormatted).isValid()) { + this.tagHiddenToLabel.val(this.getStandardFormat(defaultFormatted)); + this.validate(); + } + event.preventDefault(); + event.stopPropagation(); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of Datetime + */ + afterDependencyDidUpdateView: function () { + if (this.model.get("dependencyDidUpdate")) { + this.dependencyDidUpdateView(); + } + this.model.set({ "dependencyDidUpdate": false }, { silent: true }); + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of Datetime + */ + dependencyDidUpdateView: function () { + this.changeHidden(); + this.validate(); + }, + /** + * Change the hidden view in Datetime field + * @return {DatetimeView} + */ + changeHidden: function () { + var data = this.model.get("data"), + hiddenInput = this.tagHiddenToLabel; + if (data.hasOwnProperty("value")) { + hiddenInput.val(data.value); + } + return this; + }, + /** + * Default function + */ + onChangeCallback: function () { + }, + /** + * Sets the setOnchange helper function to a property + * @param fn + * @returns {DatetimeView} + */ + setOnChange: function (fn) { + if (typeof fn === "function") { + this.onChangeCallback = fn; + } + return this; + }, + /** + * Validate if the field is required or has an RegEx + * @param event + * @returns {DatetimeView} + */ + validate: function (event) { + this.model.set({ validate: true }); + this.model.validate(); + if (this.model.get("enableValidate")) { + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error'); + } + if (!this.model.isValid()) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".control-group").parent().append(this.validator.el); + this.applyStyleError(); + } + } else { + this.model.attributes.valid = true; + } + return this; + }, + /** + * prevent default events + * @param event + * @returns {DatetimeView} + */ + refreshBinding: function (event) { + //Validation for the Submit event + if (event.which === 13) { + event.preventDefault(); + event.stopPropagation(); + } + this.keyPressed = true; + return this; + }, + /** + * Render main method to represent the component in the page + * @returns {DatetimeView} + */ + render: function () { + var name, + dateInput, + control, + that = this, + windowResizeHandler; + + this.$el.html(this.template(this.model.toJSON())); + if (this.model.get("hint") !== "") { + this.enableTooltip(); + } + control = this.$el.find('#datetime-container-control'); + + windowResizeHandler = function () { + if (control.data("DateTimePicker")) { + control.data("DateTimePicker").hide(); + } + $(window).off('resize', windowResizeHandler); + }; + + control.datetimepicker({ + format: this.model.get("format"), + stepping: this.model.get("stepping"), + useCurrent: this.model.get("useCurrent"), + collapse: this.model.get("collapse"), + defaultDate: this.model.get("defaultDate") ? moment(this.model.get("defaultDate")) : false, + disabledDates: this.model.get("disabledDates"), + sideBySide: this.model.get("sideBySide"), + daysOfWeekDisabled: this.model.get("daysOfWeekDisabled"), + calendarWeeks: this.model.get("calendarWeeks"), + viewMode: this.model.get("viewMode"), + toolbarPlacement: this.model.get("toolbarPlacement"), + showClear: this.model.get("showClear"), + focusOnShow: true, + showTodayButton: true, + ignoreReadonly: true, + locale: this.language, + tooltips: { + today: 'Go to today'.translate(), + clear: 'Clear selection'.translate(), + close: 'Close the picker'.translate(), + selectMonth: 'Select Month'.translate(), + prevMonth: 'Previous Month'.translate(), + nextMonth: 'Next Month'.translate(), + selectYear: 'Select Year'.translate(), + prevYear: 'Previous Year'.translate(), + nextYear: 'Next Year'.translate(), + selectDecade: 'Select Decade'.translate(), + prevDecade: 'Previous Decade'.translate(), + nextDecade: 'Next Decade'.translate(), + prevCentury: 'Previous Century'.translate(), + nextCentury: 'Next Century'.translate(), + incrementHour: 'Increment Hour'.translate(), + pickHour: 'Pick Hour'.translate(), + decrementHour: 'Decrement Hour'.translate(), + incrementMinute: 'Increment Minute'.translate(), + pickMinute: 'Pick Minute'.translate(), + decrementMinute: 'Decrement Minute'.translate(), + incrementSecond: 'Increment Second'.translate(), + pickSecond: 'Pick Second'.translate(), + decrementSecond: 'Decrement Second'.translate() + }, + "minDate": this.model.get("minDate").trim().length ? this.model.get("minDate") : false, + "maxDate": this.model.get("maxDate").trim().length ? this.model.get("maxDate") : false + }).on('dp.show', function () { + if (that.project) { + that.project.hideCalendars(this); + } + that.recalculateWidgetPosition(); + $(window).on('resize', windowResizeHandler); + }).on('dp.hide', function () { + that.$el.find('input.form-control').eq(0).blur(); + }).on('dp.change', function (event) { + that.changeSelectEvent(event.date); + }).find('.form-control').attr('readonly', this.project.isMobile()); + this.datePickerObject = this.$el.find('#datetime-container-control').data()["DateTimePicker"]; + this.tagControl = this.$el.find("input[type='text']"); + this.tagHiddenToLabel = this.$el.find("input[type='hidden']"); + this.valueReader(); + if (this.model.get("group") === "grid") { + dateInput = this.$el.find("input[type='text']")[0]; + name = this.model.get("name"); + name = name.substring(0, name.length - 1).concat("_label]"); + dateInput.name = dateInput.id = "form" + name; + } + if (this.model.get("name").trim().length === 0) { + this.$el.find("input[type='text']").attr("name", ""); + this.$el.find("input[type='hidden']").attr("name", ""); + } + + this.keysNavigatorDefineEvents(); + this.$el.find(".content-print").text(this.model.get("data")["label"]); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Prepare the value because many formats is allowed in Datetime field + * suported types: "08102017", "2017-10-23" or "2017-10-23 04:00:00" + * @returns {DatetimeView} + */ + valueReader: function () { + var value = this.model.get("value"), + formattedDate, + defaultFormatted; + // I use the value instead of data because in an specific format + // "dddd, Do-MMM-YYYY", the data property arrives empty from the server. + // Data is not reliable. + if (value) { + // Need formated the value because from server arrives in the next way + // "08102017" or + // "2017-10-23" or + // "2017-10-23 04:00:00" + formattedDate = moment(value, [ + this.model.get("datetimeIsoFormat"), + this.model.get("dateIsoFormat"), + this.model.get("format") + ]); + defaultFormatted = this.prepareFormatValue(formattedDate); + if (moment(defaultFormatted).isValid()) { + this.setValue(defaultFormatted); + this.tagHiddenToLabel.val(this.getStandardFormat(defaultFormatted)); + } + } + }, + /** + * Prepares the value in the required format. + * if has time we will use "datetimeIsoFormat" format + * if has not we will use "dateIsoFormat" format + * @param userValue + * @returns {object} + */ + prepareFormatValue: function (userValue) { + var formattedValue = null; + if (userValue && userValue instanceof moment) { + formattedValue = !this.timeFormatRegEx.test(this.model.get('format')) ? + userValue.format(this.model.get("dateIsoFormat")) : userValue.format(this.model.get("datetimeIsoFormat")); + } + return formattedValue; + }, + /** + * navigation event handler Time control + * only keyboards navigation is controlled, up, down, right and left + */ + keysNavigatorDefineEvents: function () { + var that = this; + if (this.tagControl instanceof jQuery) { + this.tagControl.keyup(function (e) { + if (that.navigatorKeys.indexOf(e.keyCode) > -1) { + that.recalculateWidgetPosition(); + } + }); + } + return this; + }, + updateAttributeDatepicker: function (attribute, value) { + if (this.datePickerObject && this.datePickerObject[attribute]) { + this.datePickerObject[attribute](value); + } + return this; + }, + /** + * Parse the all formats to the user format + * @param value + * @returns {{value: string, label: string}} + */ + formatData: function (value) { + var originalFormat = this.model.get("format"), + newData = { + value: "", + label: "" + }; + if (value) { + value = this.getStandardFormat(value); + newData = { + value: value, + label: moment(value, [ + this.model.get("datetimeIsoFormat"), + this.model.get("dateIsoFormat"), + originalFormat + ]).format(originalFormat) + }; + } + return newData; + }, + /** + * Sets a valid date, here we validate if is a correct dateTime value + * @param value + * @returns {DatetimeView} + */ + setValue: function (value) { + if (value !== undefined && value !== null) { + this.previousValue = this.getValue(); + value === "" ? this.clear() : + this.datePickerObject.date(this.formatData(value).label); + } + return this; + }, + + /** + * Clear the value and clear the datetimepicker control + * @returns {DatetimeView} + */ + clear: function () { + this.datePickerObject.clear(); + this.tagHiddenToLabel.val(""); + return this; + }, + /** + * gets the value of a DatetimePicker + */ + getValue: function () { + return this.model.getValue(); + }, + getText: function () { + var data = this.model.get("data"); + return data ? data["label"] : null; + }, + + /** + * Recalculate The Wiget Postion + * @returns {DatetimeView} + */ + recalculateWidgetPosition: function () { + var index = 0, + fixedPosition = 'fixed', + absolutePosition = 'absolute', + controlDatePicker = this.$el.find(".datetime-container"), + widgetCalendar = this.$el.find(".bootstrap-datetimepicker-widget"), + picker = controlDatePicker.get(index), + controlSpace = picker ? picker.getBoundingClientRect() : null, + mainContainer = this.getParentElementForFloatingElements(), + factorAlign = 2, + isMobile = this.project.isMobile(), + widgetRect, + widgetSpace; + + //widgetRect is read only + widgetRect = !_.isEmpty(widgetCalendar.get(index)) ? widgetCalendar.get(index).getBoundingClientRect() : null; + if (widgetRect) { + // widgetRect' clone + widgetSpace = { + position: fixedPosition, + top: widgetRect.top, + left: widgetRect.left, + height: widgetRect.height + }; + // Update the arrows's widget + this.updateArrowsToRTL(widgetCalendar); + // Check if the available space is short up and down + if (this.spaceIsShort("up_down", controlSpace, widgetSpace)) { + widgetSpace = this.setWidgetPosition(widgetSpace, "top"); + } else { + //Check widget's initial position + if (this.positionWidgetIsUp(widgetSpace.top, controlSpace.top)) { + if (!this.existSpaceAvailable("up", controlSpace, widgetSpace)) { + widgetSpace = this.setWidgetPosition(widgetSpace, "under"); + } else { + widgetSpace.top = widgetSpace.top - factorAlign; + } + } else { + if (!this.existSpaceAvailable("down", controlSpace, widgetSpace)) { + widgetSpace = this.setWidgetPosition(widgetSpace, "over"); + } else { + widgetSpace.top = widgetSpace.top - factorAlign; + } + } + } + //If is mobile set properties and add scroll + if (mainContainer && isMobile) { + widgetSpace.position = absolutePosition; + widgetSpace.top += mainContainer.scrollTop; + widgetSpace.left += mainContainer.scrollLeft; + } + //Append widget calendar to main container + if (mainContainer && widgetCalendar.get(index)) { + mainContainer.appendChild(widgetCalendar.get(index)); + this.applyPosition(widgetCalendar, widgetSpace); + } + } + return this; + }, + /** + * Check the position widget + * @param widgetTop + * @param controlTop + * @param controlHeight + * @returns {boolean} + */ + positionWidgetIsUp: function (widgetTop, controlTop) { + var flag = false; + + if (controlTop > widgetTop) { + flag = true; + } + return flag; + }, + /** + * Check if the available space is short + * @param controlSpace + * @param widgetSpace + */ + spaceIsShort: function (position, controlSpace, widgetSpace) { + var flag = false, + defaultZoom = 1, + factorZoom = window.devicePixelRatio || defaultZoom, + availableSpace; + + availableSpace = { + up: controlSpace.top * factorZoom, + down: ($(window).height() - controlSpace.bottom) * factorZoom + }; + + if (availableSpace.up < widgetSpace.height * factorZoom && + availableSpace.down < widgetSpace.height * factorZoom) { + flag = true; + } + + return flag; + }, + /** + * Check the available space + * @param position + * @param controlSpace + * @param widgetSpace + * @returns {boolean} + */ + existSpaceAvailable: function (position, controlSpace, widgetSpace) { + var flag = false, + defaultZoom = 1, + factorZoom = window.devicePixelRatio || defaultZoom, + availableSpace; + + availableSpace = { + up: controlSpace.top * factorZoom, + down: ($(window).height() - controlSpace.bottom) * factorZoom + }; + + switch (position) { + case "up": + if (availableSpace.up >= widgetSpace.height * factorZoom) { + flag = true; + } + break; + case "down": + if (availableSpace.down >= widgetSpace.height * factorZoom) { + flag = true; + } + break; + } + return flag; + }, + /** + * Apply widget's new positions + * @param objPos + */ + applyPosition: function (widgetCalendar, newPositions) { + widgetCalendar.css({ + position: newPositions.position, + left: newPositions.left, + top: newPositions.top, + height: newPositions.height + }); + return this; + }, + /** + * Sets Widget Position + * @param widgetSpace + * @param position TOP, BOTTOM, OVER, UNDER and MIDDLE + */ + setWidgetPosition: function (widgetSpace, position) { + var factorPixelBottom = 2, + factorPixeTop = 6, + index = 0, + controlDatePicker = this.$el.find(".datetime-container"), + controlSpace = controlDatePicker.get(index).getBoundingClientRect(), + factorAlign, + factorInverse = -1; + + switch (position) { + case "top": + widgetSpace.top = factorPixelBottom; + break; + case "bottom": + widgetSpace.top = $(window).height() - widgetSpace.height - factorPixelBottom; + break; + case "over": + widgetSpace.top = widgetSpace.top - (widgetSpace.height + controlSpace.height + factorPixeTop); + break; + case "under": + widgetSpace.top = widgetSpace.top + (widgetSpace.height + controlSpace.height + factorPixelBottom); + break; + case "middle": + factorAlign = factorPixelBottom + (controlSpace.height / 2 + widgetSpace.height / 2); + if (this.positionWidgetIsUp(widgetSpace.top, controlSpace.top)) { + widgetSpace.top = widgetSpace.top - (factorAlign * factorInverse); + } else { + widgetSpace.top = widgetSpace.top - factorAlign; + } + break; + } + return widgetSpace; + }, + onFieldFocus: function () { + if (typeof this.onFieldFocusCallback === 'function') { + this.onFieldFocusCallback(); + } + }, + isOpen: function () { + var widget = this.$el.find(".bootstrap-datetimepicker-widget").get(0); + if (widget) { + return true; + } + return false; + }, + /** + * when the project has the RTL variable true value, date arrows component + * is reversed, so that the slide functionality is reversed + */ + updateArrowsToRTL: function (widget) { + var arrowsPrev, + arrowsNext, + i = 0, + classPrev, + classNext; + if (widget && widget instanceof jQuery) { + if (this.project && this.project.isRTL) { + arrowsPrev = widget.find(".table-condensed .prev"); + arrowsNext = widget.find(".table-condensed .next"); + while (i < arrowsPrev.length && i < arrowsNext.length) { + classPrev = arrowsPrev.eq(i).find("span").attr("class"); + classNext = arrowsNext.eq(i).find("span").attr("class"); + if (classPrev !== undefined && classNext !== undefined) { + arrowsPrev.eq(i).find("span").attr("class", classNext); + arrowsNext.eq(i).find("span").attr("class", classPrev); + i += 1; + } + } + } + } + return this; + }, + /* Returns the element in which floating elements should be appended for this field. + */ + getParentElementForFloatingElements: function () { + var text = this.$el.find("input[type='text']"), + parent = text.closest('.modal').get(0); + + return parent || document.body; + }, + /** + * Gets control user for helper function purposes. + * the result must be an instance of jquery of the HTML control. + */ + getControl: function () { + var htmlControl = this.$el.find("input[type='text']"); + return htmlControl; + }, + /** + * When the select control change value + * @param {*} date + * @return {DatetimeView} + */ + changeSelectEvent: function (date) { + var that = this, dt; + dt = this.updateView(date, function () { + that.executeChangeCallback(); + }); + return this; + }, + + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of Datetime + * @param {*} fn + * @return {DatetimeView} + */ + updateView: function (date, fn) { + var dt = { + value: "", + label: "" + }, + newData = this.formatData(date ? this.prepareFormatValue(date) : ""); + this.model.set({ "data": newData }, { silent: true }); + this.model.set({ "value": newData.value }, { silent: true }); + + dt = this.updateFieldView(newData); + // is very important pass the control to dependencyWillUpdate + this.model.dependencyWillUpdate({ + data: dt, + fn: fn + }); + return this; + }, + /** + * Update the view + * @return {DatetimeView} + */ + updateFieldView: function (data) { + if (data) { + this.tagHiddenToLabel.val(data.value); + this.tagControl.val(data.label); + this.$el.find(".content-print").text(data.label); + + } + }, + /** + * Execute the change callback on view + */ + executeChangeCallback: function () { + var form = this.form, + paramsValue = { + idField: this.model.get("id"), + current: this.getValue(), + previous: this.previousValue + }; + if (paramsValue.current !== paramsValue.previous) { + this.onChangeCallback(paramsValue.current, paramsValue.previous); + if (form) { + form.checkBinding(paramsValue); + } + this.previousValue = this.getValue(); + } + }, + /** + * Update bootstrap DateTimePicker widget + * @param {Object} options + * @return {DatetimeView} + */ + updateSettings: function (options) { + var maxDate = moment(options.maxDate || null), + minDate = moment(options.minDate || null), + currentData = moment(this.model.get("data").value ? this.model.get("data").value : null); + + if (this.validator) { + this.validator.$el.remove(); + this.$el.removeClass('has-error'); + } + if (minDate.isValid() && currentData.isValid() && currentData.diff(minDate) < 0 && this.model.get("data").value !== "") { + this.applyErrorStyle(); + this.clear(); + this.datePickerObject.options(options); + return this; + } + if (maxDate.isValid() && currentData.isValid() && maxDate.diff(currentData) < 0 && this.model.get("data").value !== "") { + this.applyErrorStyle(); + this.clear(); + this.datePickerObject.options(options); + return this; + } + if (maxDate.isValid() && minDate.isValid() && maxDate.diff(minDate) < 0) { + this.applyErrorStyle(); + return this; + } + this.datePickerObject.options(options); + this.model.attributes.valid = true; + return this; + }, + /** + * Apply error styles + * @return {DatetimeView} + */ + applyErrorStyle: function () { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + this.$el.find(".control-group").parent().append(this.validator.el); + this.applyStyleError(); + this.model.attributes.valid = false; + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.DatetimeR", DatetimeView); +}()); +(function () { + var PanelField = PMDynaform.view.Field.extend({ + validator: null, + template: _.template($("#tpl-panelField").html()), + initialize: function () { + }, + render: function () { + var content, + footer; + this.$el.html(this.template(this.model.toJSON())); + this.$el.find(".panel-body").html(this.model.get("content")); + footer = $(this.model.get("footerContent")); + if (footer.length && footer instanceof jQuery) { + this.$el.find(".panel-footer").append(footer); + } else { + this.$el.find(".panel-footer").text(this.model.get("footerContent")); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.PanelField", PanelField); +}()); + +/** + * Class Tooltip + */ +(function () { + var ToolTipView = Backbone.View.extend({ + trigger: 'manual', + position: 'bottom', + title: 'Default Content', + element: null, + initialize: function () { + //TODO: no need params. + }, + /** + * Creation of the Tooltip + * @returns {ToolTipView} + */ + render: function () { + if (this.getElement()) { + this.getElement().tooltip('destroy'); + this.getElement().tooltip({ + 'container': 'body', + 'trigger': this.trigger, + 'placement': this.getPosition(), + 'title': this.getTitle() + }); + } + return this; + }, + /** + * Show Tooltip + * @param element + * @param title + * @param position + * @returns {ToolTipView} + */ + show: function (element, title, position) { + var tooltipWidget = null; + this.setPosition(position); + this.setTitle(title); + this.setElement(element); + this.render(); + this.getElement().tooltip('show'); + tooltipWidget = $(".tooltip"); + if (!this.validatePosition(tooltipWidget, position)) { + this.reposition(tooltipWidget); + this.getElement().tooltip('show'); + } + return this; + }, + /** + * Hide Tooltip + * @param element + * @returns {ToolTipView} + */ + hide: function (element) { + var tooltipWidfget = $(".tooltip"); + element.tooltip('hide'); + element.tooltip('destroy'); + if (tooltipWidfget) { + $(".tooltip").remove(); + } + this.setElement(null); + return this; + }, + /** + * Set Element of the Tooltip + * @param element + * @returns {ToolTipView} + */ + setElement: function (element) { + this.element = element ? element : this.element; + return this; + }, + /** + * Set Position Tooltip + * @param position + * @returns {ToolTipView} + */ + setPosition: function (position) { + this.position = position ? position : this.position; + return this; + }, + /** + * Set Text content of the Tooltip + * @param title + * @returns {ToolTipView} + */ + setTitle: function (title) { + this.title = title ? title : this.title; + return this; + }, + /** + * Get Position Tooltip + * @returns {string} + */ + getPosition: function () { + return this.position; + }, + /** + * Get Text Content Tooltip + * @returns {string} + */ + getTitle: function () { + return this.title; + }, + /** + * Get Element of the Tooltip + * @returns {null} + */ + getElement: function () { + return this.element; + }, + /** + * Validate Position Tooltip + * @param element + * @param position + * @returns {boolean} + */ + validatePosition: function (element, position) { + var isAvailable = false, + propsElement = [], + margin = {top: 10, left: 20, bottom: 10, right: 20}; + + propsElement = this.getPositionAvailable(element); + if (propsElement && propsElement.length > 0) { + switch (position) { + case "top": + isAvailable = (this.getPositionArray(propsElement, "top") > margin.top && + this.getPositionArray(propsElement, "right") > margin.right && + this.getPositionArray(propsElement, "left") > margin.left) ? true : isAvailable; + break; + case "bottom": + isAvailable = (this.getPositionArray(propsElement, "bottom") > margin.bottom && + this.getPositionArray(propsElement, "right") > margin.right && + this.getPositionArray(propsElement, "left") > margin.left) ? true : isAvailable; + break; + case "right": + case "left": + isAvailable = true; + break; + default: + isAvailable = false; + } + } + return isAvailable; + }, + /** + * Get Array of Positions of the element + * @param element + * @returns {Array} + */ + getPositionAvailable: function (element) { + var top, + right, + bottom, + left, + propsElement, + widthWindow = $(window).width(), + heightWindow = $(window).height(), + position = 'bottom', + available, + arrayProps = [], + prop; + + propsElement = element ? element[0].getBoundingClientRect() : null; + if (propsElement) { + available = { + top: propsElement.top, + right: widthWindow - propsElement.right, + bottom: heightWindow - propsElement.bottom, + left: propsElement.left + }; + for (prop in available) { + arrayProps.push({ + 'key': prop, + 'value': available[prop] + }); + } + arrayProps.sort(function (a, b) { + return b.value - a.value; + }); + position = arrayProps[0]; + } + + return arrayProps; + }, + /** + * Reposition Tooltip + * @param element + * @returns {ToolTipView} + */ + reposition: function (element) { + var i, + max, + bestPosition = false, + position, + arrPositions = []; + + arrPositions = this.getPositionAvailable(element); + for (i = 0 , max = arrPositions.length; i < max; i += 1) { + position = arrPositions[i]["key"]; + if (this.validatePosition(element, position)) { + bestPosition = true; + break; + } + } + this.setPosition(position); + this.render(); + return this; + }, + /** + * Get Value Position of the Array Positions + * @param arrayProps + * @param position + * @returns {*} + */ + getPositionArray: function (arrayProps, position) { + var valuePos, + max, + object, + i; + + if (arrayProps && arrayProps.length > 0) { + for (i = 0, max = arrayProps.length; i < max; i += 1) { + object = arrayProps[i]; + if (object.key === position) { + valuePos = object.value; + break; + } + } + } + return valuePos; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.ToolTipView", ToolTipView); +}()); +(function () { + /** + * @class PMDynaform.util.ui.FlashMessageModel + * A message to display for a while. + * + * Usage example: + * + * @example + * flashModel = new PMDynaform.ui.FlashMessageModel({ + * message : "This is a flas message", + * emphasisMessage: "Info", + * startAnimation:5000, + * closable:true, + * type:"danger", + * appendTo:document.body, + * duration:5000 + * }); + * + * + * @constructor + * Creates a new instance of the class. + * + * @cfg {String} [emphasisMessage=""] The object's emphasisMessage. It can be a single string + * @cfg {String} [message=""] The object's message. It can be a single string + * @cfg {Number} [duration=3000] The time in milliseconds the message will be displayed. + * @cfg {String} [type="info"] The type for the message. Valid values: 'info', 'success', 'error', 'warning'. + */ + var FlashMessageModel = Backbone.Model.extend({ + defaults: { + /** + * The message property sets a simple label that will be displayed in the component + * @type {String} + * @readonly + */ + message: '', + /** + * The duration in milliseconds to show the message. Set by the config option + * and the method. + * @type {Number} + * @readonly + */ + duration: 3000, + /** + * The html element's object the message will be displayed in the DOM element + * @type {HTMLElement} + */ + appendTo: document.body, + /** + * The message's type. Set by the, config option with success, info, warning, danger + * @type {String} + * @readonly + */ + type: 'info', + /** + * The duration in milliseconds to start the message. Set by the config option + * and the method. + * @type {Number} + * @readonly + */ + startAnimation: 1000, + /** + * The emphasisMessage property sets a emphasis label that will be displayed in the component + * @type {String} + * @readonly + */ + emphasisMessage: '', + /** + * The valid Type 's set by config option with success, info, warning, danger + * @type {Array} + */ + validTypes: [], + /** + * add scroll of the scroll in the top, when show the flash message + * @type {Boolean} + */ + absoluteTop: false, + closable: false + }, + /** + * When creating an instance of a model, you can pass in the initial values of the attributes + * @param settings: properties with custom values + * @returns {FlashMessageModel} + */ + initialize: function (config) { + this.set("validTypes", ["success", "info", "warning", "danger"]); + this.on("change:type", this.setType); + this.on("change:appendTo", this.setAppendTo); + }, + /** + * This method, set the type for the message. Valid values: 'info', 'success', 'error', 'warning'. + * @param {[type]} type [description] + */ + setType: function (model, type) { + if (this.get("validTypes").indexOf(type) > -1) { + this.set("type", type); + } else { + this.set("type", "info"); + } + return this; + }, + /** + * The html element's object the message will be displayed in the DOM element + * @param {[type]} model : is a object model + * @param {[type]} parentNode : this a html element container. + */ + setAppendTo: function (model, parentNode) { + if (_.isObject(parentNode)) { + if (parentNode instanceof jQuery || parentNode.ELEMENT_NODE) { + this.set("appendTo", parentNode); + } + } else { + this.set("appendTo", document.body); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.ui.FlashMessageModel", FlashMessageModel); +}()); +(function () { + var FileMobile = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-extfile").html()), + templateAudio: _.template($("#tpl-extaudio").html()), + templateVideo: _.template($("#tpl-extvideo").html()), + templateMediaVideo: _.template($("#tpl-media-video").html()), + templateMediaAudio: _.template($("#tpl-media-audio").html()), + templateImage: _.template($("#tpl-extfile").html()), + templatePlusImage: _.template($("#tpl-extfile-plus-image").html()), + templatePlusAudio: _.template($("#tpl-extfile-plus-audio").html()), + templatePlusVideo: _.template($("#tpl-extfile-plus-video").html()), + templateRenderingWeb: _.template($("#tpl-multimedia-renderingWeb").html()), + boxPlus: null, + viewsFiles: [], + mediaVideos: [], + validator: null, + messageRequired: "This field is required.".translate(), + events: { + "click buttonImage": "onClickButtonMobile", + "click .pmdynaform-file-resizeimage": "onClickImage" + }, + initialize: function () { + return this; + }, + /** + * Listen OnclickEvent for Mobile Controls + * @param event + * @returns {FileMobile} + */ + onClickButtonMobile: function (event) { + var type = this.model.get("type"); + switch (type) { + case "imageMobile": + this.onClickButtonImage(event); + break; + case "audioMobile": + this.onClickButtonAudio(event); + break; + case "videoMobile": + this.onClickButtonVideo(event); + break; + } + event.preventDefault(); + event.stopPropagation(); + return this; + }, + /** + * Listen OnclickEvent for Image Control + * @param event + * @returns {FileMobile} + */ + onClickButtonImage: function (event) { + var respData, + project = this.model.get("project"); + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + type: "image", + galleryEnabled: this.model.get("galleryEnabled"), + cameraEnabled: this.model.get("cameraEnabled") + }; + project.requestManager.getImage(respData); + return this; + }, + /** + * Listen OnclickEvent for preview a image + * @param event + * @returns {FileMobile} + */ + onClickImage: function (event) { + var respData, + project = this.model.get("project"); + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + idFile: event.target.id, + type: "image", + availableOffline: this.model.get("availableOffline") + }; + project.requestManager.previewImage(respData); + return this; + }, + /** + * Listen OnclickEvent for Audio Control + * @param event + * @returns {FileMobile} + */ + onClickButtonAudio: function (event) { + var respData; + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + type: "audio" + }; + this.model.get("project").requestManager.getAudio(respData); + return this; + }, + /** + * Listen OnclickEvent for Video Control + * @param event + * @returns {FileMobile} + */ + onClickButtonVideo: function (event) { + var respData; + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + type: "video" + }; + this.model.get("project").requestManager.getVideo(respData); + return this; + }, + /** + * Validate a File Mobile Controls + * @returns {FileMobile} + */ + validate: function () { + if (this.validator) { + this.validator.$el.remove(); + if (_.isFunction(this.removeStyleError)) { + this.removeStyleError(); + } + } + + this.model.validate(); + if (!this.model.get("valid")) { + this.validator = new PMDynaform.view.Validator({ + model: new Backbone.Model({ + message: { + required: this.model.get("requiredFieldErrorMessage") || this.messageRequired + } + }) + }); + this.$el.find(".pmdynaform-field-control").append(this.validator.$el); + if (_.isFunction(this.applyStyleError)) { + this.applyStyleError(); + } + } + return this; + }, + /** + * This function apply style error in this field + * @returns {FileUpload} + */ + applyStyleError: function () { + this.$el.addClass("has-error has-feedback"); + this.$el.find(".pmdynaform-file-droparea-ext").addClass("file-mobile-error"); + return this; + }, + /** + * THis function remove style error in this field + * @returns {FileUpload} + */ + removeStyleError: function () { + this.$el.removeClass('has-error has-feedback'); + this.$el.find(".pmdynaform-file-droparea-ext").removeClass("file-mobile-error"); + return this; + }, + render: function () { + var dataFiles, + nameField, + options = _.extend( + this.model.toJSON(), + { + dottedBox: !(this.model.get("mode") === "view" || (this.model.get("mode") === "parent" && this.model.get("parent").get("mode") === "view")) + } + ); + + if (PMDynaform.core.ProjectMobile) { + if (this.model.get("mode") === "edit" || (this.model.get("mode") === "parent" && this.model.get("parent").get("mode") === "edit")) { + this.createBoxPlus(); + } + this.$el.html(this.template(options)); + if (this.model.get("hint")) { + this.enableTooltip(); + } + this.$el.find(".pmdynaform-file-droparea-ext").append(this.boxPlus); + } else { + this.$el.html(this.template(options)); + dataFiles = this.project.mobileDataControls; + nameField = this.model.get("name"); + if (dataFiles.hasOwnProperty(nameField)) { + this.renderingWeb(dataFiles[nameField]); + } + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * controls renders video, audio and image, according to the values + * obtained from the mobile version. + * @param items, is the list of the elements multimedia. + * @returns {HTMLElement} + */ + renderingWeb: function (items) { + var ieVersion, + type = this.model.get("type"), + i, + viewFiles, + elements = [], + container = this.$el.find(".pmdynaform-file-control"), + downloadLink, + data, + linkService = "showDocument"; + if (_.isArray(items)) { + this.model.set({"data": {"value": items}}); + container.empty(); + ieVersion = PMDynaform.core.Utils.checkValidIEVersion(); + if (type === "imageMobile") { + elements = this.model.remoteProxyData(items); + } else { + for (i = 0; i < items.length; i += 1) { + data = { + uid: items[i], + type: linkService + }; + downloadLink = this.project.webServiceManager.showDocument(data); + data = $.extend(true, this.model.urlFileStreaming(items[i]), {downloadLink: downloadLink}); + elements.push(data); + } + } + viewFiles = this.templateRenderingWeb({ + elements: elements, + type: type, + ieVersion: ieVersion + }); + container.append(viewFiles); + } + }, + setFilesRFC: function (arrayFiles) { + var type = this.model.get("type"); + switch (type) { + case "imageMobile": + this.loadMixingSourceImages(arrayFiles); + break; + case "audioMobile": + case "videoMobile": + this.loadMixingSourceMedia(arrayFiles); + break; + } + }, + loadMixingSourceImages: function (arrayFiles) { + var max = arrayFiles.length ? arrayFiles.length : 0, + i, + response; + + if (max) { + response = this.model.remoteProxyData(arrayFiles); + } + if (response && response.length) { + for (i = 0; i < response.length; i += 1) { + this.updateFiles(response[i]); + } + } + }, + loadMixingSourceMedia: function (arrayFiles) { + var itemMedia, + item; + for (var i = 0; i < arrayFiles.length; i++) { + item = arrayFiles[i]; + if (typeof item === "string") { + itemMedia = this.model.urlFileStreaming(item); + this.createBoxFile(itemMedia); + this.model.addItemFile(itemMedia); + } + if (item.filePath) { + this.createBoxFile(item); + this.model.addItemFile(item); + } + } + }, + /** + * Create box and update array of files + * @param item + * @returns {FileMobile} + */ + updateFiles: function (item) { + if (_.isObject(item) && !_.isEmpty(item)) { + this.model.addItemFile(item); + this.createBoxFile(item); + } + return this; + }, + /** + * [setFiles Function for set files images, video and audio from a interface to mobile] + * @param {[type]} arrayFiles [description] + */ + setFiles: function (arrayFiles) { + var i; + for (i = 0; i < arrayFiles.length; i += 1) { + this.updateFiles(arrayFiles[i]); + } + this.validate(); + }, + setData: function (data) { + this.setFilesRFC(data["value"]); + return this; + }, + /** + * Create Box of Mobile Controls + * @param file + */ + createBoxFile: function (file) { + var type = this.model.get("type"); + switch (type) { + case "imageMobile": + this.createBoxImage(file); + break; + case "audioMobile": + this.createBoxAudio(file); + break; + case "videoMobile": + this.createBoxVideo(file); + break; + } + }, + createBoxImage: function (file) { + var newSrc, + rand = Math.floor((Math.random() * 100000) + 3), + template = document.createElement("div"), + resizeImage = document.createElement("div"), + preview = document.createElement("span"), + progress = document.createElement("div"); + + if (file["filePath"]) { + newSrc = file["filePath"]; + } + if (file["base64"]) { + newSrc = this.model.makeBase64Image(file["base64"]); + } + + if (newSrc) { + template.id = rand; + template.className = "pmdynaform-file-containerimage"; + + resizeImage.className = "pmdynaform-file-resizeimage"; + resizeImage.innerHTML = ''; + preview.id = rand; + preview.className = "pmdynaform-file-preview"; + preview.appendChild(resizeImage); + progress.id = rand; + progress.className = "pmdynaform-file-progress"; + progress.innerHTML = ""; + template.appendChild(preview); + template.setAttribute("data-toggle", "modal"); + template.setAttribute("data-target", "#myModal"); + this.viewsFiles.push({ + "id": file.id, + "data": template + }); + this.$el.find(".pmdynaform-file-droparea-ext").prepend(template); + } + return this; + }, + createBoxAudio: function (file) { + var model, + tplContainerAudio, + tplMediaAudio, + mediaElement; + model = { + src: file.filePath ? file.filePath : file, + extension: file.extension ? file.extension : null, + name: file.name + }; + + tplMediaAudio = this.templateMediaAudio(model); + mediaElement = new PMDynaform.core.MediaElement({ + el: $(tplMediaAudio), + type: "audio" + }); + + tplContainerAudio = $(this.templateAudio(model)); + tplContainerAudio.find(".pmdynaform-file-resizevideo").append(mediaElement.$el); + this.$el.find(".pmdynaform-file-droparea-ext").prepend(tplContainerAudio); + + this.viewsFiles.push({ + "id": file.id, + "data": tplContainerAudio + }); + return this; + }, + createBoxVideo: function (file) { + var model, + tplContainerVideo, + tplMediaVideo, + mediaElement, + + model = { + src: file.filePath ? file.filePath : file, + name: file.name + }; + tplMediaVideo = this.templateMediaVideo(model); + mediaElement = new PMDynaform.core.MediaElement({ + el: $(tplMediaVideo), + type: "video", + streaming: file.filePath ? false : true + }); + + tplContainerVideo = $(this.templateVideo(model)); + tplContainerVideo.find(".pmdynaform-file-resizevideo").append(mediaElement.$el); + this.$el.find(".pmdynaform-file-droparea-ext").prepend(tplContainerVideo); + + this.viewsFiles.push({ + "id": file.id, + "data": tplContainerVideo + }); + return this; + }, + createBoxPlus: function () { + var type = this.model.get("type"); + switch (type) { + case "imageMobile": + this.boxPlus = $(this.templatePlusImage()); + break; + case "audioMobile": + this.boxPlus = $(this.templatePlusAudio()); + break; + case "videoMobile": + this.boxPlus = $(this.templatePlusVideo()); + break; + default: + } + return this; + }, + changeID: function (arrayNew) { + var array = this.model.getFiles(), + itemNew, + itemOld; + for (var i = 0; i < arrayNew.length; i++) { + itemNew = arrayNew[i]; + for (var j = 0; j < array.length; j++) { + itemOld = array[j]; + if (typeof itemOld === "string") { + if (itemNew["idOld"] === itemOld) { + itemOld = itemNew["idNew"]; + } + } + if (typeof itemOld === "object") { + if (itemNew["idOld"] === itemOld["id"]) { + itemOld["id"] = itemNew["idNew"]; + } + } + } + } + }, + afterRender: function () { + var data = this.model.get("data"), + prj = this.model.get("project"); + if (data && data.value && prj && prj.loadDataField) { + this.setFilesRFC(data.value); + } + return this; + }, + /** + * Enable the validation when only property required is true + * @returns {FileMobile} + */ + enableValidation: function () { + if (this.model.get("required")) { + this.model.set("enableValidate", true); + this.showRequire(); + } + return this; + }, + /** + * Disable the validation when only property required is true + * @returns {FileMobile} + */ + disableValidation: function () { + if (this.model.get("required")) { + this.model.set("enableValidate", false); + if (_.isFunction(this.removeStyleError)) { + this.removeStyleError(); + } + if (this.validator) { + this.validator.$el.remove(); + } + this.hideRequire(); + } + return this; + }, + + /** + * Exchange the file ids. + * @param oldId + * @param newId + * @returns {FileMobile} + */ + exchangeMobileDataId: function (oldId, newId){ + this.model.exchangeMobileDataId(oldId, newId); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.FileMobile", FileMobile); +}()); + +(function () { + var ImageFieldView = PMDynaform.view.Field.extend({ + eventsMobile: { + PREVIEW: "image/preview", + UPLOAD_PROGRESS: "image/uploadProgress", + CANCEL: "image/request/cancel", + DELETE: "image/delete", + THUMBNAIL: "imageThumbnail/request" + }, + template: _.template($("#tpl-extfile").html()), + templateImage: _.template($("#tpl-extfile").html()), + templatePlusImage: _.template($("#tpl-extfile-plus-image").html()), + templateRenderingWeb: _.template($("#tpl-multimedia-renderingWeb").html()), + boxPlus: null, + viewsFiles: [], + mediaVideos: [], + validator: null, + messageRequired: "This field is required.".translate(), + events: { + "click buttonImage": "onClickAddImage", + "click .pmdynaform-file-resizeimage": "onClickPreviewImage", + }, + initialize: function () { + return this; + }, + + /** + * Delete File View + * @param fileId + */ + deleteFileView: function (fileId) { + var that = this; + var view = _.find(that.viewsFiles, function (obj) {return obj.id === fileId;}); + if (view && view.data.remove) { + view.data.remove(); + } + }, + /** + * Listen OnclickEvent for Mobile Controls + * @param event + * @returns {FileMobile} + */ + onClickAddImage: function (event) { + var type = this.model.get("type"), + that = this, + respData, + project = this.model.get("project"); + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + type: "image", + galleryEnabled: this.model.get("galleryEnabled"), + cameraEnabled: this.model.get("cameraEnabled") + }; + project.requestManager.getImage(respData); + + this.model.get("project").requestManager.channelEvents( + { + handler: this.model.get("id"), + type: this.eventsMobile.UPLOAD_PROGRESS, + bridge: false, + data: {}, + callback: function (event) { + that.updateProgressBar(event); + } + }); + + event.preventDefault(); + event.stopPropagation(); + return this; + }, + /** + * Cancel Upload Image, remove the file from model and view + * @param event + * @returns {ImageFieldView} + */ + onCancelUpload: function (event) { + var that = this; + this.model.get("project").requestManager.channelEvents( + { + handler: this.model.get("id"), + type: this.eventsMobile.CANCEL, + bridge: true, + data: { + idField: this.model.get("name"), + idFile: event.currentTarget.id, + id: this.model.get("id") + }, + callback: function (event) { + that.cancelProgressBar(event.idFile); + } + }); + this.model.deleteFile(event.currentTarget.id); + this.deleteFileView(event.currentTarget.id); + event.preventDefault(); + event.stopPropagation(); + return this; + }, + /** + * Cancel progressbar in image + * @param idFile + */ + cancelProgressBar: function (idFile) { + this.model.set("blockPreviewImage", false); + this.$el.find("img").css("opacity", 1); + $("#" + idFile).find("progress").css("display", "none"); + $("#" + idFile).find(".image-cancel").css("display", "none"); + }, + /** + * The update method about upload Progress bar from mobile api + * @param data + */ + updateProgressBar: function (data) { + if (data.value < 100) { + $("#" + data.idFile).find("progress").css("display", "block"); + this.model.set("blockPreviewImage", true); + this.model.set("fileInProgress", data.idFile); + this.$el.find("img").css("opacity", 0.2); + $("#" + data.idFile).find(".image-cancel-icon").css("marginTop", (this.$el.find("img").height() - 42) / 2); + $("#" + data.idFile).find(".image-cancel").css("display", "block"); + + } else { + this.model.set("blockPreviewImage", false); + this.model.set("fileInProgress", ""); + this.$el.find("img").css("opacity", 1); + $("#" + data.idFile).find("progress").css("display", "none"); + $("#" + data.idFile).find(".image-cancel").css("display", "none"); + } + $("#" + data.idFile).find("progress")[0].value = data.value; + }, + + /** + * Listen OnclickEvent for preview a image + * @param event + * @returns {FileMobile} + */ + onClickPreviewImage: function (event) { + var respData, + that = this, + project = this.model.get("project"); + respData = { + idField: this.model.get("name"), + docUid: this.model.get("inp_doc_uid"), + idFile: event.currentTarget.id, + type: "image", + value: this.model.get("files"), + availableOffline: this.model.get("availableOffline") + }; + + this.model.get("project").requestManager.channelEvents({ + handler: this.model.get("id"), + type: this.eventsMobile.DELETE, + bridge: false, + data: {}, + callback: function (event) { + that.model.deleteFile(event.idFile); + that.deleteFileView(event.idFile); + } + }); + + if (this.model.get("blockPreviewImage") === false) { + this.model.get("project").requestManager.channelEvents({ + handler: this.model.get("id"), + type: this.eventsMobile.PREVIEW, + bridge: true, + data: respData, + callback: function (event) { + } + }); + } else if (this.model.get("fileInProgress") === event.currentTarget.id) { + this.onCancelUpload(event); + } + return this; + }, + /** + * Validate a File Mobile Controls + * @returns {FileMobile} + */ + validate: function () { + if (this.validator) { + this.validator.$el.remove(); + if (_.isFunction(this.removeStyleError)) { + this.removeStyleError(); + } + } + + this.model.validate(); + if (!this.model.get("valid")) { + this.validator = new PMDynaform.view.Validator({ + model: new Backbone.Model({ + message: { + required: this.model.get("requiredFieldErrorMessage") || this.messageRequired + } + }) + }); + this.$el.find(".pmdynaform-field-control").append(this.validator.$el); + if (_.isFunction(this.applyStyleError)) { + this.applyStyleError(); + } + } + return this; + }, + /** + * This function apply style error in this field + * @returns {FileUpload} + */ + applyStyleError: function () { + this.$el.addClass("has-error has-feedback"); + this.$el.find(".pmdynaform-file-droparea-ext").addClass("file-mobile-error"); + return this; + }, + /** + * This function remove style error in this field + * @returns {FileUpload} + */ + removeStyleError: function () { + this.$el.removeClass('has-error has-feedback'); + this.$el.find(".pmdynaform-file-droparea-ext").removeClass("file-mobile-error"); + return this; + }, + /** + * Render component, in two format web and mobile + * @returns {ImageFieldView} + */ + render: function () { + var dataFiles, + nameField, + options = _.extend( + this.model.toJSON(), + { + dottedBox: !(this.model.get("mode") === "view" || (this.model.get("mode") === "parent" && this.model.get("parent").get("mode") === "view")) + } + ); + + if (PMDynaform.core.ProjectMobile) { + if (this.model.get("mode") === "edit" || (this.model.get("mode") === "parent" && this.model.get("parent").get("mode") === "edit")) { + this.boxPlus = $(this.templatePlusImage()); + } + this.$el.html(this.template(options)); + if (this.model.get("hint")) { + this.enableTooltip(); + } + this.$el.find(".pmdynaform-file-droparea-ext").append(this.boxPlus); + } else { + this.$el.html(this.template(options)); + dataFiles = this.project.mobileDataControls; + nameField = this.model.get("name"); + if (dataFiles.hasOwnProperty(nameField)) { + this.renderWeb(dataFiles[nameField]); + } + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * controls renders video, audio and image, according to the values + * obtained from the mobile version. + * @param items, is the list of the elements multimedia. + * @returns {HTMLElement} + */ + renderWeb: function (items) { + var ieVersion, + type = this.model.get("type"), + i, + viewFiles, + elements = [], + container = this.$el.find(".pmdynaform-file-control"), + downloadLink, + data, + linkService = "showDocument"; + if (_.isArray(items)) { + this.model.set({"data": {"value": items}}); + container.empty(); + ieVersion = PMDynaform.core.Utils.checkValidIEVersion(); + if (type === "imageMobile") { + elements = this.model.remoteProxyData(items); + } else { + for (i = 0; i < items.length; i += 1) { + data = { + uid: items[i], + type: linkService + }; + downloadLink = this.project.webServiceManager.showDocument(data); + data = $.extend(true, this.model.urlFileStreaming(items[i]), {downloadLink: downloadLink}); + elements.push(data); + } + } + viewFiles = this.templateRenderingWeb({ + elements: elements, + type: type, + ieVersion: ieVersion + }); + container.append(viewFiles); + } + }, + /** + * Set File data from mobile api + * @param arrayFiles + */ + setFilesRFC: function (arrayFiles) { + var type = this.model.get("type"), max = arrayFiles.length ? arrayFiles.length : 0, + i, + response; + + if (PMDynaform.core.ProjectMobile) { + response = arrayFiles; + } else { + if (max) { + response = this.model.remoteProxyData(arrayFiles); + } + } + if (response && response.length) { + for (i = 0; i < response.length; i += 1) { + this.updateFiles(response[i]); + } + } + }, + /** + * Create box and update array of files + * @param item + * @returns {FileMobile} + */ + updateFiles: function (item) { + if (_.isObject(item) && !_.isEmpty(item)) { + this.model.addItemFile(item); + this.createBoxFile(item); + } + return this; + }, + /** + * setFiles Function for set files images, video and audio from a interface to mobile + * @param {[type]} arrayFiles [description] + */ + setFiles: function (arrayFiles) { + var i; + for (i = 0; i < arrayFiles.length; i += 1) { + this.updateFiles(arrayFiles[i]); + } + this.validate(); + }, + /** + * Set data from Pmdynaform Project, from mobile api + * @param data + * @returns {ImageFieldView} + */ + setData: function (data) { + if (data && data["value"]) { + this.setFilesRFC(data["value"]); + } + return this; + }, + /** + * Create view for image + * @param file + * @returns {ImageFieldView} + */ + createBoxFile: function (file) { + var template = _.template($("#tpl-thumbnail-image").html()), + tplResp, + newSrc; + + if (file["filePath"]) { + newSrc = file["filePath"]; + } + if (file["base64"]) { + newSrc = this.model.makeBase64Image(file["base64"]); + } + + if (file["fileContent"]) { + newSrc = this.model.makeBase64Image(file["fileContent"]); + } + + if (newSrc) { + tplResp = $(template({ + id: Math.floor((Math.random() * 100000) + 3), + src: newSrc, + idFile: file.id + })); + + this.viewsFiles.push({ + "id": file.id, + "data": tplResp + }); + this.$el.find(".pmdynaform-file-containerimage.file-plus").before(tplResp); + } + return this; + }, + /** + * Execute when after render PMDynaform, subscribe listener for thumbnails in Mobile + * @returns {ImageFieldView} + */ + afterRender: function () { + var that = this, + data = this.model.get("data"), + prj = this.model.get("project"); + + if (PMDynaform.core.ProjectMobile) { + this.model.get("project").requestManager.channelEvents( + { + handler: this.model.get("id"), + type: this.eventsMobile.THUMBNAIL, + bridge: this.model.get("data").value.length == 0 ? false : true, + data: { + idField: this.model.get("id"), + images: this.model.get("data").value + }, + callback: function (imagesThumbnail) { + var ims = []; + _.forEach(imagesThumbnail, function (obj) { + ims.push({ + id: obj.fileId, + base64: obj.fileContent + }); + }) + + that.setFilesRFC(ims); + } + }); + + + } else { + if (data && data.value && prj && prj.loadDataField) { + this.setFilesRFC(data.value); + } + } + return this; + }, + /** + * Enable the validation when only property required is true + * @returns {FileMobile} + */ + enableValidation: function () { + if (this.model.get("required")) { + this.model.set("enableValidate", true); + this.showRequire(); + } + return this; + }, + /** + * Disable the validation when only property required is true + * @returns {FileMobile} + */ + disableValidation: function () { + if (this.model.get("required")) { + this.model.set("enableValidate", false); + if (_.isFunction(this.removeStyleError)) { + this.removeStyleError(); + } + if (this.validator) { + this.validator.$el.remove(); + } + this.hideRequire(); + } + return this; + }, + }); + + PMDynaform.extendNamespace("PMDynaform.view.ImageFieldView", ImageFieldView); +}()); + +(function () { + var GeoMobile = PMDynaform.view.Field.extend({ + item: null, + template: _.template($("#tpl-extgeo").html()), + templatePlus: _.template($("#tpl-extfile-plus").html()), + templateGeoDesktop: _.template($("#tpl-map").html()), + boxPlus: null, + boxModal: null, + boxBackground: null, + viewsImages: [], + imageOffLine: "geoMap.jpg", + events: { + "click button": "onClickButton" + }, + initialize: function () { + }, + onClickButton: function (event) { + var respData; + this.model.set("interactive", true); + respData = { + idField: this.model.get("name"), + interactive: true + }; + this.model.get("project").requestManager.getLocation(respData); + event.preventDefault(); + event.stopPropagation(); + return this; + }, + makeBase64Image: function (base64) { + return "data:image/png;base64," + base64; + }, + /** + * Create Box Geo Map + * @param data + * @returns {GeoMobile} + */ + createBox: function (data) { + var rand, + newsrc, + template, + resizeImage, + preview; + + if (data.base64) { + this.clearBox(); + newsrc = this.makeBase64Image(data.base64); + rand = Math.floor((Math.random() * 100000) + 3); + template = document.createElement("div"); + resizeImage = document.createElement("div"); + preview = document.createElement("span"); + + template.id = rand; + template.className = "pmdynaform-file-containergeo"; + resizeImage.className = "pmdynaform-file-resizeimage"; + resizeImage.innerHTML = ''; + + preview.id = rand; + preview.className = "pmdynaform-file-preview"; + preview.appendChild(resizeImage); + template.appendChild(preview); + this.$el.find(".pmdynaform-ext-geo").prepend(template); + this.hideButton(); + } + return this; + }, + /** + * Clear Box Geo Map + * @returns {GeoMobile} + */ + clearBox: function () { + var htmlBox = this.$el.find(".pmdynaform-ext-geo"); + if (htmlBox.length) { + htmlBox.empty(); + } + return this; + }, + /** + * Hide Button Map + */ + hideButton: function () { + var button; + button = this.$el.find("button"); + button.hide(); + }, + render: function () { + var that = this, + fileContainer, + fileControl, + auxClass, + geomapDesktop, + that = this, + data, + canvasMap, + coords, + latitude, + longitude, + altitude; + if (PMDynaform.core.ProjectMobile) { + this.$el.html(this.template(this.model.toJSON())); + fileContainer = this.$el.find(".pmdynaform-file-droparea-ext")[0]; + fileControl = this.$el.find("input")[0]; + } else { + this.$el.html(this.templateGeoDesktop(this.model.toJSON())); + auxClass = function (params) { + this.project = params.project; + }; + auxClass.prototype.load = function () { + canvasMap = that.$el.find(".pmdynaform-map-canvas"); + coords, mapOptions, map, marker; + if (that.project.mobileDataControls) { + if (that.project.mobileDataControls) { + data = that.project.mobileDataControls[that.model.get("name")]; + if (data) { + latitude = data["latitude"] || 0; + longitude = data["longitude"] || 0; + altitude = data["altitude"] || 0; + coords = new google.maps.LatLng(latitude, longitude); + mapOptions = { + zoom: 15, + center: coords, + panControl: false, + zoomControl: false, + scaleControl: true, + streetViewControl: false, + overviewMapControl: false, + mapTypeControl: true, + navigationControlOptions: { + style: google.maps.NavigationControlStyle.SMALL + }, + mapTypeId: google.maps.MapTypeId.ROADMAP + }; + map = new google.maps.Map(canvasMap[0], mapOptions); + marker = new google.maps.Marker({ + position: coords, + map: map, + draggable: false, + title: "" + }); + } + } + } + }; + window.pmd = new auxClass({project: this}); + var script = document.createElement('script'); + script.type = 'text/javascript'; + $(script).data("script", "google"); + script.src = "https://maps.googleapis.com/maps/api/js?callback=pmd.load"; + script.src += window.pmd.project.googleMaps.key ? "&key=" + window.pmd.project.googleMaps.key : ""; + document.body.appendChild(script); + } + if (this.model.get("hint")) { + this.enableTooltip(); + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + /** + * Set Location + * @param location + */ + setLocation: function (location) { + var newLocation = {}, + imageResponse, + render; + if (location && typeof location === "object" && !_.isEmpty(location)) { + render = location.hasOwnProperty("render") && !location.render? location.render : true; + newLocation = { + idField: location.idField, + id: location.id, + base64: null, + latitude: location.latitude, + longitude: location.longitude, + altitude: location.altitude + }; + this.setGeoData(newLocation); + if (render) { + imageResponse = this.model.remoteProxyData(newLocation.id); + if (imageResponse) { + newLocation.base64 = imageResponse.base64; + this.createBox(newLocation); + } + } + } + }, + createImageOffLine: function (location) { + location["filePath"] = this.imageOffLine; + this.createBox({ + filePath: this.imageOffLine + }); + }, + setData: function (data) { + if (data["value"] && data["value"] !== "") + this.setLocation(data["value"]); + return this; + }, + /** + * Function for after render in dynaforms + * @returns {GeoMobile} + */ + afterRender: function () { + var data = this.model.get("data"), + prj = this.model.get("project"); + if (data && data.value && prj && prj.loadDataField) { + this.setLocation(data.value); + } + return this; + }, + /** + * Get Geo Data from View + * @returns {*} + */ + getGeoData: function () { + return this.model.getGeoData(); + }, + /** + * Set Geo Data Model From View + * @param data + * @returns {GeoMobile} + */ + setGeoData: function (data) { + this.model.setGeoData(data); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.view.GeoMobile", GeoMobile); +}()); + +(function () { + var MediaElement = function (settings) { + this.el = settings.el; + this.$el = settings.el; + this.streaming = settings.streaming ? settings.streaming : null; + this.type = settings.type; + if (this.type == "video") { + MediaElement.prototype.initVideo.call(this, this.el); + } + if (this.type == "audio") { + MediaElement.prototype.initAudio.call(this, this.el); + } + }; + + MediaElement.prototype.initVideo = function (element) { + var video = element.find("video"); + var control = element.find(".pmdynaform-media-control"); + //remove default control when JS loaded + video[0].removeAttribute("controls"); + element.find('.pmdynaform-media-control').fadeIn(500); + element.find('.pmdynaform-media-caption').fadeIn(500); + + //before everything get started + video.on('loadedmetadata', function () { + + //set video properties + element.find('.current').text(timeFormat(0)); + element.find('.duration').text(timeFormat(video[0].duration)); + updateVolume(0, 0.7); + + //start to get video buffering data + setTimeout(startBuffer, 150); + //bind video events + }); + + //display video buffering bar + var startBuffer = function () { + var that = this; + var currentBuffer = video[0].buffered.end(0); + var maxduration = video[0].duration; + var perc = 100 * currentBuffer / maxduration; + element.find('.pmdynaform-media-bufferBar').css('width', perc + '%'); + + if (currentBuffer < maxduration) { + setTimeout(startBuffer, 500); + } + }; + + //display current video play time + video.on('timeupdate', function () { + var currentPos = video[0].currentTime; + var maxduration = video[0].duration; + var perc = 100 * currentPos / maxduration; + element.find('.pmdynaform-media-timeBar').css('width', perc + '%'); + element.find('.current').text(timeFormat(currentPos)); + }); + + //CONTROLS EVENTS + //video screen and play button clicked + video.on('click', function () { + playpause(); + }); + element.find('.btnPlay').on('click', function () { + playpause(); + }); + var playpause = function () { + if (kitKatMode != null) { + JsInterface.startVideo(video[0].src, "video/mp4"); + } else { + if (video[0].paused) { + element.find('.btnPlay').addClass('paused'); + element.find('.btnPlay').find('.glyphicon.glyphicon-play').addClass('glyphicon glyphicon-pause').removeClass('glyphicon-play'); + video[0].play(); + } + else { + element.find('.btnPlay').removeClass('paused'); + element.find('.btnPlay').find('.glyphicon.glyphicon-pause').addClass('glyphicon glyphicon-play').removeClass('glyphicon-pause'); + video[0].pause(); + } + } + }; + + + //fullscreen button clicked + element.find('.btnFS').on('click', function () { + if ($.isFunction(video[0].webkitEnterFullscreen)) { + video[0].webkitEnterFullscreen(); + } + else if ($.isFunction(video[0].mozRequestFullScreen)) { + video[0].mozRequestFullScreen(); + } + else { + alert('Your browsers doesn\'t support fullscreen'); + } + }); + + //sound button clicked + element.find('.sound').click(function () { + video[0].muted = !video[0].muted; + $(this).toggleClass('muted'); + if (video[0].muted) { + element.find('.pmdynaform-media-volumeBar').css('width', 0); + } + else { + element.find('.pmdynaform-media-volumeBar').css('width', video[0].volume * 100 + '%'); + } + }); + + //VIDEO EVENTS + //video canplay event + video.on('canplay', function () { + element.find('.loading').fadeOut(100); + }); + + //video canplaythrough event + //solve Chrome cache issue + var completeloaded = false; + video.on('canplaythrough', function () { + completeloaded = true; + }); + + //video ended event + video.on('ended', function () { + element.find('.btnPlay').removeClass('paused'); + video[0].pause(); + }); + + //video seeking event + video.on('seeking', function () { + //if video fully loaded, ignore loading screen + if (!completeloaded) { + element.find('.loading').fadeIn(200); + } + }); + + //video seeked event + video.on('seeked', function () { + }); + + //video waiting for more data event + video.on('waiting', function () { + element.find('.loading').fadeIn(200); + }); + + //VIDEO PROGRESS BAR + //when video timebar clicked + var timeDrag = false; + /* check for drag event */ + element.find('.pmdynaform-media-progress').on('mousedown', function (e) { + timeDrag = true; + updatebar(e.pageX); + }); + $(document).on('mouseup', function (e) { + if (timeDrag) { + timeDrag = false; + updatebar(e.pageX); + } + }); + $(document).on('mousemove', function (e) { + if (timeDrag) { + updatebar(e.pageX); + } + }); + var updatebar = function (x) { + var progress = element.find('.pmdynaform-media-progress'); + + //calculate drag position + //and update video currenttime + //as well as progress bar + var maxduration = video[0].duration; + var position = x - progress.offset().left; + var percentage = 100 * position / progress.width(); + if (percentage > 100) { + percentage = 100; + } + if (percentage < 0) { + percentage = 0; + } + element.find('.pmdynaform-media-timeBar').css('width', percentage + '%'); + video[0].currentTime = maxduration * percentage / 100; + }; + + //VOLUME BAR + //volume bar event + var volumeDrag = false; + element.find('.pmdynaform-media-volume').on('mousedown', function (e) { + volumeDrag = true; + video[0].muted = false; + element.find('.sound').removeClass('muted'); + updateVolume(e.pageX); + }); + $(document).on('mouseup', function (e) { + if (volumeDrag) { + volumeDrag = false; + updateVolume(e.pageX); + } + }); + $(document).on('mousemove', function (e) { + if (volumeDrag) { + updateVolume(e.pageX); + } + }); + var updateVolume = function (x, vol) { + var volume = element.find('.pmdynaform-media-volume'); + var percentage; + //if only volume have specificed + //then direct update volume + if (vol) { + percentage = vol * 100; + } + else { + var position = x - volume.offset().left; + percentage = 100 * position / volume.width(); + } + + if (percentage > 100) { + percentage = 100; + } + if (percentage < 0) { + percentage = 0; + } + + //update volume bar and video volume + element.find('.pmdynaform-media-volumeBar').css('width', percentage + '%'); + video[0].volume = percentage / 100; + + //change sound icon based on volume + if (video[0].volume == 0) { + element.find('.sound').removeClass('sound2').addClass('muted'); + } + else if (video[0].volume > 0.5) { + element.find('.sound').removeClass('muted').addClass('sound2'); + } + else { + element.find('.sound').removeClass('muted').removeClass('sound2'); + } + + }; + + //Time format converter - 00:00 + var timeFormat = function (seconds) { + var m = Math.floor(seconds / 60) < 10 ? "0" + Math.floor(seconds / 60) : Math.floor(seconds / 60); + var s = Math.floor(seconds - (m * 60)) < 10 ? "0" + Math.floor(seconds - (m * 60)) : Math.floor(seconds - (m * 60)); + return m + ":" + s; + }; + this.$el = element; + }; + + + MediaElement.prototype.initAudio = function (element) { + var video = element.find("audio"); + var control = element.find(".pmdynaform-media-control"); + //remove default control when JS loaded + video[0].removeAttribute("controls"); + element.find('.pmdynaform-media-control').fadeIn(500); + element.find('.pmdynaform-media-caption').fadeIn(500); + + //before everything get started + video.on('loadedmetadata', function () { + + //set video properties + element.find('.current').text(timeFormat(0)); + element.find('.duration').text(timeFormat(video[0].duration)); + updateVolume(0, 0.7); + + //start to get video buffering data + setTimeout(startBuffer, 150); + + //bind video events + }); + + //display video buffering bar + var startBuffer = function () { + var that = this; + var currentBuffer = video[0].buffered.end(0); + var maxduration = video[0].duration; + var perc = 100 * currentBuffer / maxduration; + element.find('.pmdynaform-media-bufferBar').css('width', perc + '%'); + + if (currentBuffer < maxduration) { + setTimeout(startBuffer, 500); + } + }; + + //display current video play time + video.on('timeupdate', function () { + var currentPos = video[0].currentTime; + var maxduration = video[0].duration; + var perc = 100 * currentPos / maxduration; + element.find('.pmdynaform-media-timeBar').css('width', perc + '%'); + element.find('.current').text(timeFormat(currentPos)); + }); + + //CONTROLS EVENTS + //video screen and play button clicked + video.on('click', function () { + playpause(); + }); + element.find('.btnPlay').on('click', function () { + playpause(); + }); + var playpause = function () { + if (kitKatMode != null) { + JsInterface.startVideo(video[0].src, "audio/mp4"); + } else { + if (video[0].paused || video[0].ended) { + element.find('.btnPlay').addClass('paused'); + element.find('.btnPlay').find('.glyphicon.glyphicon-play').addClass('glyphicon-pause').removeClass('glyphicon-play'); + video[0].play(); + } + else { + element.find('.btnPlay').removeClass('paused'); + element.find('.btnPlay').find('.glyphicon.glyphicon-pause').removeClass('glyphicon-pause').addClass('glyphicon-play'); + video[0].pause(); + } + } + }; + + + //fullscreen button clicked + element.find('.btnFS').on('click', function () { + if ($.isFunction(video[0].webkitEnterFullscreen)) { + video[0].webkitEnterFullscreen(); + } + else if ($.isFunction(video[0].mozRequestFullScreen)) { + video[0].mozRequestFullScreen(); + } + else { + alert('Your browsers doesn\'t support fullscreen'); + } + }); + + //sound button clicked + element.find('.sound').click(function () { + video[0].muted = !video[0].muted; + $(this).toggleClass('muted'); + if (video[0].muted) { + element.find('.pmdynaform-media-volumeBar').css('width', 0); + } + else { + element.find('.pmdynaform-media-volumeBar').css('width', video[0].volume * 100 + '%'); + } + }); + + //VIDEO EVENTS + //video canplay event + video.on('canplay', function () { + element.find('.loading').fadeOut(100); + }); + + //video canplaythrough event + //solve Chrome cache issue + var completeloaded = false; + video.on('canplaythrough', function () { + completeloaded = true; + }); + + //video ended event + video.on('ended', function () { + element.find('.btnPlay').removeClass('paused'); + video[0].pause(); + }); + + //video seeking event + video.on('seeking', function () { + //if video fully loaded, ignore loading screen + if (!completeloaded) { + element.find('.loading').fadeIn(200); + } + }); + + //video seeked event + video.on('seeked', function () { + }); + + //video waiting for more data event + video.on('waiting', function () { + element.find('.loading').fadeIn(200); + }); + + //VIDEO PROGRESS BAR + //when video timebar clicked + var timeDrag = false; + /* check for drag event */ + element.find('.pmdynaform-media-progress').on('mousedown', function (e) { + timeDrag = true; + updatebar(e.pageX); + }); + $(document).on('mouseup', function (e) { + if (timeDrag) { + timeDrag = false; + updatebar(e.pageX); + } + }); + $(document).on('mousemove', function (e) { + if (timeDrag) { + updatebar(e.pageX); + } + }); + var updatebar = function (x) { + var progress = element.find('.pmdynaform-media-progress'); + + //calculate drag position + //and update video currenttime + //as well as progress bar + var maxduration = video[0].duration; + var position = x - progress.offset().left; + var percentage = 100 * position / progress.width(); + if (percentage > 100) { + percentage = 100; + } + if (percentage < 0) { + percentage = 0; + } + element.find('.pmdynaform-media-timeBar').css('width', percentage + '%'); + video[0].currentTime = maxduration * percentage / 100; + }; + + //VOLUME BAR + //volume bar event + var volumeDrag = false; + element.find('.pmdynaform-media-volume').on('mousedown', function (e) { + volumeDrag = true; + video[0].muted = false; + element.find('.sound').removeClass('muted'); + updateVolume(e.pageX); + }); + $(document).on('mouseup', function (e) { + if (volumeDrag) { + volumeDrag = false; + updateVolume(e.pageX); + } + }); + $(document).on('mousemove', function (e) { + if (volumeDrag) { + updateVolume(e.pageX); + } + }); + var updateVolume = function (x, vol) { + var volume = element.find('.pmdynaform-media-volume'); + var percentage; + //if only volume have specificed + //then direct update volume + if (vol) { + percentage = vol * 100; + } + else { + var position = x - volume.offset().left; + percentage = 100 * position / volume.width(); + } + + if (percentage > 100) { + percentage = 100; + } + if (percentage < 0) { + percentage = 0; + } + + //update volume bar and video volume + element.find('.pmdynaform-media-volumeBar').css('width', percentage + '%'); + video[0].volume = percentage / 100; + + //change sound icon based on volume + if (video[0].volume == 0) { + element.find('.sound').removeClass('sound2').addClass('muted'); + } + else if (video[0].volume > 0.5) { + element.find('.sound').removeClass('muted').addClass('sound2'); + } + else { + element.find('.sound').removeClass('muted').removeClass('sound2'); + } + + }; + + //Time format converter - 00:00 + var timeFormat = function (seconds) { + var m = Math.floor(seconds / 60) < 10 ? "0" + Math.floor(seconds / 60) : Math.floor(seconds / 60); + var s = Math.floor(seconds - (m * 60)) < 10 ? "0" + Math.floor(seconds - (m * 60)) : Math.floor(seconds - (m * 60)); + return m + ":" + s; + }; + this.$el = element; + }; + PMDynaform.extendNamespace("PMDynaform.core.MediaElement", MediaElement); + +}()); + + +(function () { + var Qrcode_mobile = PMDynaform.view.Field.extend({ + item: null, + template: _.template($("#tpl-ext-scannercode").html()), + templatePlus: _.template($("#tpl-extfile-plus").html()), + templateCode: _.template($("#tpl-ext-scanner-code").html()), + boxPlus: null, + boxModal: null, + boxBackground: null, + viewsImages: [], + events: { + "click button": "onClickButton" + }, + initialize: function () { + }, + onClickButton: function (event) { + var respData = { + idField: this.model.get("name") + }; + + this.model.get("project").requestManager.getScannerCode(respData); + event.preventDefault(); + event.stopPropagation(); + return this; + }, + hideButton: function () { + var button; + button = this.$el.find("button"); + button.hide(); + }, + showLabel: function (scannercode) { + var container; + container = this.$el.find("scanner").find(".pmdynaform-label-options"); + container.append(this.templateCode({label: scannercode})); + }, + render: function () { + var that = this, + data; + if (PMDynaform.core.ProjectMobile) { + this.$el.html(this.template(this.model.toJSON())); + } else { + this.$el.html(this.template(this.model.toJSON())); + if (that.project.mobileDataControls) { + if (that.project.mobileDataControls) { + data = that.project.mobileDataControls[that.model.get("name")]; + if (data) { + this.setScannerCode(data); + } + } + } + this.$el.find("button").detach(); + } + if (this.model.get("hint")) { + this.enableTooltip(); + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setScannerCode: function (scannercode) { + var model, i; + model = this.model; + if (_.isArray(scannercode)) { + for (i = 0; i < scannercode.length; i += 1) { + model.addCode(scannercode[i]); + this.showLabel(scannercode[i]); + } + } else { + model.addCode(scannercode.data); + this.showLabel(scannercode.data); + } + return this; + }, + setData: function (data) { + this.setScannerCode(data["value"]); + return this; + }, + readFileDeviceScanner: function (data) { + var str; + $.ajax({ + url: data.data, + dataType: 'text', + async: false, + success: function (data, xhr) { + str = data; + } + }); + this.setScannerCode({data: str}); + return this; + }, + /** + * Function for after render in dynaforms + * @returns {Qrcode_mobile} + */ + afterRender: function () { + var data = this.model.get("data"), + prj = this.model.get("project"); + if (data && data.value && prj && prj.loadDataField) { + this.setScannerCode(data.value); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Qrcode_mobile", Qrcode_mobile); +}()); + +(function () { + var Signature_mobile = PMDynaform.view.Field.extend({ + item: null, + template: _.template($("#tpl-ext-signature").html()), + templatePlus: _.template($("#tpl-extfile-plus").html()), + viewsImages: [], + imageOffLine: "geoMap.jpg", + events: { + "click button": "onClickButton" + }, + initialize: function () { + + }, + onClickButton: function (event) { + var respData; + this.model.set("interactive", true); + respData = { + idField: this.model.get("name") + }; + + this.model.get("project").requestManager.getSignature(respData); + event.preventDefault(); + event.stopPropagation(); + return this; + }, + makeBase64Image: function (base64) { + return "data:image/png;base64," + base64; + }, + createBox: function (data) { + var rand, + newsrc, + template, + resizeImage, + preview, + progress; + + if (data.filePath) { + newsrc = data.filePath; + } else { + newsrc = this.makeBase64Image(data.base64); + } + rand = Math.floor((Math.random() * 100000) + 3); + + template = document.createElement("div"), + resizeImage = document.createElement("div"), + preview = document.createElement("span"), + progress = document.createElement("div"); + + template.id = rand; + template.className = "pmdynaform-file-containergeo"; + + resizeImage.className = "pmdynaform-file-resizeimage"; + resizeImage.innerHTML = ''; + preview.id = rand; + preview.className = "pmdynaform-file-preview"; + preview.appendChild(resizeImage); + template.appendChild(preview); + this.$el.find(".pmdynaform-ext-signature").prepend(template); + this.hideButton(); + return this; + }, + hideButton: function () { + var button; + button = this.$el.find("button"); + button.hide(); + }, + render: function () { + var fileContainer, + fileControl, + signature, + files = [], + itemElement; + if (PMDynaform.core.ProjectMobile) { + this.$el.html(this.template(this.model.toJSON())); + fileContainer = this.$el.find(".pmdynaform-file-droparea-ext")[0]; + fileControl = this.$el.find("input")[0]; + } else { + this.$el.html(this.template(this.model.toJSON())); + fileContainer = this.$el.find(".pmdynaform-ext-signature").empty(); + this.$el.find("button").hide(); + if (this.project.mobileDataControls) { + signature = this.project.mobileDataControls; + if (signature && signature[this.model.get("name")] && signature[this.model.get("name")].length > 0) { + signature = signature[this.model.get("name")]; + signature = this.model.remoteProxyData(signature[0]); + files.push(signature); + this.model.set("files", files); + itemElement = $("Thumbnail Image"); + fileContainer.append(itemElement); + } + } + } + if (this.model.get("hint")) { + this.enableTooltip(); + } + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + setFiles: function (arrayFiles) { + for (var i = 0; i < arrayFiles.length; i++) { + this.createBox(arrayFiles[i]); + this.model.attributes.files.push(arrayFiles[i]); + } + }, + setSignature: function (arraySignature) { + var i, + response, + files = []; + for (i = 0; i < arraySignature.length; i++) { + if (typeof arraySignature[i] === "string") { + response = this.model.remoteProxyData(arraySignature[i]); + this.createBox(response); + files.push(response); + + } else { + this.createBox(arraySignature[i]); + files.push(arraySignature[i]); + } + } + this.model.set("files", files); + }, + changeID: function (arrayNew) { + var array = this.model.attributes.files, + itemNew, + itemOld; + for (var i = 0; i < arrayNew.length; i++) { + itemNew = arrayNew[i]; + for (var j = 0; j < array.length; j++) { + itemOld = array[j]; + if (typeof itemOld === "string") { + if (itemNew["idOld"] === itemOld) { + itemOld = itemNew["idNew"]; + } + } + if (typeof itemOld === "object") { + if (itemNew["idOld"] === itemOld["id"]) { + itemOld["id"] = itemNew["idNew"]; + } + } + } + } + }, + setData: function (data) { + this.setSignature(data["value"]); + return this; + }, + /** + * Function for after render in dynaforms + * @returns {Signature_mobile} + */ + afterRender: function () { + var data = this.model.get("data"), + prj = this.model.get("project"); + if (data && data.value && prj && prj.loadDataField) { + this.setSignature(data.value); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.view.Signature_mobile", Signature_mobile); +}()); + +(function () { + + var Validator = Backbone.Model.extend({ + defaults: { + message: {}, + title: "", + type: "", + dataType: "", + value: "", + valid: true, + maxLength: null, + required: false, + requiredFieldErrorMessage: "", + domain: false, + options: [], + factory: {}, + valueDomain: null, + regExp: null, + requiredGrid: false, + haveOptions: [ + "suggest", + "checkbox", + "radio", + "dropdown" + ] + }, + initialize: function () { + var factoryValidator = { + "text": "requiredText", + "checkbox": "requiredCheckBox", + "checkgroup": "requiredCheckGroup", + "radio": "requiredRadioGroup", + "dropdown": "requiredDropDown", + "textarea": "requiredText", + "datetime": "requiredText", + "suggest": "requiredText", + "file": "requiredFile", + "grid": "requiredGrid" + }; + this.setFactory(factoryValidator); + this.checkDomainProperty(); + }, + setFactory: function (obj) { + this.set("factory", obj); + return this; + }, + checkDomainProperty: function () { + this.attributes.domain = ($.inArray(this.get("type"), this.get("haveOptions")) >= 0) ? true : false; + return this; + }, + verifyValue: function () { + var value = this.get('value'), + valueDomain = this.get('valueDomain'), + options = this.get('options'), + validator = this.attributes.factory[this.get("type").toLowerCase()], + regExp; + + this.set("valid", true); + delete this.get("message")[validator]; + if (this.get('type') == 'file') { + if (this.get('fileOnly') && this.get('fileOnly') !== null) { + if (this.get('fileOnly')['type'] == 'support') { + this.set('valid', false); + this.set('message', { + validator: this.get('fileOnly')['message'] + }); + return this; + } + if (this.get('fileOnly')['type'] == 'size') { + this.set('valid', false); + this.set('message', { + validator: this.get('fileOnly')['message'] + }); + return this; + } + } + } + if (this.get("required")) { + if (PMDynaform.core.Validators[validator].fn(value) === false) { + this.set("valid", false); + this.set("message", { + validator: this.get("requiredFieldErrorMessage") || + PMDynaform.core.Validators[validator].message + }); + return this; + } + } + if (this.get("type") === "text" || this.get("type") === "textarea") { + if (this.get("dataType") !== "" && value !== "") { + if (PMDynaform.core.Validators[this.get("dataType")] && + PMDynaform.core.Validators[this.get("dataType")].fn(value) === false) { + this.set("valid", false); + this.set("message", { + "validator": PMDynaform.core.Validators[this.get("dataType")].message + }); + return this; + } + } + + if (this.get("maxLength")) { + if (PMDynaform.core.Validators.maxLength.fn(value, parseInt(this.get("maxLength"))) === false) { + this.set("valid", false); + this.set("message", { + validator: PMDynaform.core.Validators.maxLength.message + " " + this.get("maxLength") + " characters" + }); + return this; + } + } + + if (this.get("regExp") && this.get("regExp").validate !== "") { + regExp = new RegExp(this.get("regExp").validate); + if (value.length > 0 && !regExp.test(value)) { + this.set("valid", false); + this.set("message", {validator: this.get("regExp").message}); + } else { + this.set('valid', true); + } + return this; + } + } + return this; + }, + /** + * verifies that meets validation having at least one row + * when the grid is required + * @returns {Validator} + */ + verifyGrid: function () { + if (this.get("required")) { + if (PMDynaform.core.Validators["requiredGrid"].fn(this.get("rowsNumber")) === false) { + this.set("valid", false); + this.set("message", { + validator: this.get("requiredFieldErrorMessage") || + PMDynaform.core.Validators["requiredGrid"].message + }); + } else { + this.set('valid', true); + } + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Validator", Validator); + +}()); +(function () { + var PanelModel = Backbone.Model.extend({ + defaults: { + items: [], + mode: "edit", + namespace: "pmdynaform", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("form"), + type: "form", + onBeforePrintHandler: null, + onAfterPrintHandler: null, + jsonOptions: { + id: null, + fields: {} + } + }, + getData: function () { + return { + type: this.get("type"), + name: this.get("name"), + variables: {} + } + }, + /** + * Update a json from a specific Field + * @param id + * @param jsonModel + */ + updateModel: function (id, jsonModel) { + this.browseFields(this.attributes, function (obj) { + if (obj.id === id) { + _.extend(obj, jsonModel); + } + }); + }, + /** + * Update the json model Options from fields in dynaform + * @param id + * @param jsonModel + */ + updateJsonOptions: function (id, jsonModel) { + if (this.attributes.jsonOptions.fields && id != "") { + this.attributes.jsonOptions.fields[id] = jsonModel + } + }, + /** + * Return the JSON definition Model + * @returns {*} + */ + getJsonOptions: function () { + var js = this.get("jsonOptions"); + js.id = this.attributes.items[0].id; + return js; + }, + /** + * Return the JSON definition Model + * @returns {*} + */ + getJson: function () { + var mod = this.toJSON(); + delete mod.items[0].parent; + return mod; + }, + /** + * Search a specific Field in Json Definition + * @param json + * @param callbackAction + * @returns {PanelModel} + */ + browseFields: function (json, callbackAction) { + var that = this; + if ((_.isObject(json) || _.isArray(json)) && _.isFunction(callbackAction)) { + _.mapObject(json, function (value, key, obj) { + if (key === "type" && key != "parent" && obj.hasOwnProperty(key)) { + if (_.isObject(obj) && _.has(obj, "id") && _.has(obj, "type")) { + callbackAction(obj); + } + } + if (_.isObject(value) && obj.hasOwnProperty(key) && key != "parent") { + that.browseFields(value, callbackAction); + } + }); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Panel", PanelModel); + +}()); +(function() { + var FormPanel = Backbone.Model.extend({ + defaults: { + action: "", + autocomplete: "on", + script: {}, + data: [], + items: [], + name: 'PMDynaform-form', + method: "get", + namespace: "pmdynaform", + target: null, + type: "panel", + inputDocuments: {}, + printable: false, + project: null, + /** + * @param {PMDynaform.util.DependentsFieldManager}, dependentsManager: Dependent field event handler + */ + dependentsManager: null, + /** + * @param {object}, dependencyRelations: Dependent field relation + */ + dependencyRelations: {}, + /** + * @param {object}, fields: Fields that belong to this form + */ + fields: {}, + /** + * @param {PMDynaform.util.ArrayList}, subForms: Set of subforms + */ + subForms: null, + visited: [], + rootField: null + }, + getData: function() { + return { + type: this.get("type"), + action: this.get("action"), + method: this.get("method") + } + }, + /** + * initialize the model of the Form and Reset parameters + * @chainable + */ + initialize: function() { + this.set("dependencyRelations", {}); + this.set("fields", {}); + this.set("subForms", new PMDynaform.util.ArrayList()); + this.set("dependentsManager", null); + this.set("dependentsManager", + new PMDynaform.util.DependentsFieldManager({ + form: this + })); + return this; + }, + /** + * This method closes this form, stand alone version for mobile + * @returns {FormPanel} + */ + close: function() { + var project = this.get("project"), + windowMain; + if (project) { + if (project.isMobile() && project.requestManager) { + project.requestManager.closeForm(); + } else { + if (!project.isPreview) { + windowMain = this.getMainWindowFrame(); + windowMain.parent.location.reload(true); + } + } + } + return this; + }, + /** + * Get the main window + * @returns {Window} + */ + getMainWindowFrame: function() { + var windowMain = window.parent; + while (windowMain && windowMain.frameElement && windowMain.frameElement["name"] !== "casesFrame") { + windowMain = windowMain.parent; + } + return windowMain; + }, + /** + * addField, Register a new field created in this form + * @chainable + */ + addField: function(field, key) { + var fields; + fields = this.get("fields"); + if (field && key) { + fields[key] = field; + } + return this; + }, + /** + * dispachEvents, Executes logged events when a field that has dependents changes its value + * @chainable + */ + dispachEvents: function(nameToRegisterEvent, target, data) { + this.get("dependentsManager").notify({ + registrationName: nameToRegisterEvent, + target: target, + data: data + }); + return this; + }, + /** + * addEvent, Records a new dependent field event + * @chainable + */ + addEvent: function(field, callback, target) { + this.get("dependentsManager").addEvent(field, callback, target); + return this; + }, + /** + * detachRegisteredEvents, Disable Events Logged on the Dependent Field Handler + * @chainable + */ + detachRegisteredEvents: function(field, target) { + this.get("dependentsManager").removeEvent(field, target); + return this; + }, + /** + * Retrieves the options when a field is dependent and needs the options for drawing, + * this method is currently working on radio type and checkgroup + */ + loadSqlOptionsInFields: function() { + var item, + relations = this.get("dependencyRelations"), + i, + dependents, + dependent, + optionsSql; + for (item in relations) { + if (relations.hasOwnProperty(item)) { + dependents = relations[item]; + for (i = 0; i < dependents.length; i += 1) { + dependent = dependents[i]; + optionsSql = dependent.get("optionsSql"); + if (!_.isEmpty(dependent.get("sql")) && _.isArray(optionsSql) + && _.isEmpty(optionsSql) && typeof dependent.loadRemotesOptions === "function") { + dependent.loadRemotesOptions(); + } + } + } + } + return this; + }, + /** + * registerNewDependencyRelation, Prepares to Record Dependent Field for a Field That Has Dependents + * @chainable + */ + registerNewDependencyRelation: function(name) { + var relations; + relations = this.get("dependencyRelations"); + if (!relations.hasOwnProperty(name)) { + relations[name] = []; + } + return this; + }, + /** + * registerNewDependent,Registers a new dependent field + * @chainable + */ + registerNewDependent: function(dependency, dependent) { + var relations; + relations = this.get("dependencyRelations"); + if (relations.hasOwnProperty(dependency)) { + relations[dependency].push(dependent); + } + return this; + }, + /** + * setAppData: Sets the data to the form, set _label too + * @param data {object} Set of valid data for the form + */ + setAppData: function(data) { + var dependency, + key, + field, + dataForDependent; + for (key in data) { + if (data.hasOwnProperty(key)) { + field = this.getField(key); + if (field) { + if (this.needsValueAndLabelToSetData(field)) { + field.setAppData({ + value: data[key], + label: data[key + "_label"] + }); + } else { + if (field.isDependent && field.isDependent()) { + dataForDependent = this.dependentFilterData(field.get("dependency"), data); + } + field.setAppData(data[key], dataForDependent); + } + } + } + } + return this; + }, + /** + * needsValueAndLabelToSetData, Evaluates if it is necessary to send data with value and label + * @param field {object}, the efected field + * @returns {boolean} result + */ + needsValueAndLabelToSetData: function(field) { + var needs = ["suggest", "file", "dropdown"], + type, + mode; + if (field) { + type = field.get("type"); + mode = field.get("mode"); + type = mode === "view" ? field.get("originalType") : type; + if (needs.indexOf(type) > -1) { + return true; + } + } + return false; + }, + + /** + * dependentFilterData, If the field is dependent, construct the data by + * performing the search of the values in the appdata + * @param dependency {array}, Values on which it depends + * @param appData {object}, Set of valid data for the form + * @returns newAppData {object} + */ + dependentFilterData: function(dependency, appData) { + var newAppData = {}, + i, + item; + if (_.isArray(dependency)) { + for (i = 0; i < dependency.length; i += 1) { + item = dependency[i]; + if (appData.hasOwnProperty(item)) { + newAppData[item] = appData[item]; + } + } + } + return newAppData; + }, + /** + * getField, Gets a form field from a key, this can be variable, name or id. + * @param name {string}, Identifier, can be variable, name or id + * @returns item {object} + */ + getField: function(name) { + var fields = this.get("fields"), + subformModel, + subForms, + i, + item = fields[name] || null; + for (i = 0; i < this.get("subForms").getSize(); i += 1) { + subForms = this.get("subForms").get(i); + subformModel = subForms.model.get("formModel"); + fields = subformModel.get("fields"); + if (fields && fields[name]) { + item = fields[name]; + } + } + return item; + }, + /** + * Validates if a subForm exists into of the mainForm + * @param id + * @returns {boolean} + */ + isSubForm: function (id) { + var i, + view, + response = false, + subForms = this.get("subForms"), + size = subForms.getSize(); + if (id) { + for (i = 0; i < size; i += 1) { + view = subForms.get(i); + if (view.model.get("id") === id) { + response = true; + break; + } + } + } + return response; + }, + /** + * Walks by the field dependency tree (recursive); + * @param {*} name + * @param {*} callbackName + * @chainable + */ + walkByDependencyTree: function(name, callbackName) { + var relations = this.get("dependencyRelations"), + dependents = relations[name]; + this.visited.push(name); + if(dependents && dependents.length) { + for (i = 0; i < dependents.length; i += 1) { + dependent = dependents[i]; + if (dependent.get("view") && dependent.get("view")[callbackName] + && typeof dependent.get("view")[callbackName] === 'function') { + dependent.get("view")[callbackName](); + } + } + } + }, + /** + * Shows the dependent field spinners + * @param {*} name field's name + * @chainable + */ + enableDependencySpinners: function(name) { + this.walkByDependencyTree(name, "switchControlBySpinner"); + return this; + }, + /** + * Hides the dependent field spinners + * @param {*} name field's name + * @chainable + */ + disableDependencySpinners: function(name) { + this.walkByDependencyTree(name, "switchSpinnerByControl"); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.FormPanel", FormPanel); +}()); + +(function () { + var FieldModel = Backbone.Model.extend({ + defaults: { + colSpan: 12, + id: PMDynaform.core.Utils.generateID(), + label: "Untitled", + name: PMDynaform.core.Utils.generateName(), + value: "", + nameGridColum: null, + text: "", + data: null, + _hidden: false, + /** + * @param {object}: dataForDependent, Stores data to eject dependent field service + */ + dataForDependent: {}, + /** + * toDraw: When this property change, the view is redrawn + * @member {boolean} + */ + toDraw: false, + /** + * @param {object}: stores the request ajax instance + */ + xhr: null, + /** + * @param {boolean}: stores the field loading status. + */ + tabIndex: "", + ariaLabel: "", + isSync: false + }, + eventsMobile: { + EXECUTE_QUERY: "dependentField/executeQuery", + SYNC_EXECUTE_QUERY: "dependentField/syncExecuteQuery" + }, + initialize: function (options) { + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + }, + + /** + * Generate default data object + * @param defaultValue + * @param value + * @param data + * @returns {{label: string, value: string}|*} + */ + initData: function (defaultValue, value, data) { + var auxData, + auxValue = "0", + auxLabel = "false", + options = this.get("options"), + i; + + if (typeof data === "object") { + if (data.hasOwnProperty("value") && data["value"] !== "") { + if (this.get("optionsToFalse").indexOf(data["value"]) > -1) { + auxValue = "0"; + } else { + if (this.get("optionsToTrue").indexOf(data["value"]) > -1) { + auxValue = "1"; + } + } + } else { + if (typeof defaultValue === "boolean") { + if (this.get("optionsToFalse").indexOf(defaultValue) > -1) { + auxValue = "0"; + } else { + if (this.get("optionsToTrue").indexOf(defaultValue) > -1) { + auxValue = "1"; + } + } + } + } + } + for (i = 0; i < options.length; i += 1) { + if (options[i].value === auxValue) { + auxLabel = options[i].label; + break; + } + } + auxData = { + label: auxLabel, + value: auxValue + }; + return auxData; + }, + defineModelEvents: function () { + this.on("change:text", this.onChangeText, this); + this.on("change:options", this.onChangeOptions, this); + this.on("change:data", this.onChangeData, this); + return this; + }, + /** + * onChangeData: This event is executed by modifying the data property + * @chainable + */ + onChangeData: function () { + this.setDataToSuggest(); + this.executeDependentsEvents(); + }, + /** + * onChangeData: Executes the dependency event if it is registered in the + * "PMDynaform.util.DependentsFieldManager" in the form + * @chainable + */ + executeDependentsEvents: function () { + var form = this.get("form"), + name = this.evaluateName(), + data = this.get("data"); + if (form) { + // creates visited to register all nodes that was walked + form.visited = []; + // here enables the dependency spinner for all dependent fields + this.enableDependencySpinners(); + // register the dependency events + form.dispachEvents("dependency:" + this.getNameToRegisterEvent(name), name, data); + } + return this; + }, + /** + * setDataToSuggest: PMDynaform.model.Suggest type fields are not executed in form-dependent + * field events, but the dataForDependent property must be updated to be used in suggest + * @chainable + */ + setDataToSuggest: function () { + var form = this.get("form"), + dependent, + dependentsRelation, + dependents, + i, + data = {}, + name = this.evaluateName(); + if (this.get("group") === "grid") { + name = name + ":" + this.attributes.keyEvent; + } + if (form) { + dependentsRelation = this.get("form").get("dependencyRelations") || {}; + if (dependentsRelation.hasOwnProperty(name)) { + dependents = dependentsRelation[name]; + for (i = 0; i < dependents.length; i += 1) { + dependent = dependents[i]; + if (dependent.get("type") === "suggest") { + data[this.evaluateName()] = this.get("data")["value"] || ""; + dependent.set("dataForDependent", data); + dependent.set("value", ""); + dependent.get("view").$el.find(".select2-selection__rendered").text(""); + $(dependent.get('view').getIdSelect()).empty(); + } + } + } + } + return this; + }, + /** + * evaluateName: Evaluates the valid name either a cell or a regular field + * @chainable + */ + evaluateName: function () { + var parent = this.get("group"), + name = ""; + if (parent === "form") { + name = this.get("variable") || this.get("id"); + } else if (parent === "grid") { + name = this.get("columnName") || this.get("columnId"); + } + return name; + }, + /** + * getNameToRegisterEvent: Creates an identifier to register in the event handler of form-dependent fields + * @param variable {string}: Is the base name to create a new key + * @returns {string}, the new key for registered event + */ + getNameToRegisterEvent: function (variable) { + var result = "", + row = this.get("row"), + parent = this.get("parent"); + if (parent.get("type") === "form") { + result = variable; + } else if (parent.get("type") === "grid") { + result = variable + ":" + this.get("keyEvent"); + } + return result; + }, + onChangeValue: function (attrs, item) { + var data; + data = this.findOption(item, "value"); + if (data) { + this.set("data", data); + } else { + this.set("data", { value: "", label: "" }); + } + this.set("text", this.get("data")["label"]); + return this; + }, + onChangeText: function (attrs, item) { + var data; + data = this.findOption(item, "label"); + if (data) { + this.set("data", data); + } else { + this.set("data", { value: "", label: "" }); + } + this.set("value", this.get("data")["value"]); + return this; + }, + getData: function () { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + }, + /** + * Get Control HTML default + * @returns {Array} + */ + getControl: function () { + return this.get("mode") !== "edit" ? undefined : []; + }, + parseLabel: function () { + var currentLabel = this.get("label"), + maxLength = this.get("maxLengthLabel"), + itemsLabel, + k, + parsed = false; + + itemsLabel = currentLabel.split(/\s/g); + for (k = 0; k < itemsLabel.length; k += 1) { + if (itemsLabel[k].length > maxLength) { + parsed = true; + } + } + if (parsed) { + this.set("tooltipLabel", currentLabel); + this.set("label", currentLabel.substr(0, maxLength - 4) + "..."); + } + return this; + }, + validate: function (attrs) { + this.set("value", this.get("value")); + this.set("label", this.get("label")); + return this; + }, + getEndpointVariable: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + } + } + } + + return endPointFixed; + }, + setLocalOptions: function () { + if (this.get("options")) { + this.set("localOptions", this.get("options")); + } + return this; + }, + setRemoteOptions: function () { + if (this.get("remoteOptions")) { + this.set("remoteOptions", this.get("optionsSql")); + } + return this; + }, + mergeOptionsSql: function () { + var options = []; + if (this.get("options") && this.get("optionsSql")) + options = this.get("localOptions").concat(this.get("optionsSql")); + this.set("options", options); + return this; + }, + /** + * This function add value from a field in a field formula + * @param formulator + * @returns {FieldModel} + */ + addFormulaTokenAssociated: function (formulator) { + if (formulator instanceof PMDynaform.core.Formula) { + formulator.addTokenValue(this.get("id"), this.get("value")); + } + return this; + }, + /** + * This function update the field with formula + * @param field + * @returns {FieldModel} + */ + updateFormulaValueAssociated: function (field) { + var resultField = field.model.get("formulator").evaluate(); + field.model.set("value", resultField); + return this; + }, + /** + * findOption(): This method find and return a option in the array options if exist + * @param value = the filter in the search "value", "label" or "defaultValue" + * @param criteria = is the criteria in the find the option should be a "value", "label" + * @returns {boolean||object} + */ + findOption: function (value, criteria) { + var i, + index = -1, + options, + option = null; + if (_.isArray(this.get("options"))) { + options = this.get("options").slice(0); + if (_.isArray(options) && value !== undefined && typeof criteria === "string") { + for (i = 0; i < options.length; i += 1) { + if (options[i] && (value == options[i][criteria])) { + option = _.extend({}, options[i]); + index = i; + break; + } + } + } + } + if (option !== null) { + option['index'] = index; + } + return option; + }, + /** + * findOptions(): This method find and return multiple options in the array options if exist the values + * @param values = the filter in the search "value" or "label" + * @param criteria = is the criteria in the find the option should be a "value" or "label" + * @returns {Array} + */ + findOptions: function (values, criteria) { + var options = this.get("options"), + filterOptions = []; + if (typeof values === "string") { + values = values.split('|'); + } + if (_.isArray(values) && _.isArray(options) && typeof criteria === "string") { + filterOptions = options.filter(function (item) { + index = _.find(values, function (num) { + return item[criteria] == num; + }); + if (index) { + return item; + } + }); + } + return filterOptions; + }, + /** + * returnOptionsData(): This build the data for the multiple options + * @param options: this options the field + * @returns {{value: Array, label: Array}} + */ + returnOptionsData: function (options) { + var i, + labels = [], + values = [], + options = options || this.get("options"); + if (_.isArray(options)) { + for (i = 0; i < options.length; i += 1) { + values.push(options[i]["value"]); + labels.push(options[i]["label"]); + } + } + return { + value: values, + label: labels + } + }, + /** + * Executes the dependency query + * using the data parameters + * @param {*} data necessary data for execute the query + * @returns {FieldModel} + */ + executeQuery: function (data) { + var project = this.get("project"), + that = this, + xhr; + if (PMDynaform.core.ProjectMobile) { + data.var_name = this.get("variable") || ""; + data.sql = this.get("sql") || ""; + project.requestManager.channelEvents( + { + handler: this.get("id"), + type: this.eventsMobile.EXECUTE_QUERY, + bridge: true, + data: data, + callback: function (response) { + if (response.error) { + that.afterExecuteQueryFail(response.error); + } else { + that.afterExecuteQuery(response); + } + } + }); + } else if (project) { + this._abortRequest(); + xhr = project.webServiceManager.executeQuery(data, this.get("variable") || "", this); + this.set({ xhr: xhr }); + } + return this; + }, + /** + * preparePostData, Prepares the additional data to execute the service to execute the query + * @returns data {object} + */ + preparePostData: function () { + var data = {}, + parent = this.get("parent"), + project = this.get("project"); + if (this.get("group") === "grid") { + data["field_id"] = this.get("columnName"); + } else { + data["field_id"] = this.get("id"); + } + if (project) { + data["dyn_uid"] = project.getDynUID() || ""; + } else { + data["dyn_uid"] = ""; + } + return data; + }, + /** + * isDependent, Verify if a field is dependent + * @returns dependent {boolean} + */ + isDependent: function () { + var dependent = false, + parentDependents = this.get("dependency"); + if (_.isArray(parentDependents) && parentDependents.length > 0) { + dependent = true; + } + return dependent; + }, + /** + * formatResponse, Valid query execution service response + * @param response {array}: a set of options + * @returns response {array} + */ + formatResponse: function (response) { + var k, + remoteOpt = []; + if (_.isArray(remoteOpt)) { + for (k = 0; k < response.length; k += 1) { + remoteOpt.push({ + value: response[k].value, + label: response[k].text || response[k].label || "" + }); + } + } + return remoteOpt; + }, + canExecuteQuery: function () { + var sql = this.get('sql'), + flag = false, + executeQueryMap = ["database", "datavariable"]; + if (sql && sql.length) { + flag = true; + } else { + //verify by datasource property + flag = executeQueryMap.indexOf(this.get('datasource').toLowerCase()) > -1 ? true : false; + } + return flag; + }, + getValue: function () { + var value = ""; + return value; + }, + /** + * Trigger a event bus an specific topic [onChange/target/source] + * @param topic + */ + triggerTopicEventBus: function (topic) { + var that = this, + deps = this.get("dependency"); + _.forEach(deps, function (dep) { + PMDynaform.EventBus.trigger(topic + "/" + dep + "/" + that.get("id"), ""); + }); + }, + + /** + * _dependentFieldEventRegister, if this component depends on another field, the dependence is recorded + * @param sql {string}, Is the query, of which is made the search of the + * variables on which this component depends + * @chainable + */ + _dependentFieldEventRegister: function (sql) { + var parse, + result, + variable = null, + form = this.get("form"), + parent = this.get("parent"), + hasMultipleDependents = false, + relationName; + this.set("dependency", []); + parse = /\@(?:([\@\%\#\=\!Qq])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*?)*)\))/g; + while ((result = parse.exec(sql)) !== null) { + if (_.isArray(result) && result.length) { + variable = result[0]; + variable = variable.substring(2, variable.length); + + relationName = parent.get("type") === "grid" ? variable + ":" + this.attributes.keyEvent : variable; + form.get("dependentsManager").registerNewDependencyRelation(relationName); + form.get("dependentsManager").registerNewDependent(relationName, this); + form.get("dependentsManager").registerDependency(this.get("id"), variable); + } + } + return this; + }, + /** + * Add event to the dependency manager + * updated de dependency model property + * @param {*} variable + * @chainable + */ + addEvent: function (variable) { + var form = this.get("form"), + prefix = "dependency:"; + if (_.indexOf(this.get("dependency"), variable) === -1) { + this.get("dependency").push(variable); + form.get("dependentsManager").addEvent(prefix + this.getNameToRegisterEvent(variable), this.dependentHandler, this); + } + return this; + }, + + /** + * Dependent field handler, this callback is instanced for all register event, + * and runs when the event logged in PMDynaform.util.DependentsFieldManager + * param info {object}, Is the field information on which this component depends + */ + dependentHandler: function (info) { + var data = this.buildDataForQuery(info); + this.executeQuery(data); + return this; + }, + /** + * getDependentsManager, Retrieves form-dependent field handler + * @returns {PMDynaform.util.DependentsFieldManager} + */ + getDependentsManager: function () { + var form; + form = this.get("form"); + if (form) { + return this.get("form").get("dependentsManager"); + } + return null; + }, + /* + * buildDataForQuery, Builds the data needed to execute the query correctly + * @param info {object}: the initial data of the fields on which this component depends + * @returns dataForDependent {object} + */ + buildDataForQuery: function (info) { + var dependency = this.get("dependency"), + i, + dataForDependent = this.get("dataForDependent"), + dependencyItem, + form = this.get("form"), + parent = this.get("parent"); + if (!_.isEmpty(info)) { + dataForDependent[info.target] = info.data.value; + } + if (_.isArray(dependency)) { + for (i = 0; i < dependency.length; i += 1) { + if (parent && parent.get("type") === "grid") { + dependencyItem = parent.findCellInRow(this.get("row"), dependency[i]); + } else { + dependencyItem = form.get("fields")[dependency[i]]; + } + if (dependencyItem) { + dataForDependent[dependency[i]] = dependencyItem.get("data").value; + } + } + } + _.extend(dataForDependent, this.preparePostData()); + return dataForDependent; + }, + /* + * Abstract method + */ + afterExecuteQuery: function (response) { + }, + /* + * Abstract method fires whe the service fails + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(); + form.visited = []; + if (this.get("view")) { + this.get("view").switchSpinnerByControl(); + } + if (response !== "abort") { + this.get("view").showQueryFailMessage(); + } + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + return this; + }, + /* + * Abstract method, + */ + onChangeOptions: function () { + }, + /* mergeRemoteOptions, merge the options obtained from the query to the + * service with the local options + * @chainable + */ + mergeRemoteOptions: function (remoteOptions) { + var k, + remoteOpt = [], + localOpt = this.get("localOptions") || [], + options; + for (k = 0; k < remoteOptions.length; k += 1) { + remoteOpt.push({ + value: remoteOptions[k].value, + label: remoteOptions[k].text || remoteOptions[k].label || "" + }); + } + this.set("optionsSql", remoteOpt); + options = localOpt.concat(remoteOpt); + this.set("options", options); + if (this.get("view") && this.get("view").firstLoad) { + this.trigger('change:options', this.model, options); + } + this.updateJsonOptions({ + optionsSql: remoteOpt + }); + return this; + }, + + /** + * Update json in Project Model + * @param json + */ + updateJsonOptions: function (json) { + var prj = this.get("project"); + if (prj && prj.updateModel) { + prj.updateModel(this.get("id"), json); + } + }, + /** + * Load the remote options by referring to the service + * Anonymous function + */ + loadRemotesOptions: function () { + var data; + data = this.buildDataForQuery({}); + dependentsManager = this.getDependentsManager(); + this.executeQuery(data); + return this; + }, + /** + * Retrieves the domain of the component based on + * the fields on which it depends + * @param data {object}: Data of the fields on which it depends + */ + recoveryRemoteOptions: function (data) { + var dependentsManager = this.getDependentsManager(), + response; + if (typeof data === "object" && _.isArray(this.get("options"))) { + _.extend(data, this.preparePostData()); + this.executeQuery(data); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (value) { + var data; + data = this.findOption(value, "value"); + if (!data) { + data = { + value: value, + label: value + } + } + this.set({ "data": data }, { silent: true }); + this.set({ "value": value }, { silent: true }); + this.set("toDraw", true); + return this; + }, + /** + * Return the name and name_label data + * @param value + * @returns {object} + */ + getAppData: function () { + var dt = this.get("data") || {}, + data = {}; + data[this.get("name")] = dt.value; + data[this.get("name") + "_label"] = dt.label; + return data; + }, + /** + * selectedOptions, Select an option from the option set + * @param criteria {string}, is the search criterion + * @param values {array}, set of the values + */ + selectedOptions: function (criteria, values) { + var options = this.get("options"), + i, + validCriteria = ["index", "value", "label"]; + if (_.isArray(options) && validCriteria.indexOf(criteria) > -1) { + for (i = 0; i < options.length; i += 1) { + if (criteria === "index" && values.indexOf(i) > -1) { + options[i].selected = true; + } else if (values.indexOf(options[i][criteria]) > -1) { + options[i].selected = true; + } else { + options[i].selected = false; + } + } + } + return this; + }, + /** + * Abort the current ajax request + * @returns {DropdownModel} + */ + _abortRequest: function () { + if (this.get("xhr")) { + this.get("xhr").abort(); + } + return this; + }, + /** + * Enable the dependent field spinner + * @chainable + */ + enableDependencySpinners: function () { + var name = this.evaluateName(), + form = this.get("form"); + form.visited = []; + form.enableDependencySpinners(this.getNameToRegisterEvent(name)); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Field", FieldModel); +}()); + +(function () { + var FieldModel = Backbone.Model.extend({ + defaults: { + colSpan: 12, + id: PMDynaform.core.Utils.generateID(), + label: "Untitled", + name: PMDynaform.core.Utils.generateName(), + value: "", + nameGridColum: null, + text: "", + data: null, + _hidden: false, + /** + * @param {object}: dataForDependent, Stores data to eject dependent field service + */ + dataForDependent: {}, + /** + * toDraw: When this property change, the view is redrawn + * @member {boolean} + */ + toDraw: false, + /** + * @param {object}: stores the request ajax instance + */ + xhr: null, + tabIndex: "", + ariaLabel: "", + isSync: false, + isDependent: false + }, + eventsMobile: { + EXECUTE_QUERY: "dependentField/executeQuery", + SYNC_EXECUTE_QUERY: "dependentField/syncExecuteQuery" + }, + initialize: function (options) { + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + }, + /** + * Generate default data object + * @param defaultValue + * @param value + * @param data + * @returns {{label: string, value: string}|*} + */ + initData: function (defaultValue, value, data) { + var auxData, + auxValue = "0", + auxLabel = "false", + options = this.get("options"), + i; + + if (typeof data === "object") { + if (data.hasOwnProperty("value") && data["value"] !== "") { + if (this.get("optionsToFalse").indexOf(data["value"]) > -1) { + auxValue = "0"; + } else { + if (this.get("optionsToTrue").indexOf(data["value"]) > -1) { + auxValue = "1"; + } + } + } else { + if (typeof defaultValue === "boolean") { + if (this.get("optionsToFalse").indexOf(defaultValue) > -1) { + auxValue = "0"; + } else { + if (this.get("optionsToTrue").indexOf(defaultValue) > -1) { + auxValue = "1"; + } + } + } + } + } + for (i = 0; i < options.length; i += 1) { + if (options[i].value === auxValue) { + auxLabel = options[i].label; + break; + } + } + auxData = { + label: auxLabel, + value: auxValue + }; + return auxData; + }, + /** + * Define events (Deprecated in the new classes) + */ + defineModelEvents: function () { + this.on("change:text", this.onChangeText, this); + this.on("change:options", this.onChangeOptions, this); + this.on("change:data", this.onChangeData, this); + return this; + }, + /** + * onChangeData: This event is executed by modifying the data property + * @chainable + */ + onChangeData: function () { + this.setDataToSuggest(); + this.executeDependentsEvents(); + }, + /** + * onChangeData: Executes the dependency event if it is registered in the + * "PMDynaform.util.DependentsFieldManager" in the form + * @chainable + */ + executeDependentsEvents: function () { + var form = this.get("form"), + name = this.evaluateName(), + data = this.get("data"); + if (form) { + // creates visited to register all nodes that was walked + form.visited = []; + // here enables the dependency spinner for all dependent fields + this.enableDependencySpinners(); + // register the dependency events + form.dispachEvents("dependency:" + this.getNameToRegisterEvent(name), name, data); + } + return this; + }, + /** + * setDataToSuggest: PMDynaform.model.Suggest type fields are not executed in form-dependent + * field events, but the dataForDependent property must be updated to be used in suggest + * @chainable + */ + setDataToSuggest: function () { + var form = this.get("form"), + dependent, + dependentsRelation, + dependents, + i, + data = {}, + name = this.evaluateName(); + if (this.get("group") === "grid") { + name = name + ":" + this.attributes.keyEvent; + } + if (form) { + dependentsRelation = this.get("form").get("dependencyRelations") || {}; + if (dependentsRelation.hasOwnProperty(name)) { + dependents = dependentsRelation[name]; + for (i = 0; i < dependents.length; i += 1) { + dependent = dependents[i]; + if (dependent.get("type") === "suggest") { + data[this.evaluateName()] = this.get("data")["value"] || ""; + dependent.set("dataForDependent", data); + dependent.set("value", ""); + dependent.get("view").$el.find(".select2-selection__rendered").text(""); + $(dependent.get('view').getIdSelect()).empty(); + } + } + } + } + return this; + }, + /** + * evaluateName: Evaluates the valid name either a cell or a regular field + * @chainable + */ + evaluateName: function () { + var parent = this.get("group"), + name = ""; + if (parent === "form") { + name = this.get("variable") || this.get("id"); + } else if (parent === "grid") { + name = this.get("columnName") || this.get("columnId"); + } + return name; + }, + /** + * getNameToRegisterEvent: Creates an identifier to register in the event handler of form-dependent fields + * @param variable {string}: Is the base name to create a new key + * @returns {string}, the new key for registered event + */ + getNameToRegisterEvent: function (variable) { + var result = "", + row = this.get("row"), + parent = this.get("parent"); + if (parent.get("type") === "form") { + result = variable; + } else if (parent.get("type") === "grid") { + result = variable + ":" + this.get("keyEvent"); + } + return result; + }, + /** + * Handler for change value (Deprecated in the new classes) + * @param {*} attrs + * @param {*} item + * @returns {FieldModel} + */ + onChangeValue: function (attrs, item) { + var data; + data = this.findOption(item, "value"); + if (data) { + this.set("data", data); + } else { + this.set("data", { value: "", label: "" }); + } + this.set("text", this.get("data")["label"]); + return this; + }, + /** + * Handler for change text property (Deprecated in the new classes) + * @param {*} attrs + * @param {*} item + * @returns {FieldModel} + */ + onChangeText: function (attrs, item) { + var data; + data = this.findOption(item, "label"); + if (data) { + this.set("data", data); + } else { + this.set("data", { value: "", label: "" }); + } + this.set("value", this.get("data")["value"]); + return this; + }, + /** + * Return data with value + * @returns {Object} + */ + getData: function () { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + }, + /** + * Get Control HTML default + * @returns {Array} + */ + getControl: function () { + return this.get("mode") !== "edit" ? undefined : []; + }, + /** + * Function base for others models + * @param {*} attrs + * @returns {FieldModel} + */ + validate: function (attrs) { + return this; + }, + /** + * Return the url endpoint + * @param {*} urlObj + * @returns {String} + */ + getEndpointVariable: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + } + } + } + + return endPointFixed; + }, + /** + * Set the localoptions (Array hardcode from designer) + * @returns {FieldModel} + */ + setLocalOptions: function () { + if (this.get("options")) { + this.set("localOptions", this.get("options")); + } + return this; + }, + /** + * Set the options from sql query + * @returns {FieldModel} + */ + setRemoteOptions: function () { + if (this.get("remoteOptions")) { + this.set("remoteOptions", this.get("optionsSql")); + } + return this; + }, + /** + * Merge local options with the sql options + * @returns {FieldModel} + */ + mergeOptionsSql: function () { + var options = []; + if (this.get("options") && this.get("optionsSql")) + options = this.get("localOptions").concat(this.get("optionsSql")); + this.set("options", options); + return this; + }, + /** + * This function add value from a field in a field formula + * @param formulator + * @returns {FieldModel} + */ + addFormulaTokenAssociated: function (formulator) { + if (formulator instanceof PMDynaform.core.Formula) { + formulator.addTokenValue(this.get("id"), this.get("data")["value"]); + } + return this; + }, + /** + * This function update the field with formula + * @param field + * @returns {FieldModel} + */ + updateFormulaValueAssociated: function (field) { + var resultField = field.model.get("formulator").evaluate(); + field.model.set("data", { + value: resultField, + label: resultField + }); + return this; + }, + /** + * findOption(): This method find and return a option in the array options if exist + * @param value = the filter in the search "value", "label" or "defaultValue" + * @param criteria = is the criteria in the find the option should be a "value", "label" + * @returns {boolean||object} + */ + findOption: function (value, criteria) { + var i, + index = -1, + options, + option = null; + if (_.isArray(this.get("options"))) { + options = this.get("options").slice(0); + if (_.isArray(options) && value !== undefined && typeof criteria === "string") { + for (i = 0; i < options.length; i += 1) { + if (options[i] && (value == options[i][criteria])) { + option = _.extend({}, options[i]); + index = i; + break; + } + } + } + } + if (option !== null) { + option['index'] = index; + } + return option; + }, + /** + * findOptions(): This method find and return multiple options in the array options if exist the values + * @param values = the filter in the search "value" or "label" + * @param criteria = is the criteria in the find the option should be a "value" or "label" + * @returns {Array} + */ + findOptions: function (values, criteria) { + var options = this.get("options"), + filterOptions = []; + if (typeof values === "string") { + values = values.split('|'); + } + if (_.isArray(values) && _.isArray(options) && typeof criteria === "string") { + filterOptions = options.filter(function (item) { + index = _.find(values, function (num) { + return item[criteria] == num; + }); + if (index) { + return item; + } + }); + } + return filterOptions; + }, + /** + * returnOptionsData(): This build the data for the multiple options + * @param options: this options the field + * @returns {{value: Array, label: Array}} + */ + returnOptionsData: function (options) { + var i, + labels = [], + values = [], + options = options || this.get("options"); + if (_.isArray(options)) { + for (i = 0; i < options.length; i += 1) { + values.push(options[i]["value"]); + labels.push(options[i]["label"]); + } + } + return { + value: values, + label: labels + } + }, + /** + * Executes the dependency query + * using the data parameters + * @param {*} data necessary data for execute the query + * @returns {FieldModel} + */ + executeQuery: function (data) { + var project = this.get("project"), + that = this, + xhr; + if (PMDynaform.core.ProjectMobile) { + data.var_name = this.get("variable") || ""; + data.sql = this.get("sql") || ""; + project.requestManager.channelEvents( + { + handler: this.get("id"), + type: this.eventsMobile.EXECUTE_QUERY, + bridge: true, + data: data, + callback: function (response) { + if (response.error) { + that.afterExecuteQueryFail(response.error); + } else { + that.afterExecuteQuery(response); + } + } + }); + } else if (project) { + this._abortRequest(); + xhr = project.webServiceManager.executeQuery(data, this.get("variable") || "", this); + this.set({ xhr: xhr }); + } + return this; + }, + /** + * preparePostData, Prepares the additional data to execute the service to execute the query + * @returns data {object} + */ + preparePostData: function () { + var data = {}, + parent = this.get("parent"), + project = this.get("project"); + if (this.get("group") === "grid") { + data["field_id"] = this.get("columnName"); + } else { + data["field_id"] = this.get("id"); + } + if (project) { + data["dyn_uid"] = project.getDynUID() || ""; + } else { + data["dyn_uid"] = ""; + } + return data; + }, + /** + * isDependent, Verify if a field is dependent + * @returns dependent {boolean} + */ + isDependent: function () { + var dependent = false, + parentDependents = this.get("dependency"); + if (_.isArray(parentDependents) && parentDependents.length > 0) { + dependent = true; + } + return dependent; + }, + /** + * Verify if the model contains sql property + * @returns {boolean} + */ + canExecuteQuery: function () { + var sql = this.get('sql'), + flag = false, + executeQueryMap = ["database", "datavariable"]; + if (sql && sql.length) { + flag = true; + } else { + //verify by datasource property + flag = executeQueryMap.indexOf(this.get('datasource').toLowerCase()) > -1 ? true : false; + } + return flag; + }, + /** + * Abstract method + * @returns {String} + */ + getValue: function () { + var value = ""; + return value; + }, + /** + * Trigger a event bus an specific topic [onChange/target/source] + * @param topic + */ + triggerTopicEventBus: function (topic) { + var that = this, + deps = this.get("dependency"); + _.forEach(deps, function (dep) { + PMDynaform.EventBus.trigger(topic + "/" + dep + "/" + that.get("id"), ""); + }); + }, + + /** + * _dependentFieldEventRegister, if this component depends on another field, the dependence is recorded + * @param sql {string}, Is the query, of which is made the search of the + * variables on which this component depends + * @chainable + */ + _dependentFieldEventRegister: function (sql) { + var parse, + result, + variable = null, + form = this.get("form"), + parent = this.get("parent"), + hasMultipleDependents = false, + relationName; + this.set("dependency", []); + parse = /\@(?:([\@\%\#\=\?\!Qq])([a-zA-Z\_]\w*)|([a-zA-Z\_][\w\-\>\:]*)\(((?:[^\\\\\)]*?)*)\))/g; + while ((result = parse.exec(sql)) !== null) { + if (_.isArray(result) && result.length) { + variable = result[0]; + variable = variable.substring(2, variable.length); + relationName = parent.get("type") === "grid" ? form.getField(variable) ? variable : variable + "-" + this.attributes.keyEvent : variable; + form.get("dependentsManager").registerNewDependencyRelation(relationName); + form.get("dependentsManager").registerNewDependent(relationName, this); + form.get("dependentsManager").registerDependency(parent.get("type") === "grid" ? this.get("id") + "-" + this.attributes.keyEvent : this.get("id"), relationName); + this.set("isDependent", true); + } + } + return this; + }, + /** + * Dependent field handler, this callback is instanced for all register event, + * and runs when the event logged in PMDynaform.util.DependentsFieldManager + * param info {object}, Is the field information on which this component depends + * @param {*} info + * @returns {FieldModel} + */ + dependentHandler: function (info) { + var data = this.buildDataForQuery(info); + this.executeQuery(data); + return this; + }, + /** + * getDependentsManager, Retrieves form-dependent field handler + * @returns {PMDynaform.util.DependentsFieldManager} + */ + getDependentsManager: function () { + var form; + form = this.get("form"); + if (form) { + return this.get("form").get("dependentsManager"); + } + return null; + }, + /* + * buildDataForQuery, Builds the data needed to execute the query correctly + * @param info {object}: the initial data of the fields on which this component depends + * @returns dataForDependent {object} + */ + buildDataForQuery: function (info) { + var dependency = this.get("dependency"), + i, + dataForDependent = this.get("dataForDependent"), + dependencyItem, + form = this.get("form"), + parent = this.get("parent"); + if (!_.isEmpty(info)) { + dataForDependent[info.target] = info.data.value; + } + if (_.isArray(dependency)) { + for (i = 0; i < dependency.length; i += 1) { + if (parent && parent.get("type") === "grid") { + dependencyItem = parent.findCellInRow(this.get("row"), dependency[i]); + } else { + dependencyItem = form.get("fields")[dependency[i]]; + } + if (dependencyItem) { + dataForDependent[dependency[i]] = dependencyItem.get("data").value; + } + } + } + _.extend(dataForDependent, this.preparePostData()); + return dataForDependent; + }, + /** + * Abstract Method + * @param {*} response + */ + afterExecuteQuery: function (response) { + }, + /* + * Method fires when the service fails + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(); + form.visited = []; + if (this.get("view")) { + this.get("view").switchSpinnerByControl(); + } + if (response !== "abort") { + this.get("view").showQueryFailMessage(); + } + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + return this; + }, + /* + * Abstract method, + */ + onChangeOptions: function () { + }, + /* mergeRemoteOptions, merge the options obtained from the query to the + * service with the local options + * @chainable + */ + mergeRemoteOptions: function (remoteOptions) { + var k, + remoteOpt = [], + localOpt = this.get("localOptions") || [], + options; + for (k = 0; k < remoteOptions.length; k += 1) { + remoteOpt.push({ + value: remoteOptions[k].value, + label: remoteOptions[k].text || remoteOptions[k].label || "" + }); + } + this.set("optionsSql", remoteOpt); + options = localOpt.concat(remoteOpt); + this.set("options", options); + if (this.get("view") && this.get("view").firstLoad) { + this.trigger('change:options', this.model, options); + } + this.updateJsonOptions({ + optionsSql: remoteOpt + }); + return this; + }, + /** + * Update json in Project Model + * @param json + */ + updateJsonOptions: function (json) { + var prj = this.get("project"); + if (prj && prj.updateModel) { + prj.updateModel(this.get("id"), json); + } + }, + /** + * Load the remote options by referring to the service + * Anonymous + * @returns {FieldModel} + */ + loadRemotesOptions: function () { + var data; + data = this.buildDataForQuery({}); + dependentsManager = this.getDependentsManager(); + this.executeQuery(data); + return this; + }, + /** + * Retrieves the domain of the component based on + * the fields on which it depends + * @param data {object}: Data of the fields on which it depends + */ + recoveryRemoteOptions: function (data) { + var dependentsManager = this.getDependentsManager(), + response; + if (typeof data === "object" && _.isArray(this.get("options"))) { + _.extend(data, this.preparePostData()); + this.executeQuery(data); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (value) { + var data; + data = this.findOption(value, "value"); + if (!data) { + data = { + value: value, + label: value + } + } + this.set({ "data": data }, { silent: true }); + this.set({ "value": value }, { silent: true }); + this.set("toDraw", true); + return this; + }, + /** + * Return the name and name_label data + * @param value + * @returns {object} + */ + getAppData: function () { + var dt = this.get("data") || {}, + data = {}; + data[this.get("name")] = dt.value; + data[this.get("name") + "_label"] = dt.label; + return data; + }, + /** + * selectedOptions, Select an option from the option set + * @param criteria {string}, is the search criterion + * @param values {array}, set of the values + * @returns {FieldModel} + */ + selectedOptions: function (criteria, values) { + var options = this.get("options"), + i, + validCriteria = ["index", "value", "label"]; + if (_.isArray(options) && validCriteria.indexOf(criteria) > -1) { + for (i = 0; i < options.length; i += 1) { + if (criteria === "index" && values.indexOf(i) > -1) { + options[i].selected = true; + } else if (values.indexOf(options[i][criteria]) > -1) { + options[i].selected = true; + } else { + options[i].selected = false; + } + } + } + return this; + }, + /** + * Abort the current ajax request + * @returns {FieldModel} + */ + _abortRequest: function () { + if (this.get("xhr")) { + this.get("xhr").abort(); + } + return this; + }, + /** + * Enable the dependent field spinner + * @chainable + */ + enableDependencySpinners: function () { + var name = this.evaluateName(), + form = this.get("form"); + form.visited = []; + form.enableDependencySpinners(this.getNameToRegisterEvent(name)); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @returns {FieldModel} + */ + dependencyWillUpdate: function (any) { + if (any.data) { + this.set({ + data: any.data + }, { silent: true }); + } + this.get("form").get("dependentsManager").createBidirectional(this, any.fn); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Subscribe the changes in dependencies + * @param {*} dt + * @param {*} serial + * @returns {FieldModel} + */ + executeDependency: function (dt, serial) { + var that = this, + data = _.extend(dt, this.preparePostData()), + callback = function (data, err) { + var rootField; + that.dependencyDidUpdate(data, dt, err); + that.get("form").get("dependentsManager").emit({ + channel: "dependencies", + event: that.getFieldId() + serial, + payload: "" + }); + // Hack to manage when we need update the grid columns model + rootField = that.get("form").get("rootField"); + if (rootField && rootField.get("group") !== "grid" && that.get("group") == "grid") { + //means there are form grid dependecy relations + that.get("parent").updateGridColumn(dt, { + optionsSql: that.get("optionsSql"), + data: that.get("data") + }); + } + }; + if (this.get("view")) { + this.get("view").switchControlBySpinner(); + } + if (PMDynaform.core.ProjectMobile) { + this.executeQueryMobile(data, callback); + } else { + this.executeQueryWeb(data, this.get("form").get("isSync") ? false : true, callback); + } + return this; + }, + /** + * Execute Query for Mobile + * @param {*} data + * @param {*} callback + * @returns {FieldModel} + */ + executeQueryMobile: function (data, callback) { + var project = this.get("project"), + that = this; + data.var_name = this.get("variable") || ""; + data.sql = this.get("sql") || ""; + project.requestManager.channelEvents({ + handler: this.get("id"), + type: this.eventsMobile.EXECUTE_QUERY, + bridge: true, + data: data, + callback: callback + }); + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Update only view of dropdown + * @param {*} data + * @param {*} err + */ + dependencyDidUpdate: function (data, dt, err) { + var that = this; + if (data) { + that.afterExecuteQuery(data); + } else { + that.afterExecuteQueryFail(err); + } + this.set("dependencyDidUpdate", { error: err || false }); + this.trigger('change:dependencyDidUpdate'); + }, + /** + * Will update the column model + * in order to create a new cell + * @param {Object} dt + */ + updateGridModels: function (dt) { + }, + /** + * Execute query for web + * @param {*} data + * @param {*} async + * @param {*} callback + * @returns {FieldModel} + */ + executeQueryWeb: function (data, async, callback) { + var project = this.get("project"), + xhr; + this._abortRequest(); + xhr = project.webServiceManager.execQuery(data, this.get("variable") || this.get("columnName") || "", async, this.get("memoryCache"), callback); + this.set({ xhr: xhr }); + return this; + }, + /** + * Return the id for triggers the dependencies + * @returns {String} + */ + getFieldId: function () { + var id, + parent = this.get("parent"); + id = parent.get("type") === "grid" ? (this.get("columnId") || this.get("id")) + "-" + this.get("keyEvent") : this.get("id"); + return id; + }, + /** + * Find text in options model + * @param {*} text + * @returns {Array} + */ + findTextInOptions: function (text) { + var options = this.get("options"); + return _.find(options, function (o) { + return o.label === text; + }); + }, + /** + * Find the val in options model + * @param {*} val + * @returns {Array} + */ + findValueInOptions: function (val) { + var options = this.get("options"); + return _.find(options, function (o) { + return o.value === val; + }); + }, + /** + * Execute the remote options for this field + * @param {*} fn + * @chainable + */ + getRemoteOptions: function (fn) { + var that = this, + data = this.get("form").get("dependentsManager").getDependenciesData(this); + if(this.get("sql")){ + data = _.extend(data, this.preparePostData()); + if (data) { + if (PMDynaform.core.ProjectMobile) { + this.executeQueryMobile(data, function (res, err) { + that.mergeRemoteOptions(res && _.isArray(res) ? res : []); + if (_.isFunction(fn)) { + fn(res, err); + } + }) + } else { + this.executeQueryWeb(data, false, function (res, err) { + that.mergeRemoteOptions(res && _.isArray(res) ? res : []); + if (_.isFunction(fn)) { + fn(res, err); + } + }); + } + } + } + return this; + }, + /** + * Clear the options and optionsSql property of a field (dropdown). + * @chainable + */ + clearOptions: function () { + this.set('options', []); + this.set('optionsSql', []); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.FieldR", FieldModel); +}()); + +(function () { + var GridModel = PMDynaform.model.Field.extend({ + defaults: { + title: "Grid".translate(), + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + columns: [], + data: [], + disabled: false, + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("grid"), + gridtable: [], + layoutOpt: [ + "responsive", + "static" + ], + layout: "responsive", + pager: true, + paginationRotate: false, + paginationItems: 1, + pageSize: 5, + mode: "edit", + rows: 1, + type: "grid", + functions: false, + totalrow: [], + functionOptions: { + "sum": "sumValues", + "avg": "avgValues" + }, + dataColumns: [], + gridFunctions: [], + titleHeader: [], + valid: true, + countHiddenControl: 0, + addRow: true, + deleteRow: true, + variable: "", + required: false, + emptyMessage: "No records".translate(), + addRowText: "New".translate(), + addAriaLabel: "Add a new row to grid".translate(), + removeAriaLabel: "Remove row".translate(), + hint: "", + columnFileDelete: {}, + /** + * @param {Object}: dataSchema, used to validate the data because empty string is valid. + */ + dataSchema: {} + }, + /** + * initialize the validator object in the grid + * @returns {GridModel} + */ + initValidators: function () { + this.set("validator", new PMDynaform.model.Validator({ + type: this.get("type"), + required: this.get("required"), + rowsNumber: this.get("rows"), + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + return this; + }, + /** + * verify if the grid is valid + * @returns {boolean} + */ + isValid: function () { + this.validate(); + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + /** + * execute the validation of the validator associated object + * and evaluate the grid validation + * @returns {GridModel} + */ + validate: function () { + this.get("validator").set("rowsNumber", this.get("rows")); + this.get("validator").verifyGrid(); + return this; + }, + initialize: function (options) { + var pagesize; + this.set("gridtable",[]); + options = options || {}; + this.set("totalrow", []); + if (options["addRow"] === undefined) { + this.set("addRow", true); + } + if (options["deleteRow"] === undefined) { + this.set("deleteRow", true); + } + if (jQuery.isNumeric(this.get("pageSize"))) { + pagesize = parseInt(this.get("pageSize"), 10); + if (pagesize < 1) { + pagesize = 1; + this.set("pager", false); + } + } else { + this.set("pager", false); + } + if (!PMDynaform.core.ProjectMobile) { + this.set("pageSize", pagesize); + } + this.set("label", this.get("label")); + this.on("change:label", this.onChangeLabel, this); + if (options.project) { + this.project = options.project; + } + if (this.get("variable").trim().length === 0) { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("variable"); + } + this.fixCoutFieldsHidden(); + this.setLayoutGrid(); + this.setPaginationItems(); + this.checkTotalRow(); + this.initValidators(); + }, + /** + * Changes undefined layout properties to static + * @param initial + * @param final + * @returns {GridModel} + */ + setLayoutGrid: function () { + if ($.inArray(this.get("layout"), this.get("layoutOpt")) < 0) { + this.set("layout", "static"); + } + + return this; + }, + setPaginationItems: function () { + var rows = this.get("rows"), + size = this.get("pageSize"), + rotate = this.get("paginationRotate"), + pagerItems; + + pagerItems = Math.ceil(rows / size) ? Math.ceil(rows / size) : 1; + + this.set("paginationRotate", rotate); + this.set("paginationItems", pagerItems); + + return this; + }, + checkTotalRow: function () { + var i; + + loop_total: + for (i = 0; i < this.attributes.columns.length; i += 1) { + if (this.attributes.columns[i].operation) { + if (this.attributes.functionOptions[this.attributes.columns[i].operation.toLowerCase()]) { + this.attributes.functions = true; + break loop_total; + } + + } + } + return this; + }, + applyFunction: function () { + var i; + + for (i = 0; i < this.attributes.columns.length; i += 1) { + if (this.attributes.columns[i].operation) { + if (this.attributes.functionOptions[this.attributes.columns[i].operation.toLowerCase()]) { + this.attributes.totalrow[i] = this[this.attributes.functionOptions[this.attributes.columns[i].operation.toLowerCase()]](i); + } + } + } + + return this; + }, + sumValues: function (colIndex) { + var i, + sum = 0, + grid = this.attributes.gridFunctions; + + for (i = 0; i < grid.length; i += 1) { + sum += grid[i][colIndex]; + } + + return sum; + }, + avgValues: function (colIndex) { + var i, + sum = 0, + grid = this.attributes.gridFunctions; + + for (i = 0; i < grid.length; i += 1) { + sum += grid[i][colIndex]; + } + + return Math.round((sum / grid.length) * 100) / 100; + }, + fixCoutFieldsHidden: function () { + var i, countHiddenControl = 0; + for (i = 0; i < this.get("columns").length; i += 1) { + if (this.get("columns")[i].type === "hidden") { + countHiddenControl += 1; + } + } + this.set("countHiddenControl", countHiddenControl); + return this; + }, + /** + * Get Array of the Values of each field + * @returns {{name: *, value: Array}} + */ + getData: function () { + var i, + j, + cell, + row, + dataGrid = [], + gridTable = this.attributes.view.gridtable, + max = gridTable.length, + dataRow, + data; + if (this.get("view")) { + for (i = 0; i < max; i += 1) { + dataRow = []; + row = gridTable[i]; + for (j = 0; j < row.length; j += 1) { + cell = row[j]; + dataRow.push(cell.getValue()); + } + dataGrid.push(dataRow); + } + } + data = { + name: this.get("name"), + value: dataGrid + }; + return data; + }, + /** + * Get array of the values or an value cell + * @param row + * @param col + * @returns {*} + */ + getValue: function (row, col) { + var valueGrid = "", + gridData = this.getData(), + values = ""; + if (row && col) { + if (this.isColumnInRange(col) && this.isRowInRange(row)) { + values = gridData ? gridData.value : values; + valueGrid = values[row - 1][col - 1]; + } + } else { + valueGrid = gridData ? gridData.value : valueGrid; + } + return valueGrid; + }, + /** + * Validate index col + * @param col + * @returns {boolean} + */ + isColumnInRange: function (col) { + var valid = false, + numCols = 0, + columns = this.get("columns"); + numCols = columns ? columns.length : numCols; + if (col >= 1 && col <= numCols) { + valid = true; + } + return valid; + }, + /** + * Validate index row + * @param row + * @returns {boolean} + */ + isRowInRange: function (row) { + var valid = false, + numRows = this.get("rows"); + if (row >= 1 && row <= numRows) { + valid = true; + } + return valid; + }, + /** + * add a columnId to array columnFileDelete to know the columns to delete multiple files and update the variable to delete files; return the number of index in the array + * @returns {number} + */ + getColumnFileDelete: function (columnId, nameRow) { + var prop, + indexCol = -1, + indexName = -1, + arrFiles = this.get("columnFileDelete"); + + if (!arrFiles.hasOwnProperty(columnId)) { + arrFiles[columnId] = []; + } + for (prop in arrFiles) { + if (arrFiles.hasOwnProperty(prop)) { + indexCol = indexCol + 1; + if (prop === columnId) { + break; + } + } + } + + indexName = arrFiles[columnId].indexOf(nameRow); + if (indexName === -1) { + if (_.isString(nameRow)) { + arrFiles[columnId].push(nameRow); + indexName = arrFiles[columnId].indexOf(nameRow); + } + } + + return { + col: indexCol, + row: indexName + }; + }, + /** + * Returns the array hiddens columns json before a number col + * @param col + * @returns {Array} + */ + getHiddensBeforeColumn: function (col) { + var arrCols = [], index, + columns = this.get("columns"); + if (_.isNumber(col)) { + for (index = 0; index < col; index += 1) { + if (columns[index].type === "hidden") { + arrCols.push(columns[index]); + } + } + } + return arrCols; + }, + /** + * detachRegisteredEvents, Disable Events Logged on the Dependent Field Handler + * @chainable + */ + detachRegisteredEvents: function(row) { + var i = 0, + form = this.get("form"), + cell, + name; + if (_.isArray(row) && row.length) { + row = row[0]; + for (i = 0; i < row.length; i += 1) { + cell = row[i]; + if (cell && form) { + name = cell.model.getNameToRegisterEvent(cell.model.get("columnName")); + form.detachRegisteredEvents(name, cell.model.get("columnName")); + } + } + } + return this; + }, + /** + * findCellInRow: Obtains a cell that belongs to a row + * @param rowIndex {number}: Row position + * @param cellId {string}: cell original id + * @returns {PMDynaform.model.Field} + */ + findCellInRow: function(rowIndex, cellId) { + var i, + row = this.get("gridtable")[rowIndex]; + if (_.isArray(row)) { + for (i = 0; i < row.length; i += 1) { + if (row[i].model.get("columnId") === cellId) { + return row[i].model; + } + } + } + return null; + }, + /** + * Update the grid model and columnModel property in order + * to create new rows + * @param {Object} dt + * @param {Object} options + * @returns {PMDynaform.model.Field} + */ + updateGridColumn: function (dt, options) { + this.updateColumnCollection(this.get("columns"), dt, options); + this.updateColumnCollection(this.get("view").columnsModel, dt, options); + return this; + }, + /** + * Update a column object into the collection + * @param {Array} collection + * @param {Object} dt + * @param {Object} options + * @returns {PMDynaform.model.Field} + */ + updateColumnCollection: function (collection, dt, options) { + var match = _.find(collection, function(item) { return item.id === dt.field_id }) + if (match) { + _.extend(match, options); + } + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.GridPanel", GridModel); +}()); + +(function () { + var ButtonModel = PMDynaform.model.Field.extend({ + defaults: { + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("button"), + label: "untitled label", + type: "button", + namespace: "pmdynaform", + disabled: false, + colSpan: 12, + tabIndex: "", + ariaLabel: "" + }, + getValue: function () { + var label = this.get("label"); + return label ? label : ""; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Button", ButtonModel); +}()); +(function () { + var DropdownModel = PMDynaform.model.FieldR.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dataType: "string", + defaultValue: "", + disabled: false, + executeInit: true, + group: "form", + hint: "", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("dropdown"), + label: "untitled label", + tabIndex: "", + ariaLabel: "", + localOptions: [], + mode: "edit", + options: [], + remoteOptions: [], + required: false, + type: "text", + valid: true, + validator: null, + variable: null, + var_uid: null, + var_name: null, + variableInfo: {}, + columnName: null, + originalType: null, + data: { + value: "", + label: "" + }, + optionsSql: [], + enableValidate: true, + placeholder: "", + /** + * this parameter verify if exist placeholder in the component + */ + therePlaceholder: false, + /** + * this property fix the custom placeholder options + */ + placeholderOption: null, + /** + * @param {object}: dependency, Fields on which it depends + */ + dependency: [], + /** + * @param {object}: dataForDependent, Stores data to eject dependent field service + */ + showDependentSpinners: true, + isSync: false, + dependencyDidUpdate: false, + memoryCache: false, + disablePlaceholder: false + }, + initValidators: function () { + this.set("validator", new PMDynaform.model.Validator({ + domain: true, + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + return this; + }, + initialize: function (options) { + var data; + this.initValidators(); + this.setLocalOptions(); + this.setRemoteOptions(); + this.mergeOptionsSql(); + //verify the exist a placeholder an set the therePlaceholder parameter + this.verifyExistPlaceholder(); + this.setDefaultValue(); + this.set("dataForDependent", {}); + data = this.get("data"); + if (data && data["value"] === "" && !this.get("therePlaceholder")) { + this.setFirstOptionInData(); + } + if (this.get("variable") && this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this._dependentFieldEventRegister(this.get("sql")); + //create a placeholder option if exist + if (this.get("therePlaceholder")) { + this.set("placeholderOption", this.createPlaceHolderOption()); + } + }, + /** + * Verify if exist placeholder, when exist set paremeter therePlacehodler = true + * @returns {DropdownModel} + */ + verifyExistPlaceholder: function () { + var placeholder = this.get("placeholder"), + therePlaceholder = false; + if (typeof placeholder === "string") { + if (placeholder.trim().length !== 0) { + therePlaceholder = true; + } + } + this.set("therePlaceholder", therePlaceholder); + return this; + }, + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + } + }, + setDefaultValue: function () { + var options = this.get("options"), + defaultValue = this.get("defaultValue"), + arrayDefaults = ["", null, undefined]; + + if (arrayDefaults.indexOf(defaultValue) > -1 && options.length > 0) { + this.set("value", options[0].value); + } + + return this; + }, + isValid: function () { + return this.get("valid"); + }, + validate: function () { + var valueFixed = this.get("data")["value"]; + this.attributes.value = valueFixed; + if (this.get("enableValidate")) { + this.get("validator").set("type", this.get("type")); + this.get("validator").set("required", this.get("required")); + this.get("validator").set("value", valueFixed); + this.get("validator").set("dataType", this.get("dataType")); + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + setLocalOptions: function () { + var item = {}; + if (this.get("options")) { + this.set("localOptions", this.get("options")); + } + return this; + }, + /** + * createPlaceHolderOption(), when the property 'therePlaceholder' is true + * then the placeholder option is created + * @returns {{}} + */ + createPlaceHolderOption: function () { + var option = {}; + option["label"] = this.get("placeholder"); + option["value"] = undefined; + return option; + }, + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * Set value method, this method only will works for gridMobile class. + * @param {*} value + * @param {*} callback + */ + setValue: function (value, callback) { + var that = this, + dataOption, + criteria = "value"; + if (value !== undefined && value !== null) { + this.getRemoteOptions(function (data, err) { + dataOption = that.findOption(value, criteria); + that.dependencyWillUpdate({ + data: dataOption, + fn: callback + }); + }); + } + return this; + }, + /** + * SetValue, get Remote options, update the view and model but not trigger the dependencies without execute onchange callbacks only works in mobile + * @param {*} value + * @param {*} fn + * @return {DropDownModel} + */ + setValueWithoutTriggerDependencies: function (value, fn) { + var that = this, + dataOption, + criteria = "value"; + if (value !== undefined && value !== null) { + this.getRemoteOptions(function (data, err) { + dataOption = that.findOption(value, criteria); + that.setFirstOptionInData(); + // If not exist the value in options, we need show the first option and we need update the hidden + if (dataOption) { + that.set("data", dataOption); + } + if (_.isFunction(fn)) { + fn(); + } + }); + } + return this; + }, + /** + * Set text method, this method only will works for gridMobile class. + * @param {*} txt + * @param {*} callback + */ + setText: function (txt, callback) { + var that = this, + dataOption, + criteria = "label"; + if (typeof txt !== undefined && txt !== null) { + this.getRemoteOptions(function (data, err) { + dataOption = that.findOption(txt, criteria); + that.dependencyWillUpdate({ + data: dataOption, + fn: callback + }); + }); + } + return this; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + */ + afterExecuteQuery: function (response) { + var currentValue = this.get("value"), + newValue; + if (_.isArray(response)) { + this.clearOptions(); + this.mergeRemoteOptions(response); + this.set('addRowValue', null); + this.setFirstOptionInData(); + this.set('disablePlaceholder',true); + } + newValue = this.get("value"); + if (_.isArray(response) && response.length > 0 && this.get("showDependentSpinners") && currentValue !== newValue) { + this.set("showDependentSpinners", true); + } + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(); + form.visited = []; + if (response !== "abort") { + this.get("view").showQueryFailMessage(); + this.get("view").switchSpinnerByControl(); + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + } + this.mergeRemoteOptions([]); + this.setFirstOptionInData(); + return this; + }, + /** + * setFirstOptionInData: Sets the first domain option if it exists + * if there are not domain a default empty data has been setted + */ + setFirstOptionInData: function () { + var options = this.get("options"), + defaultData, + index = 0, + val; + if (options.length) { + val = this.get('addRowValue') || (options[index] && options[index].value); + defaultData = _.find(options, function (item) { + return item.value === val; + }); + this.set("data", defaultData || { value: '', label: '' }); + } else { + this.set("data", { value: '', label: '' }); + this.set('toDraw', true); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var newData; + if (typeof data === "object") { + newData = data; + } else { + newData = this.findOption(data, "value"); + if (!newData) { + newData = { + value: "", + label: "" + } + } + } + this.set({ "data": newData }, { silent: true }); + this.set("toDraw", true); + return this; + }, + /** + * Execute the remote options for this field + * @param {*} fn + * @chainable + */ + getRemoteOptions: function (fn) { + var that = this, + data = this.get("form").get("dependentsManager").getDependenciesData(this); + data = _.extend(data, this.preparePostData()); + if (data) { + if (PMDynaform.core.ProjectMobile) { + this.executeQueryMobile(data, function (res, err) { + that.mergeRemoteOptions(res && _.isArray(res) ? res : []); + if (_.isFunction(fn)) { + fn(res, err); + } + }) + } else { + this.executeQueryWeb(data, false, function (res, err) { + that.mergeRemoteOptions(res && _.isArray(res) ? res : []); + if (_.isFunction(fn)) { + fn(res, err); + } + }); + } + } + return this; + }, + /** + * Will update the column model + * in order to create a new cell + * @param {Object} dt + */ + updateGridModels: function (dt) { + newOptions = { optionsSql: this.get("options") }; + this.get("parent").updateGridColumn(dt, newOptions); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.DropdownR", DropdownModel); +}()); + +(function () { + var RadioboxModel = PMDynaform.model.FieldR.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("radio"), + dataType: "string", + disabled: false, + defaultValue: "", + label: "untitled label", + tabIndex: "", + ariaLabel: "", + ariaLabelVisible: true, + localOptions: [], + group: "form", + hint: "", + options: [], + mode: "edit", + type: "radio", + readonly: false, + remoteOptions: [], + required: false, + validator: null, + valid: true, + variable: "", + var_uid: null, + var_name: null, + variableInfo: {}, + columnName: null, + originalType: null, + itemClicked: false, + optionsSql: [], + enableValidate: true, + data: { + value: "", + label: "" + }, + dependencyDidUpdate: false, + memoryCache: false + }, + /** + * Initialize Field Model + * @param {*} attrs + */ + initialize: function (attrs) { + var data = this.get("data"); + this.set("label", this.get("label")); + this.set("dataForDependent", {}); + this.set("validator", new PMDynaform.model.Validator({ + domain: true, + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + this.verifyControl(); + this.setLocalOptions(); + this.setRemoteOptions(); + this.mergeOptionsSql(); + this.initControl(); + + if (data && data["value"].toString()) { + this.set("data", data); + } else { + this.set("data", { value: "", label: "" }); + } + if (this.get("group") === "form") { + if (this.get("variable").trim().length === 0) { + this.attributes.name = this.get("id"); + } + } else { + this.attributes.name = this.get("id"); + } + this._dependentFieldEventRegister(this.get("sql")); + }, + /** + * Init the values in Field + */ + initControl: function () { + var opts = this.get("options"), + i, + newOpts = [], + itemsSelected = []; + + if (this.get("defaultValue")) { + this.set("data", { + value: this.get("defaultValue"), + label: this.get("data").label + }); + } + for (i = 0; i < opts.length; i += 1) { + if (opts[i].selected) { + itemsSelected.push(opts[i].value.toString()); + } + newOpts.push({ + label: opts[i].label, + value: opts[i].value, + selected: opts[i].selected ? true : false + }); + } + + this.set("options", newOpts); + this.set("selected", itemsSelected); + }, + /** + * Set the local options in model + * @returns {RadioboxModel} + */ + setLocalOptions: function () { + this.set("localOptions", this.get("options")); + return this; + }, + /** + * Verify the validation in model + * @returns {boolean} + */ + isValid: function () { + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + /** + * Verify the data in control + */ + verifyControl: function () { + var opts = this.get("options"), i; + for (i = 0; i < opts.length; i += 1) { + opts[i].value = opts[i].value.toString(); + } + this.set("data", { + value: this.get("data").value.toString(), + label: this.get("data").label + }); + }, + /** + * Validate the radio Model + * @param {*} attrs + * @returns {RadioboxModel} + */ + validate: function (attrs) { + if (this.get("enableValidate")) { + if (attrs) { + this.get("validator").set("type", attrs.type); + this.get("validator").set("value", attrs.data.value); + this.get("validator").set("valueDomain", attrs.data.value); + this.get("validator").set("required", attrs.required); + this.get("validator").set("dataType", attrs.dataType); + } + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + /** + * Set the selected option + * @param {*} itemUpdated + * @returns {RadioboxModel} + */ + setItemClicked: function (itemUpdated) { + var opts = this.get("options"), + selected = this.get("selected"), + i; + this.itemClicked = true; + if (opts) { + for (i = 0; i < opts.length; i += 1) { + if (opts[i].value.toString() === itemUpdated.value.toString()) { + this.set("value", itemUpdated.value.toString()); + } + } + } + return this; + }, + /** + * Returns the data model + * @returns {Object} + */ + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + } + }, + /** + * Listener for value property in Radio Model + * @param {*} attrs + * @param {*} value + * @returns {RadioboxModel} + */ + onChangeValue: function (attrs, value) { + var option; + this.attributes.value = attrs.attributes.value; + option = this.findOption(value, "value"); + if (option && typeof option === "object") { + if (!this.itemClicked) { + this.set("data", { + value: option.value, + label: option.label + }); + } + this.itemClicked = false; + this.get("validator").set({ + valueDomain: this.get("value"), + options: this.get("options") || [] + }); + this.get("validator").verifyValue(); + } else { + this.attributes.value = this.previous("value"); + } + return this; + }, + /** + * Returns the value model + * @returns {Object} + */ + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + * @returns {RadioboxModel} + */ + afterExecuteQuery: function (response) { + this.set("data", { value: "", label: "" }); + this.mergeRemoteOptions(response); + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(); + form.visited = []; + if (response !== "abort") { + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + } + this.mergeRemoteOptions([]); + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param value {object} valid data for this component + * @param dependencyData {object}, data to complete the component domain + * @returns {RadioboxModel} + */ + setAppData: function (value, dependencyData) { + var data; + if (dependencyData) { + this.recoveryRemoteOptions(dependencyData); + } + data = this.findOption(value, "value") || { value: "", label: "" }; + this.set({ "data": data }, { silent: true }); + this.set("toDraw", true); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.RadioR", RadioboxModel); +}()); + +(function () { + var SubmitModel = PMDynaform.model.Field.extend({ + defaults: { + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("submit"), + label: "untitled label", + type: "submit", + namespace: "pmdynaform", + disabled: false, + colSpan: 12, + tabIndex: "", + ariaLabel: "" + }, + getValue: function () { + var label = this.get("label"); + return label ? label : ""; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Submit", SubmitModel); +}()); +(function () { + var TextAreaModel = PMDynaform.model.FieldR.extend({ + defaults: { + type: "textarea", + placeholder: "", + label: "untitled label", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("textarea"), + colSpan: 12, + value: "", + defaultValue: "", + tabIndex: "", + ariaLabel: "", + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + maxLengthLabel: 15, + rows: 2, + group: "form", + dataType: "string", + hint: "", + disabled: false, + maxLength: null, + mode: "edit", + required: false, + validator: null, + valid: true, + columnName: null, + originalType: null, + data: null, + enableValidate: true, + variable: '', + memoryCache: false + }, + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("data").value + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("data").value + } + } + }, + initialize: function (attrs) { + var data, maxLength; + this.set("optionsSql", null); + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + this.set("dataForDependent", {}); + this.set("validator", new PMDynaform.model.Validator({ + "type": this.get("type"), + "required": this.get("required"), + "maxLength": this.get("maxLength"), + "requiredFieldErrorMessage": this.get("requiredFieldErrorMessage"), + "dataType": this.get("dataType") || "string", + "regExp": { + validate: this.get("validate"), + message: this.get("validateMessage") + } + })); + + data = this.get("data"); + if (data && data["value"] !== "") { + data = { + value: data["value"], + label: data["value"] + }; + this.set("data", data); + this.set("defaultValue", data["value"]); + } else { + this.set("data", { value: "", label: "" }); + } + this.initControl(); + + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this._dependentFieldEventRegister(this.get("sql")); + }, + initControl: function () { + if (this.get("defaultValue")) { + this.set("value", this.get("defaultValue")); + } + }, + isValid: function () { + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + validate: function (attrs) { + var valueFixed; + if (this.get("data") !== undefined) { + valueFixed = this.get("data")["value"]; + if (this.get("enableValidate")) { + this.get("validator").set("value", valueFixed); + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + } + return this; + }, + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * Set value Only works from gridMobile + * @param value + * @param callback + * @returns {DropdownModel} + */ + setValue: function (value, callback) { + if (value) { + this.dependencyWillUpdate({ + data: { + value: value, + label: value + }, + fn: callback + }); + } + return this; + }, + /** + * Set text Only works from gridMobile + * @param txt + * @param callback + * @returns {DropdownModel} + */ + setText: function (txt, callback) { + this.setValue(txt, callback); + return this; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + */ + afterExecuteQuery: function (response) { + var currentValue = this.get("value"), + newValue; + this.clearOptions(); + this.mergeRemoteOptions(response); + this.setFirstOptionInData(); + newValue = this.get("value"); + if (_.isArray(response) && response.length > 1 && this.get("showDependentSpinners") && currentValue !== newValue) { + this.enableDependencySpinners(); + } + return this; + }, + /** + * setFirstOptionInData: Sets the first domain option if it exists + * if there are not domain a default empty data has been setted + */ + setFirstOptionInData: function() { + var indexValue = 0, + val, + responseDefault = [{ + value: "", + text: "" + }], + options = this.get("options") || []; + _.defaults(options, responseDefault); + if (_.isArray(options)) { + val = options[indexValue].value; + this.set("data", { + value: val, + label: val + }); + } + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(), + data = { + value: "", + label: "" + }; + form.visited = []; + if (response !== "abort") { + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + } + this.set("data", data); + return this; + }, + /** + * Superclass override method + */ + recoveryRemoteOptions: function (data, postRender) { + if (postRender) { + if (typeof data === "object") { + _.extend(data, this.preparePostData()); + this.executeQuery(data); + } + } + return this; + }, + /** + * Will update the column model + * in order to create a new cell + * @param {Object} dt + */ + updateGridModels: function(dt) { + newOptions = {data: this.get("data")}; + this.get("parent").updateGridColumn(dt, newOptions); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.TextAreaR", TextAreaModel); +}()); + +(function () { + + var TextModel = PMDynaform.model.FieldR.extend({ + defaults: { + type: "text", + placeholder: "", + label: "untitled label", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("text"), + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + maxLengthLabel: 15, + namespace: "pmdynaform", + operation: null, + tooltipLabel: "", + tabIndex: "", + ariaLabel: "", + group: "form", + defaultValue: "", + dataType: "string", + hint: "", + mask: "", + disabled: false, + maxLength: null, + mode: "edit", + autoComplete: "off", + required: false, + formulator: null, + validator: null, + textTransform: "", + valid: true, + variable: '', + var_uid: null, + var_name: null, + columnName: null, + originalType: null, + data: null, + keyValue: null, + formulaAssociatedObject: [], + enableValidate: true, + formula: '', + memoryCache: false + }, + initialize: function (attrs) { + var data, maxLength; + this.set("optionsSql", null); + this.set("dataType", this.get("dataType").trim().length ? this.get("dataType") : "string"); + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + this.set("validator", new PMDynaform.model.Validator({ + "type": this.get("type"), + "required": this.get("required"), + "requiredFieldErrorMessage": this.get("requiredFieldErrorMessage"), + "maxLength": this.get("maxLength"), + "dataType": this.get("dataType") || "string", + "regExp": { + validate: this.get("validate"), + message: this.get("validateMessage") + } + })); + + if (this.get("formula").trim().length) { + this.attributes.formula = this.get("formula").replace(/\s/g, ''); + } + if (this.attributes._extended && this.attributes._extended.formula) { + this.attributes._extended.formula = this.attributes._extended.formula.replace(/\s/g, ''); + } + + data = this.get("data"); + if (data && data["value"] !== "") { + if (data["label"] !== "") { + data = { + value: data["value"], + label: data["label"] + }; + } else { + data = { + value: data["value"], + label: data["value"] + }; + } + this.set("data", data); + this.set("defaultValue", data["value"]); + } else { + this.set("data", { value: "", label: "" }); + } + this.initControl(); + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this._dependentFieldEventRegister(this.get("sql")); + }, + initControl: function () { + if (typeof this.get("formula") === "string" && + this.get('formula') !== "undefined" && + this.get('formula') !== "null" && + this.get('formula').length > 1) { + this.set("formulator", new PMDynaform.core.Formula(this.get("formula"))); + this.set("disabled", true); + } + }, + addFormulaTokenAssociated: function (formulator) { + if (formulator instanceof PMDynaform.core.Formula) { + formulator.addTokenValue(this.get("id"), this.get("data")["value"]); + } + return this; + }, + addFormulaFieldName: function (otherField) { + this.get("formulator").addField("field", otherField); + return this; + }, + // Update the field with formula property + updateFormulaValueAssociated: function (field) { + var resultField = field.model.get("formulator").evaluate(); + field.setValue(resultField); + return this; + }, + isValid: function () { + return this.get("valid"); + }, + validate: function (attrs) { + var valueFixed; + if (this.get("data") !== undefined) { + valueFixed = this.get("data")['value']; + if (this.get("enableValidate")) { + this.get("validator").set("value", valueFixed); + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + } + return this; + }, + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("data").value + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("data").value + } + } + }, + getData2: function () { + var data = {}, name, value; + name = this.get("variable") ? this.get("variable").var_name : this.get("name"); + value = this.get("data").value; + data[name] = value; + return data; + }, + /** + * Set value Only works from gridMobile + * @param value + * @param callback + * @returns {TextModel} + */ + setValue: function (value, callback) { + if (value) { + this.dependencyWillUpdate({ + data: { + value: value, + label: value + }, + fn: callback + }); + } + return this; + }, + /** + * Set text Only works from gridMobile + * @param txt + * @param callback + * @returns {TextModel} + */ + setText: function (txt, callback) { + this.setValue(txt, callback); + return this; + }, + /** + * Returns the value from model + * @returns {TextModel} + */ + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + */ + afterExecuteQuery: function (response) { + var currentValue = this.get("value"), + newValue; + this.clearOptions(); + this.mergeRemoteOptions(response); + this.setFirstOptionInData(); + newValue = this.get("value"); + if (_.isArray(response) && response.length > 1 && this.get("showDependentSpinners") && currentValue !== newValue) { + this.enableDependencySpinners(); + } + return this; + }, + /** + * setFirstOptionInData: Sets the first domain option if it exists + * if there are not domain a default empty data has been setted + */ + setFirstOptionInData: function() { + var indexValue = 0, + val, + responseDefault = [{ + value: "", + text: "" + }], + options = this.get("options") || []; + _.defaults(options, responseDefault); + if (_.isArray(options)) { + val = options[indexValue].value; + this.set("data", { + value: val, + label: val + }); + } + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(), + data = { + value: "", + label: "" + }; + form.visited = []; + if (response !== "abort") { + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + } + this.set("data", data); + return this; + }, + /** + * Will update the column model + * in order to create a new cell + * @param {Object} dt + */ + updateGridModels: function(dt) { + newOptions = {data: this.get("data")}; + this.get("parent").updateGridColumn(dt, newOptions); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.TextR", TextModel); +}()); + +(function () { + var File = PMDynaform.model.Field.extend({ + defaults: { + autoUpload: false, + camera: true, + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + defaultValue: "", + disabled: false, + dnd: false, + dndMessage: "Drag or choose local files", + extensions: "pdf, png, jpg, mp3, doc, txt", + group: "form", + height: "200px", + hint: "", + id: PMDynaform.core.Utils.generateID(), + items: [], + label: "Untitled label", + tabIndex: "", + ariaLabel: "", + labelButton: "Choose Files", + mode: "edit", + multiple: false, + name: PMDynaform.core.Utils.generateName("file"), + variable: null, + inputDocuments: null, + preview: false, + required: false, + size: 1, //1 MB + type: "file", + proxy: [], + valid: true, + validator: null, + value: "", + columnName: null, + originalType: null, + data: { + value: [], + label: [] + }, + appDocUID: [], + enableValidate: true, + sizeUnity: "", + stackLabels: [], + cleaned: false + }, + initialize: function (properties) { + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + this.set("items", []); + this.set("proxy", []); + this.set("validator", new PMDynaform.model.Validator({ + "type": "file", + "required": this.get("required"), + "requiredFieldErrorMessage": this.get("requiredFieldErrorMessage") + })); + this.formatData(properties.data); + this.setSizeAndUnity(properties.size, properties.sizeUnity); + this.clearStackLabels(); + return this; + }, + /** + * Format Data File + * @param data + * @returns {File} + */ + formatData: function (data) { + var defaultValue = [], + defaultLabel = [], + valueAux, + labelAux; + if (data && _.isObject(data) && data.value && data.label) { + labelAux = this.parseToArray(data.label); + valueAux = this.parseToArray(data.value); + if (_.isArray(labelAux) && _.isArray(valueAux)) { + defaultLabel = labelAux; + defaultValue = valueAux; + } + this.setAppDocUID(data.app_doc_uid ? data.app_doc_uid : null); + } + this.set("data", { + value: defaultValue, + label: defaultLabel + }); + this.set("value", defaultValue); + return this; + }, + /** + * Apply JSON PARSE + * @param data + * @returns {*} + */ + parseToArray: function (data) { + var arrData = data; + if (data && _.isString(data)) { + arrData = JSON.parse(data); + } + return arrData; + }, + /** + * Validate File + * @returns {boolean} + */ + isValid: function () { + var valid = false; + this.get("validator").set("value", this.get("value").toString()); + this.get("validator").verifyValue(); + if (this.get("validator").get("valid")) { + valid = true; + } + return valid; + }, + /** + * Gets appDocUID to file field + */ + getAppDocUID: function () { + return this.get("appDocUID") || null; + }, + /** + * Set AppDocUid + * @param appDocUid + * @returns {File} + */ + setAppDocUID: function (appDocUid) { + if (_.isArray(appDocUid) && appDocUid.length) { + this.set("appDocUID", appDocUid); + } + return this; + }, + /** + * Set Size and SizeUnity + * @param size + * @param unity + * @returns {File} + */ + setSizeAndUnity: function (size, unity) { + var defaultSize = parseInt(size) || 999999, + defaultUnity = parseInt(size) ? unity : "MB"; + this.set("size", defaultSize); + this.set("sizeUnity", defaultUnity); + return this; + }, + /** + * Get name file (text). + * @returns {Array} + */ + getText: function () { + var data = this.get("data"), + label = []; + if (_.isArray(data.label) && data.label.length) { + label = data.label; + } else if (this.getCurrentNameFile()) { + label = [this.getCurrentNameFile()]; + } + return label; + }, + /** + * Get Doc UID (value). + * @returns {Array} + */ + getValue: function () { + return this.getAppDocUID() || []; + }, + /** + * Add Label File To stackLabels + * @param label + * @returns {File} + */ + addLabelToStack: function (label) { + var auxiliarStack = this.get("stackLabels"); + if (typeof label === "string") { + auxiliarStack.unshift(label); + } + this.set("stackLabels", auxiliarStack); + return this; + }, + /** + * Clear stackLabels + * @returns {File} + */ + clearStackLabels: function () { + this.set("stackLabels", []); + return this; + }, + /** + * Clear Content File Data + * @returns {File} + */ + clearContent: function () { + var data = this.get("data"); + if (data && !_.isEmpty(data) && data.value && data.label) { + this.set("cleaned", true); + this.set("data", { + value: [], + label: [], + app_doc_uid: [] + }); + this.set("value", []); + this.set("appDocUID", []); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param value {array} valid data for this component + */ + setAppData: function (value) { + this.set("value", value); + return this; + }, + /** Return the previous name of last file + * @returns {string} + */ + getPreviousNameFile: function () { + var auxiliarStack = this.get("stackLabels"), + index = 1; + return (auxiliarStack && auxiliarStack.length > 1) ? auxiliarStack[index] : ""; + }, + /** + * Return the name of the current file + * @returns {string} + */ + getCurrentNameFile: function () { + var auxiliarStack = this.get("stackLabels"), + index = 0; + return (auxiliarStack && auxiliarStack.length > 0) ? auxiliarStack[index] : ""; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.File", File); +}()); + +(function () { + var CheckGroupModel = PMDynaform.model.FieldR.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dataType: "string", + disabled: false, + group: "form", + hint: "", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("checkgroup"), + label: "untitled label", + tabIndex: "", + ariaLabel: "", + ariaLabelVisible: true, + localOptions: [], + maxLengthLabel: 15, + mode: "edit", + options: [], + readonly: false, + required: false, + optionsSql: [], + selected: [], + type: "checkgroup", + validator: null, + valid: true, + columnName: null, + originalType: null, + data: { + value: [], + label: "" + }, + defaultValue: [], + variable: "", + enableValidate: true, + dependencyDidUpdate: false, + memoryCache: false + }, + initialize: function (attrs) { + var data; + this.set("validator", new PMDynaform.model.Validator({ + type: this.get("type"), + required: this.get("required"), + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + this.set("dataForDependent", {}); + if (this.get("optionsSql") || this.get("options")) { + this.set("localOptions", this.get("options")); + this.mergeRemoteOptions(this.get("optionsSql")); + } + if (this.get("data") || this.get("data")["value"] || this.get("data")["defaultValue"]) { + this.set("data", this.initData(this.get("defaultValue"), this.get("value"), this.get("data"), this.get("variable"))); + this.attributes.value = this.get("data")["value"]; + } + this.initControl(); + this.get("validator").set("value", this.get("data").value); + + if (this.get("variable") === "") { + this.attributes.name = ""; + } + this._dependentFieldEventRegister(this.get("sql")); + return this; + }, + initData: function (defaultV, value, data) { + var auxData = {}, existData = false; + if (data) { + if (typeof data === "object") { + if (data.hasOwnProperty("value") && $.isArray(data["value"])) { + if (data.hasOwnProperty("label") && data["label"].toString().trim() === "") { + auxData["value"] = data["value"]; + auxData["label"] = []; + for (var i = 0; i < this.get("options").length; i += 1) { + if (data["value"].indexOf(this.get("options")[i]["value"]) > -1) { + auxData["label"].push(this.get("options")[i]["label"]); + } + } + } else { + if ($.isArray(data["label"])) { + data["label"] = JSON.stringify(data["label"]); + auxData = data; + } else { + if (data["label"].indexOf("[") === 0 && data["label"].lastIndexOf("]") === data["label"].length - 1) { + auxData = data; + } + } + } + existData = true; + } else { + if (typeof data["value"] === "string" && data["value"].length) { + data["value"] = data["value"].split(/,/g); + if (data["label"].indexOf("[") === 0 && data["label"].lastIndexOf("]") === data["label"].length - 1) { + this.attributes.labelsSelected = JSON.parse(data["label"]); + data["label"] = JSON.stringify(this.attributes.labelsSelected); + } + auxData = data; + } + if (!data.hasOwnProperty("value") || data["value"] === "") { + auxData["value"] = []; + auxData["label"] = []; + } + existData = true; + } + } else { + auxData["value"] = []; + auxData["label"] = []; + } + } else { + auxData["value"] = []; + auxData["label"] = []; + } + if (defaultV && !existData) { + var defaultV = defaultV.split("|"); + for (var i = 0; i < this.get("options").length; i += 1) { + if (defaultV.indexOf(this.get("options")[i]["value"]) > -1) { + auxData["value"].push(this.get("options")[i]["value"]); + auxData["label"].push(this.get("options")[i]["label"]); + } + } + } + if ($.isArray(auxData["label"])) { + auxData["label"] = JSON.stringify(auxData["label"]); + } + return auxData; + }, + initControl: function () { + var opts = this.get("options"), + i, + newOpts = [], + itemsSelected = []; + + for (i = 0; i < opts.length; i += 1) { + if (this.get("data") && this.get("data").value) { + if (this.get("data").value.indexOf(opts[i].value) > -1) { + opts[i].selected = true; + itemsSelected.push(opts[i]); + } + } + newOpts.push({ + label: opts[i].label, + value: opts[i].value, + selected: opts[i].selected ? true : false + }); + } + this.set("options", newOpts); + this.set("selected", itemsSelected); + }, + setLocalOptions: function () { + this.set("localOptions", this.get("options")); + return this; + }, + getData: function () { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + }; + }, + validate: function (attrs) { + if (this.get("enableValidate")) { + this.get("validator").set("value", attrs.value.length); + if (this.get("options").length) { + this.get("validator").set("options", this.attributes.options); + } + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + isValid: function () { + return this.get("valid"); + }, + setItemChecked: function (itemUpdated) { + var opts = this.get("options"), + selected = [], + i; + if (opts) { + for (i = 0; i < opts.length; i += 1) { + if (opts[i].value.toString() === itemUpdated.value.toString()) { + opts[i].selected = itemUpdated.checked; + } + } + this.set("options", opts); + for (i = 0; i < opts.length; i += 1) { + if (i === opts.length - 1 && selected.length) { + opts[i].selected = false; + } + if (opts[i].selected) { + selected.push(opts[i].value); + } + } + if (selected.length) { + this.attributes.value = selected; + } else { + this.attributes.value = []; + } + this.set("selected", selected); + } + return this; + }, + setItemsChecked: function (items) { + for (var index = 0; index < items.length; index++) { + this.setItemChecked({ + value: items[index], + checked: true + }); + } + return this; + }, + updateItemSelected: function () { + var i, + selected = this.get("selected"), auxValue, opts = this.get("options"); + if ($.isArray(this.get("value"))) { + this.set("selected", []); + selected = this.get("selected"); + for (i = 0; i < opts.length; i += 1) { + opts[i].selected = false; + } + this.set("options", opts); + auxValue = this.get("value"); + for (i = 0; i < auxValue.length; i += 1) { + this.setItemChecked({ + value: auxValue[i], + checked: true + }); + } + } else { + this.setItemChecked({ + value: this.attributes.value, + checked: true + }); + } + for (i = 0; i < selected.length; i += 1) { + this.setItemChecked({ + value: selected[i].trim ? selected[i].trim() : selected[i], + checked: true + }); + } + if (!this.attributes.disabled) { + this.get("validator").set({ + valueDomain: this.get("value"), + options: this.get("options") + }); + this.get("validator").set("value", this.get("selected").length); + this.get("validator").verifyValue(); + } + if (this.attributes.data) { + this.attributes.data["value"] = this.get("value"); + } + return this; + }, + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + */ + afterExecuteQuery: function (response) { + this.mergeRemoteOptions(response); + if (this.get("view")) { + this.get("view").switchSpinnerByControl(); + } + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(); + form.visited = []; + if (response !== "abort") { + this.get("view").showQueryFailMessage(); + this.get("view").switchSpinnerByControl(); + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + } + this.mergeRemoteOptions([]); + return this; + }, + + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + * @param dependencyData {object}, data to complete the component domain + * Is used in the method PMDynaform.model.CheckGroup.recoreryRemoteOptions + */ + setAppData: function (values, dependencyData) { + var data = { + value: [], + label: [] + }, + i, + options; + this.recoveryRemoteOptions(dependencyData); + options = this.findOptions(values, "value"); + if (_.isArray(options)) { + for (i = 0; i < options.length; i += 1) { + data.value.push(options[i].value); + data.label.push(options[i].label); + } + } + data.label = JSON.stringify(data.label); + this.set({ "data": data }, { silent: true }); + this.set({ "value": data.value }, { silent: true }); + this.set("toDraw", true); + return this; + }, + /** + * Trigger the dependencies for this Field + * @param {*} fn + * @returns {CheckGroupModel} + */ + triggerDependencies: function (fn) { + this.get("form").get("dependentsManager").createBidirectional(this, fn); + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.CheckGroupR", CheckGroupModel); +}()); + +(function () { + var CheckBoxModel = PMDynaform.model.Field.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dataType: "boolean", + disabled: false, + group: "form", + hint: "", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("checkgroup"), + label: "untitled label", + tabIndex: "", + ariaLabel: "", + ariaLabelVisible: true, + localOptions: [], + mode: "edit", + options: [], + required: false, + type: "checkbox", + validator: null, + valid: true, + value: null, + columnName: null, + originalType: null, + data: {}, + defaultValue: null, + labelsSelected: null, + optionsToTrue: [true, 1, "true", "1"], + optionsToFalse: [false, 0, "false", "0"], + variable: "", + enableValidate: true, + /** + * @member toDraw {boolean}: toDraw: When this property change, the view is redrawn + */ + toDraw: false + }, + /** + * This initialize data + * @param defData: json with valid options value and label + * @returns {CheckBoxModel} + */ + initialize: function (attrs) { + var data; + this.on("change:data", this.updateValue, this); + this.on("change:value", this.updateItemSelected, this); + this.set("validator", new PMDynaform.model.Validator({ + type: this.get("type"), + required: this.get("required"), + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + if (_.isArray(this.get("options")) && !this.get("options").length) { + this.attributes.options = [ + { + "value": "1", + "label": "true" + }, + { + "value": "0", + "label": "false" + } + ]; + this.attributes.dataType = "boolean"; + } + if (this.get("data") || this.get("value") || this.get("defaultValue")) { + data = this.initData(this.get("defaultValue"), this.get("value"), this.get("data"), this.get("variable")); + this.set({data: data}, {silent: true}); + this.attributes.value = this.get("data")["value"]; + } else { + this.attributes.data["value"] = ""; + this.attributes.data["label"] = ""; + this.attributes.value = this.get("data")["value"]; + } + this.initControl(); + this.attributes.value = this.get("data").value; + this.get("validator").set("value", this.get("value")); + this.setLocalOptions(); + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this.defineModelEvents(); + return this; + }, + initControl: function () { + var opts = this.get("options"), + i, + newOpts = [], + itemsSelected = []; + if (_.isArray(opts)) { + for (i = 0; i < opts.length; i += 1) { + if (!opts[i].value && (typeof opts[i].value !== "number")) { + opts[i].value = opts[i].label; + } + if (this.get("data") && this.get("data").value) { + if (this.get("data").value.indexOf(opts[i].value) > -1) { + opts[i].selected = true; + } else { + opts[i].selected = false; + } + } + newOpts.push({ + label: opts[i].label, + value: opts[i].value, + selected: opts[i].selected ? true : false + }); + } + } + this.set("options", newOpts); + this.set("selected", itemsSelected); + }, + setLocalOptions: function () { + this.set("localOptions", this.get("options")); + return this; + }, + getData: function () { + if (this.get("group") === "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: [this.get("value")] + } + + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: [this.get("value")] + } + } + return this; + }, + validate: function (attrs) { + var value; + value = parseInt(this.get("data")["value"]); + if (this.get("enableValidate")) { + this.get("validator").set("value", value); + if (this.get("options").length) { + this.get("validator").set("options", this.attributes.options); + } + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + isValid: function () { + return this.get("valid"); + }, + /** + * Update data with the current value + * @returns {CheckBoxModel} + */ + updateItemSelected: function () { + var currValue = this.get("value"), + currData = this.get("data"); + if (!this.attributes.disabled) { + this.get("validator").set({ + valueDomain: currValue, + options: this.get("options") + }); + this.get("validator").set("value", this.get("selected").length); + this.get("validator").verifyValue(); + } + if (currValue && currData) { + this.setData(currValue); + } + return this; + }, + /** + * Update value with the current data + * @returns {CheckBoxModel} + */ + updateValue: function () { + var currentData = this.get("data"); + if (currentData && currentData.value) { + this.set({value: currentData.value}, {silent: true}); + } + return this; + }, + /** + * Get Value from data + * @returns {null} + */ + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * Set Value + * @param value + * @returns {CheckBoxModel} + */ + setValue: function (value) { + var valuesForTrue = [1, true, "1", "true"], + valuesForFalse = [0, false, "0", "false"]; + value = (_.isArray(value) && value.length > 0) ? value[0] : value; + if (value !== undefined) { + if (valuesForTrue.indexOf(value) > -1) { + this.set("value", "1"); + } else if (valuesForFalse.indexOf(value) > -1) { + this.set("value", "0"); + } + } + return this; + }, + /** + * Set Data + * @param value + * @returns {CheckBoxModel} + */ + setData: function (value) { + var data = this.findOption(value, "value"); + if (data) { + this.set('data', { + value: data.value || '', + label: data.label || '' + }); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {boolean|string|number} valid data for this component + */ + setAppData: function (value) { + var data; + data = this.findOption(value, "value"); + if (data) { + this.selectedOptions("index", [data.index]); + this.set({"data": data}, {silent: true}); + this.set({"value": data["value"]}, {silent: true}); + this.set("toDraw", true); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.CheckBox", CheckBoxModel); +}()); + +(function () { + var DatetimeModel = PMDynaform.model.FieldR.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dataType: "date", + group: "form", + hint: "", + id: "", + name: "", + placeholder: "", + tabIndex: "", + ariaLabel: "", + required: false, + validator: null, + originalType: null, + disabled: false, + format: "YYYY-MM-DD", + mode: "edit", + data: { + value: "", + label: "" + }, + value: "", + stepping: 1, + minDate: false, + maxDate: false, + useCurrent: false, + collapse: true, + defaultDate: '', + disabledDates: [], + sideBySide: false, + daysOfWeekDisabled: false, + calendarWeeks: true, + viewMode: "days", + toolbarPlacement: "default", + showTodayButton: true, + showClear: true, + widgetPositioning: { + horizontal: "left", + vertical: "bottom" + }, + keepOpen: false, + dayViewHeaderFormat: "MMMM YYYY", + pickType: "datetime", + keyLabel: "", + enableValidate: true, + text: "", + variable: "", + type: "datetime", + label: "untitled label", + datetimeIsoFormat: "YYYY-MM-DD HH:mm:ss", + dateIsoFormat: "YYYY-MM-DD", + dependentOptions: {}, + dependencyDidUpdate: false + }, + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") + } + + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + } + return this; + }, + initialize: function (options) { + var useDefaults = { + showClear: false, + useCurrent: false + }, + useCurrentOptions = [true, false, 'year', 'month', 'day', 'hour', 'minute'], + viewMode = ['years', 'months', 'days'], + data = { + value: "", + label: "" + }, + defaultDate, + maxOrMinDate, + flag = true, + dependentOption; + this.redefinepropertiesV4(options); + + if (this.get("useCurrent") === "true") { + this.attributes.useCurrent = JSON.parse(this.get("useCurrent")); + } + if (useCurrentOptions.indexOf(this.get("useCurrent")) === -1) { + this.attributes.useCurrent = useDefaults["useCurrent"]; + } + + if (this.get("showClear") === "true") { + this.attributes.showClear = JSON.parse(this.get("showClear")); + } + + if (this.get("showClear") === "false") { + this.attributes.showClear = JSON.parse(this.get("showClear")); + } + if (typeof this.get("showClear") !== "boolean") { + this.attributes.showClear = useDefaults["showClear"]; + } + + if (this.get("format") === "false") { + this.attributes.format = JSON.parse(this.get("format")); + } + + this.customPickTimeIcon(this.get("pickType")); + + if (!_.isEmpty(this.get("data")) && (this.get("data")["value"] !== "" || this.get("data")["label"] !== "")) { + this.set("defaultDate", false); + } else { + this.set("value", this.get("defaultDate")); + this.set("data", data); + } + if (typeof this.get("maxDate") === "boolean") { + this.set("maxDate", ""); + } + + if (!this.isDate(this.get("maxDate"))) { + this.set("maxDate", ""); + } + + if (!this.isDate(this.get("minDate"))) { + this.set("minDate", ""); + } + + if (!this.isDate(this.get("defaultDate"))) { + this.set("defaultDate", ""); + } + + if (this.get("maxDate").trim().length && this.get("defaultDate") && this.get("defaultDate").trim().length) { + defaultDate = this.get("defaultDate").split("-"); + maxOrMinDate = this.get("maxDate").split("-"); + if ((parseInt(defaultDate[0]) <= parseInt(maxOrMinDate[0]))) { + if ((parseInt(defaultDate[1]) <= parseInt(maxOrMinDate[1]))) { + if ((parseInt(defaultDate[2]) <= parseInt(maxOrMinDate[2]))) { + flag = true; + } else { + flag = false; + } + } else { + flag = false; + } + } else { + flag = false; + } + if (!flag) { + this.set("defaultDate", false); + } + } + if (flag) { + if (typeof this.get("minDate") === "boolean") { + this.set("minDate", ""); + } + if (this.get("minDate").trim().length && this.get("defaultDate") && this.get("defaultDate").trim().length) { + defaultDate = this.get("defaultDate").split("-"); + maxOrMinDate = this.get("minDate").split("-"); + if ((parseInt(defaultDate[0]) >= parseInt(maxOrMinDate[0]))) { + if ((parseInt(defaultDate[1]) >= parseInt(maxOrMinDate[1]))) { + if ((parseInt(defaultDate[2]) >= parseInt(maxOrMinDate[2]))) { + flag = true; + } else { + flag = false; + } + } else { + flag = false; + } + } else { + flag = false; + } + if (!flag) { + this.set("defaultDate", false); + } + } + } + if (this.get("data") && this.get("data")["value"] !== "") { + this.attributes.value = this.get("data")["value"]; + this.attributes.keyLabel = this.get("data")["label"]; + } else { + if (this.get("defaultDate") !== "") { + this.attributes.data = { + value: this.get("defaultDate"), + label: this.get("defaultDate") + }; + } else { + this.attributes.data = { + value: "", + label: "" + }; + } + } + this.set("validator", new PMDynaform.model.Validator({ + required: this.get("required"), + type: this.get("type"), + dataType: this.get("dataType"), + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this.defineModelEvents(); + this.set("text", this.get("data")["label"]); + // Registering dependency events + if (this.get("dependentOptions")) { + for (dependentOption in this.get("dependentOptions")) { + this._dependentFieldEventRegister(this.get("dependentOptions")[dependentOption]); + } + } + return this; + }, + customPickTimeIcon: function (format) { + + }, + isValid: function () { + return this.get("valid"); + }, + validate: function (attrs) { + var valueFixed = this.get("data")["value"]; + if (this.get("enableValidate")) { + this.get("validator").set("value", valueFixed); + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + isDate: function (dateValue) { + var pattern = /@@|@\$|@=/; + var d = new Date(dateValue); + if (pattern.test(dateValue) || d == "Invalid Date" || typeof d == "undefined" || !d) { + return false; + } + return true; + }, + validateDate: function (date) { + var valid, data, value; + value = date.replace(/-/g, "/"); + if (new Date(value).toString() !== "Invalid Date") { + valid = true; + } else { + valid = false; + } + return valid; + }, + formatedData: function (value) { + var newData, + format = 'YYYY-MM-DD HH:mm:ss'; + if (value) { + newData = { + value: moment(value).format(format), + label: moment(value).format(this.get('format')) + }; + } + return newData; + }, + onChangeValue: function (attrs, item) { + var data = { value: "", label: "" }; + if (item !== undefined) { + if (this.validateDate(item)) { + data = this.formatedData(item); + } + } + this.set("data", data); + this.attributes.value = data["value"]; + this.attributes.text = data["label"]; + return this; + }, + onChangeText: function (attrs, item) { + // This method is not support to this control type + return this; + }, + /** + * Some property values that were modified in updating v3 to v4 is redefined necessary + * @param {Object} settings json configuration stored in definitiong + * @return {Object} new json configuration + */ + redefinepropertiesV4: function (settings) { + var propConf; + if (typeof settings === "object") { + if (this.get("daysOfWeekDisabled")) { + propConf = this.get("daysOfWeekDisabled"); + propConf = (_.isArray(propConf) && _.isEmpty(propConf)) ? false : propConf; + this.set("daysOfWeekDisabled", propConf); + } + } + return this; + }, + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * Set value + * @param value + * @param {callback} fn + * @returns {DatetimeModel} + */ + setValue: function (value, fn) { + if (value !== undefined && value !== null) { + this.set("value", value); + this.set("text", value); + this.set("data", { + value: value, + label: value + }); + if (_.isFunction(fn)) { + fn(); + } + } + return this; + }, + /** + * Set text + * @param value + * @param {callback} fn + */ + setText: function (value, fn) { + this.setValue(value); + if (_.isFunction(fn)) { + fn(); + } + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {string} valid data for this component + */ + setAppData: function (value) { + if (value !== undefined) { + value = value.replace(/-/g, "/"); + if (new Date(value).toString() !== "Invalid Date") { + this.set("value", value); + } else if (!value) { + this.set("value", ""); + } + } + return this; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * Subscribe the changes in dependencies + * @param {*} dt + * @param {*} serial + * @returns {FieldModel} + */ + executeDependency: function (dt, serial) { + var that = this; + _.extend(dt, this.preparePostData()); + this.set("dependencyDidUpdate", { error: false }); + this.get("form").get("dependentsManager").emit({ + channel: "dependencies", + event: that.getFieldId() + serial, + payload: "" + }); + newOptions = this.getWidgetOption(dt); + this.get("view").updateSettings(newOptions); + if (this.get("parent").get("type") === "grid" && dt.internalType !== "grid") { + this.get("parent").updateGridColumn(dt, this.getDataOptions(dt)); + } + return this; + }, + /** + * Get and prepare options for bootstrap DateTimepicker widget + * @param {Object} dt + * @returns {Object} + */ + getWidgetOption: function (dt) { + var widgetOption = {}, + option, + item, + optionSelected; + for (item in dt) { + optionSelected = null; + for (option in this.get("dependentOptions")) { + if (this.get("dependentOptions")[option].substr(2) === item) { + optionSelected = option; + break; + } + } + if (optionSelected && moment(dt[item]).isValid()) { + widgetOption[optionSelected] = moment(dt[item]).format(this.get("format")); + } + } + return widgetOption; + }, + /** + * Get and prepare options for dependencies + * @param {Object} dt + * @returns {Object} + */ + getDataOptions: function (dt) { + var widgetOption = {}, + option, + item, + optionSelected; + for (item in dt) { + optionSelected = null; + for (option in this.get("dependentOptions")) { + if (this.get("dependentOptions")[option].substr(2) === item) { + optionSelected = option; + break; + } + } + if (optionSelected && moment(dt[item]).isValid()) { + widgetOption[optionSelected] = dt[item]; + } + } + return widgetOption; + }, + /** + * After render Handler, will be fired if the form was rendered + * First time the dependent fields need to be update if there is dependencies + */ + afterRenderHook: function () { + if (!_.isEmpty(this.get("dependentOptions"))) { + this.get("form").get("dependentsManager").defaultValuesDependency(this); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.DatetimeR", DatetimeModel); +}()); + +(function () { + var SuggestModel = PMDynaform.model.FieldR.extend({ + defaults: { + autoComplete: "off", + type: "suggest", + placeholder: "untitled", + label: "untitled label", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("suggest"), + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + group: "form", + defaultValue: "", + tabIndex: "", + ariaLabel: "", + maxLengthLabel: 15, + mode: "edit", + tooltipLabel: "", + disabled: false, + dataType: "string", + executeInit: true, + required: false, + maxLength: null, + validator: null, + valid: true, + proxy: null, + variable: '', + var_uid: null, + var_name: null, + options: [], + localOptions: [], + remoteOptions: [], + columnName: null, + originalType: null, + mask: "", + clickedControl: true, + keyLabel: "", + enableValidate: true, + filter: '', + data: { + value: '', + label: '' + }, + hint: '', + nameModalSuggest: null, + dependencyDidUpdate: false, + memoryCache: false, + dataForDependent: {}, + resultsLimit: "10" + }, + eventsMobile: { + EXECUTE_QUERY_SUGGEST: "suggestField/executeQuery" + }, + /** + * Initialize the Field model + * @param {*} attrs + */ + initialize: function (attrs) { + var data; + this.set("dataType", this.get("dataType").trim().length ? this.get("dataType") : "string"); + this.set("optionsSql", null); + this.set("label", this.get("label")); + this.set("dataForDependent", {}); + this.set("defaultValue", this.get("defaultValue")); + this.set("validator", new PMDynaform.model.Validator({ + "required": this.get("required"), + requiredFieldErrorMessage: this.get("requiredFieldErrorMessage") + })); + this.initControl(); + this.setLocalOptions(); + this.setRemoteOptions(); + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this._dependentFieldEventRegister(this.get("sql")); + }, + /** + * Init the control with the default value + */ + initControl: function () { + var data = this.get("data"); + if (data && data["value"] === "" && data["label"] === "") { + if (this.get("defaultValue")) { + this.set("data", { + label: this.get("data").label, + value: this.get("defaultValue") + }); + } + } + }, + /** + * Set the local options in model + * @returns {SuggestModel} + */ + setLocalOptions: function () { + this.set("localOptions", this.get("options")); + return this; + }, + /** + * Return the flag valid + * @returns {boolean} + */ + isValid: function () { + return this.get("valid"); + }, + /** + * Validate the model + * @param {*} attrs + * @returns {SuggestModel} + */ + validate: function (attrs) { + var valueFixed = this.get("data")["value"]; + if (this.get("enableValidate")) { + this.get("validator").set("type", this.get("type")); + this.get("validator").set("required", this.get("required")); + this.get("validator").set("value", valueFixed); + this.get("validator").set("dataType", this.get("dataType")); + this.get("validator").verifyValue(); + } else { + this.get("validator").set("valid", true); + } + this.set("valid", this.get("validator").get("valid")); + return this; + }, + /** + * Return the data in format + * @returns {Object} + */ + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("data")["value"] + } + } + }, + /** + * Return the value + * @returns {Object} + */ + getValue: function () { + var data = this.get("data"); + return data ? data["value"] : null; + }, + /** + * Set Value Only works in mobile GRID ATTENTION!!!! + * @param value + * @param callback + * @returns {SuggestModel} + */ + setValue: function (value, callback) { + var that = this, dt; + this.executeQuery({ + value: value, + typeSearch: 'val' + }, function (response, err) { + if (response) { + dt = that._findOption(response, 'val', value); + that.dependencyWillUpdate({ + data: { + value: dt.value, + label: dt.text + }, + fn: callback + }); + } + }); + }, + /** + * Set Text Only works in mobile GRID ATTENTION!!!! + * @param value + * @param callback + * @returns {SuggestModel} + */ + setText: function (value, callback) { + var that = this, dt; + this.executeQuery({ + value: value, + typeSearch: 'text' + }, function (response, err) { + if (response) { + dt = that._findOption(response, 'text', value); + that.dependencyWillUpdate({ + data: { + value: dt.value, + label: dt.text + }, + fn: callback + }); + } + }); + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + * @returns {SuggestModel} + */ + setAppData: function (data) { + if (data.hasOwnProperty("value") && data.hasOwnProperty("label")) { + this.set({ "data": data }, { silent: true }); + this.set({ "value": data.value }, { silent: true }); + this.set("toDraw", true); + } + return this; + }, + /** + * buildDataForQuery, Builds the data needed to execute the query correctly + * @param info {object}: the initial data of the fields on which this component depends + * @returns dataForDependent {object} + */ + buildDataForQuery: function (info) { + var dataForDependent = this.get("form").get("dependentsManager").getDependenciesData(this); + _.extend(dataForDependent, this.preparePostData()); + _.extend(dataForDependent, { + app_uid: (PMDynaform.getProjectKeys() && PMDynaform.getProjectKeys().caseUID) ? + PMDynaform.getProjectKeys().caseUID : null, + filter: this.get('data').value, + order_by: "ASC", + var_name: this.get("id"), + limit: this.get("resultsLimit"), + sql: this.get("sql") + }); + if (this.get("dataForDependent")) { + _.extend(dataForDependent, this.get("dataForDependent")); + } + return dataForDependent; + }, + /** + * EXECUTION DEPENDENCIES METHOD + * @param {*} dt + * @param {*} serial + * @returns {SuggestModel} + */ + executeDependency: function (dt, serial) { + this.set("data", { + label: "", + value: "" + }); + this.set("dataForDependent", _.extend(dt, this.preparePostData())); + this.set("dependencyDidUpdate", { error: false }); + this.trigger('change:dependencyDidUpdate'); + this.get("form").get("dependentsManager").emit({ + channel: "dependencies", + event: this.getFieldId() + serial, + payload: "" + }); + return this; + }, + /** + * Only work with setValue helper or setOnChange helper + * @param {*} params + * @param {*} callback + */ + executeQuery: function (params, callback) { + var prj = this.get("project"), + variable, + data = { + "query": { + match: (params.typeSearch === 'text') ? { text: params.value } : { value: params.value } + } + }; + _.extend(data, this.buildDataForQuery({})); + + if (this.get("group") === "grid") { + variable = this.get("columnName"); + } else { + variable = this.get("id"); + } + + if (PMDynaform.core.ProjectMobile) { + prj.requestManager.channelEvents({ + handler: this.get("id"), + type: this.eventsMobile.EXECUTE_QUERY_SUGGEST, + bridge: true, + data: data, + callback: function (response) { + if (_.isFunction(callback)) { + callback(response); + } + } + }); + } else { + this.xhr = prj.webServiceManager.execQuerySuggest({ + data: data, + variable: variable, + callback: callback, + async: this.get("form").get("isSync") ? false : true + }); + } + }, + /** + * Filter local options + * @param value + * @param maxItems + * @param elements + * @returns {Array} + */ + filterLocalOptions: function (value, maxItems, elements) { + var itemLabel, + count = 0, + data = []; + if (value) { + $.grep(elements, function (options) { + itemLabel = options.label.toString(); + if ((itemLabel.toLowerCase().indexOf(value.toLowerCase()) !== -1) && count < maxItems) { + data.push(options); + count += 1; + } + }); + } else { + data = $.grep(elements, function (n, i) { + return (i < maxItems); + }); + } + return data; + }, + /** + * Merge Local Options And Remote Options + * @param data + * @param params + * @returns {*} + */ + mergeLocalAndRemoteOptions: function (data, params) { + var elements = [], + par = params && params.data ? params.data.filter : params.term; + elements = this.filterLocalOptions(par, this.get("resultsLimit"), this.get('options')); + data = elements.concat(data); + data = (!data.length && !params.term) ? data.concat(this.get("view").getDataSelect2()) : data; + return data; + }, + /** + * Look up the value and the text + * @param response + * @param typeSearch + * @param value + * @returns {*} + * @private + */ + _findOption: function (response, typeSearch, value) { + var newOpt, + dataMerge = response.concat(this.get('options')); + if (typeSearch === 'text') { + //if the setText helper is executed + newOpt = _.find(dataMerge, function (item) { + var text = item.label || item.text; + return text.toUpperCase() === value.toUpperCase(); + }); + } else { + //if the setValue helper is executed + newOpt = _.find(dataMerge, function (item) { + return item.value.toUpperCase() === value.toUpperCase(); + }); + } + return newOpt; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.SuggestR", SuggestModel); +}()); + +(function () { + var LinkModel = PMDynaform.model.Field.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dataType: "string", + defaultValue: "", + disabled: false, + group: "form", + hint: "", + href: "", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("link"), + label: "untitled label", + tabIndex: "", + ariaLabel: "", + mode: "edit", + required: false, + target: "_blank", + targetOptions: { + blank: "_blank", + parent: "_parent", + self: "_self", + top: "_top" + }, + rel:"noopener noreferrer", + type: "link", + valid: true, + value: "", + columnName: null, + originalType: null, + text: "", + protocol: "http://" + }, + initialize: function (options) { + var data = this.getData(), + text = data ? data.label : this.get("value"); + this.set("text", text || ""); + this.setHref(this.get("href")); + this.on("change:text", this.onChangeText, this); + this.on("change:value", this.onChangeValue, this); + this.setTarget(); + }, + setTarget: function () { + var opt = this.get("targetOptions"), + target; + + target = opt[this.get("target")] ? opt[this.get("target")] : "_blank"; + this.set("target", target); + }, + getData: function () { + return this.get("data"); + }, + /** + * Validation w3c URL standards + * @param url + * @returns {boolean} + */ + validationURL: function (url) { + var regExp = new RegExp (['^ *((ed2k|ftp|http|https|irc|mailto|news|gopher|nntp|telnet|webcal|xmpp|callto', + '|feed|svn|urn|aim|rsync|tag|ssh|sftp|rtsp|afs|file|javascript|tel|ldap):|#|\\/|\\.|\\?)'].join('')); + return regExp.test(url); + }, + + /** + * Reformat URL, add protocol + * @param url + * @returns {*} + */ + reformatURL: function (url) { + return this.get("protocol") + url; + }, + setHref: function (href) { + var newHref = href; + if (!this.validationURL(href)) { + newHref = this.reformatURL(href); + } + this.set("href", newHref); + this.updateData(newHref, this.get("text")); + return this; + }, + onChangeValue: function (attrs, item) { + if (item) { + this.setHref(item); + } + return this; + }, + onChangeText: function (attrs, item) { + if (item) { + this.set("text", item); + this.updateData(this.get("href"), item); + } + return this; + }, + updateData: function (href, dText) { + this.set("data", { + value: href, + label: dText + }); + return this; + }, + getValue: function () { + var href = this.get("href"); + return href ? href : ""; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Link", LinkModel); +}()); +(function () { + + var Label = PMDynaform.model.FieldR.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + group: "form", + hint: "", + namespace: "pmdynaform", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("label"), + label: "untitled label", + mode: "view", + options: [], + required: false, + type: "label", + columnName: null, + originalType: null, + variable: "", + var_uid: null, + var_name: null, + localOptions: [], + remoteOptions: [], + fullOptions: [""], + data: null, + value: null, + dataType: null, + keyValue: null, + optionsSql: [], + enableValidate: true, + optionsToTrue: [true, 1, "true", "1"], + optionsToFalse: [false, 0, "false", "0"], + /** + * @param {object}: dataForDependent, Stores data to eject dependent field service + */ + dataForDependent: {}, + /** + * @param {boolean}: supportedOptions + */ + supportedOptions: false, + ariaLabel: "" + }, + initialize: function (options) { + var originalType = this.get("originalType"), + newData; + if (options && _.isArray(options["options"])) { + this.set("supportedOptions", true); + } + this.set("dataForDependent", {}); + this.set("label", this.get("label")); + this.set('defaultValue', this.get('defaultDate') || this.get('defaultValue')); + this.on("change:label", this.onChangeLabel, this); + this.on("change:options", this.onChangeOptions, this); + this.on("change:data", this.onChangeData, this); + this.setLocalOptions(); + this.setRemoteOptions(); + this.mergeOptionsSql(); + this.setData(options.data); + if (originalType === "checkbox") { + newData = this.initData(this.get("defaultValue"), this.get("value"), this.get("data")); + this.setData(newData); + } + if (_.isString(this.get("variable")) && this.get("variable") !== "") { + this.set("name", this.get("variable") ? this.get("variable") : this.get("id")); + } + if (typeof this.get("formula") === "string" && + this.get('formula') !== "undefined" && + this.get('formula') !== "null" && + this.get('formula').length > 1) { + this.set("formulator", new PMDynaform.core.Formula(this.get("formula"))); + this.set("disabled", true); + } + this._dependentFieldEventRegister(this.get("sql")); + return this; + }, + getData: function () { + var value = ""; + if (this.get("group") == "grid") { + if (this.get("originalType") !== "label") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("keyValue") + } + } else { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") + } + } + } else { + if (this.get("originalType") !== "label") { + value = this.get("data")["value"]; + if (this.get('originalType') === 'checkbox') { + value = this.get("value"); + } + return { + name: this.get("name") ? this.get("name") : "", + value: value + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") + } + } + } + }, + /** + * setData, Set the data in the component + * @chainable + */ + setData: function (data) { + //when it is checkgroup it is necessary to verify the data + if (this.get("originalType") === "checkgroup") { + data = this.getDataCheckgroup(data); + } + + if (data && !_.isEmpty(data) && data.value) { + this.set("data", data); + this.set({ "value": data["value"] }, { silent: true }); + } else { + this.set("data", this.getDataWithDefaultValue()); + this.set({ "value": this.get('data')['value'] }, { silent: true }); + } + this.set("fullOptions", this.obtainingLabelsToShow()); + return this; + }, + /** + * Check data for CheckGroup + * @param data + * @returns {*} + */ + getDataCheckgroup: function (data) { + var value; + if (data && !_.isEmpty(data)) { + value = data.hasOwnProperty("value") && data.value; + if (!value || _.isEmpty(value)) { + data = { + value: [], + label: JSON.stringify([]) + }; + } + } + return data; + }, + setValue: function (value) { + var originalType = this.get("originalType"), + newData; + switch (originalType) { + case "checkbox": + newData = this.getCheckBoxData(value); + break; + case "checkgroup": + newData = this.getCheckGroupData(value); + break; + case "dropdown": + newData = this.getDropDownData(value); + break; + case "datetime": + newData = this.getDateTimeData(value); + break; + case "radio": + newData = this.getRadioData(value); + break; + case "suggest": + newData = this.getSuggestData(value); + break; + default: + newData = this.getTextBoxData(value); + break; + } + this.setNewData(newData); + return this; + }, + /** + * Gets checkbox's data + * @param value + * @returns {{}} + */ + getCheckBoxData: function (value) { + var valuesForTrue = [1, true, "1", "true"], + valuesForFalse = [0, false, "0", "false"], + options = this.get("options"), + valueDefault = (_.isArray(value) && value.length) ? value[0] : value, + dataObject = {}; + if (valuesForTrue.indexOf(valueDefault) > -1) { + dataObject = { + value: options[0]["value"], + label: options[0]["label"] + }; + } else if (valuesForFalse.indexOf(valueDefault) > -1) { + dataObject = { + value: options[1]["value"], + label: options[1]["label"] + }; + } + return dataObject; + }, + /** + * Gets checkgroup's data + * @param values + * @returns {{value: Array, label}} + */ + getCheckGroupData: function (values) { + var data, + dataObject = { + value: [], + label: "[]" + }, + resultOptions; + if (_.isString(values)) { + values = values.split(","); + } + if (_.isArray(values)) { + resultOptions = this.findOptions(values, "value"); + data = this.returnOptionsData(resultOptions); + dataObject = { + value: data["value"], + label: _.isString(data["label"]) ? JSON.parse(data["label"]) : data["label"] + }; + } + return dataObject; + }, + /** + * Gets dropdown's data + * @param value + * @returns {*|boolean|Object|{value: string, label: string}} + */ + getDropDownData: function (value) { + var defaultData = { + value: "", + label: "" + }, + dataObject = this.findOption(value, "value"); + if (!dataObject) { + dataObject = this.get("data"); + } + return dataObject || defaultData; + }, + /** + * Gets datetime's data + * @param value + * @returns {{value: string, label: string}} + */ + getDateTimeData: function (value) { + var format = 'YYYY-MM-DD HH:mm:ss', + dataObject = { value: "", label: "" }; + value = value.replace(/-/g, "/"); + if (new Date(value).toString() !== "Invalid Date") { + dataObject = { + value: moment(value).format(format), + label: moment(value).format(this.get('format')) + } + } + return dataObject; + }, + /** + * Gets radio's data + * @param value + * @returns {*|boolean|Object|{value: string, label: string}} + */ + getRadioData: function (value) { + return this.findOption(value, "value") || { value: "", label: "" }; + }, + /** + * Gets suggest's data + * @param data + * @returns {{value: *, label: *}} + */ + getSuggestData: function (data) { + var dataObject = { + value: data, + label: data + }; + if (data && _.isObject(data) && data.hasOwnProperty("value") && data.hasOwnProperty("label")) { + dataObject = { + value: data.value !== undefined ? data['value'] : "", + label: data.label !== undefined ? data['label'] : "" + } + } + return dataObject; + }, + /** + * Gets textbox and textarea's data + * @param value + * @returns {{value: *, label: *}} + */ + getTextBoxData: function (value) { + return { value: value, label: value } + }, + /** + * Sets new data getted + * @param dataObject + * @returns {Label} + */ + setNewData: function (dataObject) { + this.set("value", dataObject.value); + this.set("data", dataObject); + this.setFullOptions(dataObject.label); + return this; + }, + /** + * Gets full options + * @param items + * @returns {Label} + */ + setFullOptions: function (items) { + var options, + element, + showLabels = []; + if (_.isArray(items)) { + this.set("fullOptions", items); + } else { + try { + options = JSON.parse(JSON.stringify(items)); + if (_.isArray(options)) { + this.set("fullOptions", options); + } else { + element = options; + showLabels.push(element); + this.set("fullOptions", showLabels); + } + } catch (e) { + element = items; + showLabels.push(element); + this.set("fullOptions", showLabels); + } + } + return this; + }, + getValue: function () { + var data = this.get("data"); + return (data && data.value) || ""; + }, + getDataWithDefaultValue: function () { + var data, + options, + i; + data = { + label: this.get("defaultValue") || "", + value: this.get("defaultValue") || "" + }; + options = this.get("options") || []; + for (i = 0; i < options.length; i += 1) { + if (this.get("defaultValue") === options[i].value) { + data = options[i]; + break; + } + } + return data; + }, + setLocalOptions: function () { + this.set("localOptions", this.get("options")); + return this; + }, + addFormulaTokenAssociated: function (formulator) { + if (formulator instanceof PMDynaform.core.Formula) { + formulator.addTokenValue(this.get("id"), this.get("value")); + } + return this; + }, + updateFormulaValueAssociated: function (field) { + var resultField = field.model.get("formulator").evaluate(); + field.model.set("value", resultField); + return this; + }, + addFormulaFieldName: function (otherField) { + this.get("formulator").addField("field", otherField); + return this; + }, + /** + * Gets all labels to show + * @returns {Array} + */ + obtainingLabelsToShow: function () { + var data, + labels = []; + data = this.get("data"); + if (data && !_.isEmpty(data)) { + if (this.get("originalType") === "checkgroup") { + labels = PMDynaform.core.Utils.isJsonAndParse(data["label"]); + } else { + labels.push(data["label"]); + } + } + return labels; + }, + /** + * afterExecuteQuery: After executing the dependent field service, + * it retrieves a data array, here it handles the new data + * @param response {array}: response data set + * @chainable + */ + afterExecuteQuery: function (response) { + var currentValue = this.get("value"), + newValue; + this.clearOptions(); + this.mergeRemoteOptions(response); + this.setFirstOptionInData(); + newValue = this.get("value"); + if (_.isArray(response) && response.length > 1 && this.get("showDependentSpinners") && currentValue !== newValue) { + this.enableDependencySpinners(); + } + return this; + }, + /** + * setFirstOptionInData: Sets the first domain option if it exists + * if there are not domain a default empty data has been setted + */ + setFirstOptionInData: function () { + var index = 0, + supportedOptions = this.get("supportedOptions"), + data, + value, + responseDefault = [{ + value: "", + text: "" + }], + options = this.get("options") || []; + + _.defaults(options, responseDefault); + if (this.get("view")) { + this.get("view").switchSpinnerByControl(); + } + if (_.isArray(options)) { + if (supportedOptions) { + this.mergeRemoteOptions(options); + this.setDomainValue(index, 'index'); + } else { + value = options[index].value ? options[index].value : ""; + data = { + value: value, + label: value + }; + this.set("data", data); + } + this.set("value", this.get("data").value); + } + return this; + }, + /* + * Handler when the execute-query service fails. + * @param {*} response + * @chainable + */ + afterExecuteQueryFail: function (response) { + var form = this.get("form"), + name = this.evaluateName(), + data = { + value: "", + label: "" + }; + form.visited = []; + if (response !== "abort") { + this.get("view").showQueryFailMessage(); + } + this.set("data", data); + this.set("value", data.value); + if (this.get("view")) { + this.get("view").switchSpinnerByControl(); + } + + form.disableDependencySpinners(this.getNameToRegisterEvent(name)); + return this; + }, + /** + * setDomainValue: Set an element of the options as the data for the component + * @param value {number|string|number}: The value you are looking for in the options + * @param criteria {string}: Search criteria, The accepted values can be + * - index + * - value + * - label + * @chainable + */ + setDomainValue: function (value, criteria) { + var options = this.get("options"), + option, + invalidForAutocomplete = ["suggest"], + originalType = this.get("originalType"), + data = { + value: "", + label: "" + }; + if (criteria === "index") { + option = options[value]; + } else if (criteria === "value" || criteria === "label") { + option = this.findOption(value, criteria); + } + if (invalidForAutocomplete.indexOf(originalType) === -1) { + this.set("data", option ? option : data); + } else { + this.setData(data); + } + return this; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + * @param dependencyData {object}, data to complete the component domain + * @chainable + */ + setAppData: function (value, dependencyData) { + var data, + originalType = this.get("originalType"), + values; + + switch (originalType) { + case "checkgroup": + this.recoveryRemoteOptions(dependencyData); + values = this.findOptions(value, "value"); + this.setAppDataToCheckGroup(values); + break; + case "radio": + this.recoveryRemoteOptions(dependencyData); + data = this.findOption(value, "value"); + break; + case "checkbox": + data = this.findOption(value[0], "value"); + break; + case "dropdown": + case "suggest": + if (value.hasOwnProperty("value") && value.hasOwnProperty("label")) { + data = value; + } else { + data = this.findOption(value, value); + } + break; + case "text": + case "textarea": + data = { + value: value, + label: value + }; + break; + case "datetime": + data = this.setDatetimeValue(value); + break; + } + data = data || this.get("data"); + this.set({ "data": data }, { silent: true }); + this.set({ "value": value }, { silent: true }); + if (originalType === "checkgroup") { + this.set("fullOptions", [JSON.parse(data.label)]); + } else { + this.set("fullOptions", [data.label]); + } + this.set("toDraw", true); + return this; + }, + /** + * setDatetimeValue: Sets the corresponding data in the datetime + * @param values {date} valid data for this component + */ + setDatetimeValue: function (value) { + var format = 'YYYY-MM-DD HH:mm:ss'; + value = value.replace(/-/g, "/"); + if (new Date(value).toString() !== "Invalid Date") { + return { + value: moment(value).format(format), + label: moment(value).format(this.get('format')) + }; + } + return null; + }, + /** + * setAppDataToCheckGroup: Sets the corresponding data in the component + * @param values {array} valid data for this component + * @chainable + */ + setAppDataToCheckGroup: function (values) { + var data = { + value: [], + label: [] + }, + i; + if (_.isArray(values)) { + for (i = 0; i < values.length; i += 1) { + data.value.push(values[i].value); + data.label.push(values[i].label); + } + } + data.label = JSON.stringify(data.label); + this.set({ "data": data }, { silent: true }); + this.set({ "value": data.value }, { silent: true }); + return this; + }, + /** + * Abstract method to implement in the extended classes + */ + setAppDataToCheckbox: function () { + + }, + /** + * Retrieves the domain of the component based on + * the fields on which it depends + * @param data {object}: Data of the fields on which it depends + */ + recoveryRemoteOptions: function (data) { + var dependentsManager = this.getDependentsManager(), + response; + if (typeof data === "object" && this.get("supportedOptions")) { + _.extend(data, this.preparePostData()); + this.executeQuery(data); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Label", Label); +}()); + +(function () { + var Title = PMDynaform.model.Field.extend({ + defaults: { + type: "title", + label: "untitled label", + ariaLabel: "", + mode: "view", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("title"), + colSpan: 12, + namespace: "pmdynaform", + className: { + title: "pmdynaform-label-title", + subtitle: "pmdynaform-label-subtitle" + } + }, + initialize: function () { + this.set("label", this.get("label")); + }, + getValue: function () { + var data = this.get("label"); + return data ? data : ""; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Title", Title); +}()); +(function () { + var Empty = Backbone.Model.extend({ + defaults: { + colSpan: 12, + namespace: "pmdynaform", + id: PMDynaform.core.Utils.generateID(), + type: "empty" + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.Empty", Empty); +}()); +(function () { + var HiddenModel = PMDynaform.model.Field.extend({ + defaults: { + colSpan: 12, + dataType: "string", + namespace: "pmdynaform", + defaultValue: null, + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("hidden"), + type: "hidden", + valid: true, + value: "", + group: "form", + var_name: "", + data: null, + keyLabel: "", + options: [], + optionsSql: [], + remoteOptions: [], + text: "", + variable: "" + }, + defineModelEvents: function () { + this.on("change:value", this.onChange, this); + this.on("change:text", this.onChange, this); + return this; + }, + initialize: function (options) { + var data = {}; + this.set("defaultValue", this.get("defaultValue")); + if (!this.get("data")) { + data = { + value: this.get("defaultValue"), + label: this.get("defaultValue") + }; + this.attributes.data = data; + } + this.set("value", this.get("data")["value"]); + this.set("keyLabel", this.get("data")["label"]); + this.setLocalOptions(); + this.setRemoteOptions(); + this.mergeOptionsSql(); + this.initControl(); + if (this.get("variable").trim().length === 0) { + if (this.get("group") === "form") { + this.attributes.name = ""; + } else { + this.attributes.name = this.get("id"); + } + } + this.defineModelEvents(); + this.set("text", this.get("data")["label"]); + return this; + }, + initControl: function () { + if (this.get("defaultValue")) { + this.set("value", this.get("defaultValue")); + } + }, + onChangeValue: function () { + }, + getData: function () { + if (this.get("group") == "grid") { + return { + name: this.get("columnName") ? this.get("columnName") : "", + value: this.get("value") ? this.get("value") : "" + } + } else { + return { + name: this.get("name") ? this.get("name") : "", + value: this.get("value") ? this.get("value") : "" + } + } + }, + onChange: function (attrs, item) { + var data; + data = { + value: item || "", + label: item || "" + }; + this.set("data", data); + this.set({text: item, value: item}); + return this; + }, + getValue: function () { + var data = this.getData(); + return data ? data["value"] : null; + }, + /** + * Sets value and data + * @param value + * @returns {HiddenModel} + */ + setValue: function (value) { + if (value !== null && value !== undefined) { + this.set("value", value); + this.set("data", { + value: value, + label: value + }); + } + return this; + }, + /** + * Will update the column model + * in order to create a new cell + * @param {Object} dt + */ + updateGridModels: function(dt) { + newOptions = {data: this.get("data")}; + this.get("parent").updateGridColumn(dt, newOptions); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.Hidden", HiddenModel); +}()); + +(function () { + var ImageModel = PMDynaform.model.Field.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + disabled: false, + defaultValue: "", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("image"), + label: "untitled label", + tabIndex: "", + ariaLabel: "", + crossorigin: "anonymous", + alt: "", + src: "", + height: "", + width: "", + mode: "view", + shape: "thumbnail", + shapeTypes: { + thumbnail: "img-thumbnail", + rounded: "img-rounded", + circle: "img-circle" + }, + type: "image", + columnName: null, + originalType: null, + group: "form", + alternateText: "", + comment: "", + hint: "" + }, + initialize: function (options) { + var defaults; + this.set("label", this.get("label")); + this.set("defaultValue", this.get("defaultValue")); + this.on("change:label", this.onChangeLabel, this); + this.on("change:value", this.onChangeValue, this); + if (options && options.project) { + this.project = options.project; + } + this.setShapeType(); + }, + setShapeType: function () { + var shape = this.get("shape"), + types = this.get("shapeTypes"), + selected; + + selected = types[shape] ? types[shape] : types["thumbnail"]; + this.set("shape", selected); + return this; + }, + getValue: function () { + var value = this.get("src"); + return value ? value : ""; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.Image", ImageModel); +}()); + +(function () { + var SubFormModel = Backbone.Model.extend({ + defaults: { + colSpan: 12, + namespace: "pmdynaform", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("form"), + type: "form", + mode: "edit", + valid: true, + modelForm: null + }, + initialize: function () { + + }, + getData: function () { + return { + name: this.get("name"), + id: this.get("id"), + variables: {} + } + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.SubForm", SubFormModel); +}()); +(function () { + + var GeoMapModel = PMDynaform.model.Field.extend({ + defaults: { + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + namespace: "pmdynaform", + dragMarker: false, + dataType: "string", + disabled: false, + decimals: 6, + group: "form", + hint: "", + fullscreen: false, + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("link"), + googlemap: null, + label: "untitled label", + mode: "edit", + required: false, + valid: true, + value: "", + navigator: true, + currentLocation: false, + supportNavigator: false, + altitude: 0, + latitude: 0, + longitude: 0, + marker: null, + zoom: 15, + tooltipLabel: "", + panControl: false, + zoomControl: false, + scaleControl: false, + streetViewControl: false, + overviewMapControl: false, + mapTypeControl: false, + title: "" + }, + initialize: function () { + this.set("label", this.get("label")); + this.checkSupportGeoLocation(); + }, + checkSupportGeoLocation: function () { + var supportNavigator = navigator.geolocation ? true : false; + + this.set("supportNavigator", supportNavigator); + + return this; + }, + rightToLeftLabels: function () { + var marker = this.get("marker"), + infowindow = new google.maps.InfoWindow(); + + infowindow.setContent('القاهرة'); + google.maps.event.addListener(marker, 'click', function () { + infowindow.open(this.get("googlemap"), marker); + }); + }, + getData: function () { + return { + name: this.get("variable") ? this.get("variable").var_name : this.get("name"), + value: this.get("longitude") + "|" + this.get("latitude") + }; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.GeoMap", GeoMapModel); +}()); +(function () { + var Annotation = PMDynaform.model.Field.extend({ + defaults: { + type: "annotation", + label: "untitled label", + id: PMDynaform.core.Utils.generateID(), + name: PMDynaform.core.Utils.generateName("title"), + colSpan: 12, + namespace: "pmdynaform", + ariaLabel: "" + }, + initialize: function () { + this.set("label", this.get("label")); + }, + getValue: function () { + var data = this.get("label"); + return data ? data : null; + }, + getAppData: function () { + return {}; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Annotation", Annotation); +}()); +(function () { + var PanelField = PMDynaform.model.Field.extend({ + defaults: { + type: "panel", + showHeader: false, + showFooter: false, + title: "untitled-panel", + footerContent: "
    footer pmdynaform!
    ", + content: "
    content Body in panel PMDynaform
    ", + id: PMDynaform.core.Utils.generateID(), + colSpan: 12, + namespace: "pmdynaform", + typePanel: "default", + border: "1px" + }, + initialize: function (options) { + var length; + if (this.get("border")) { + length = this.verifyLenght(this.get("border")); + this.set("border", length); + } + }, + verifyLenght: function (length) { + if (typeof length === 'number') { + length = length + "px"; + } else if (Number(length).toString() != "NaN") { + length = length + "px"; + } else if (/^\d+(\.\d+)?px$/.test(length)) { + length = length; + } else if (/^\d+(\.\d+)?%$/.test(length)) { + length = length; + } else if (/^\d+(\.\d+)?em$/.test(length)) { + length = length; + } else if (length === 'auto' || length === 'inherit') { + length = length; + } else { + length = "1px"; + } + return length; + } + + }); + PMDynaform.extendNamespace("PMDynaform.model.PanelField", PanelField); +}()); +(function () { + /** + * @class PMDynaform.view.FlashMessageView + * A message to display for a while. + * + * Usage example: + * + * @example + * flashModel = new PMDynaform.ui.FlashMessageModel({ + * message : "This is a flas message", + * emphasisMessage: "Info", + * startAnimation:5000, + * closable:true, + * type:"danger", + * appendTo:document.body, + * duration:5000 + * }); + * flashView = new PMDynaform.ui.FlashMessageView({model:flashModel}) + * flashView.render(); + * + */ + var FlashMessageView = Backbone.View.extend({ + template: _.template($('#tpl-flashMessage').html()), + initialize: function () { + this.model.on('change', this.render, this); + }, + render: function () { + var offsetTarget; + this.$el.html(this.template(this.model.toJSON())); + this.configurateAnimation(); + return this; + }, + /** + * This method sets the necessary parameters for the effect shown + * the message using animation Jquery + * @return {[type]} [description] + */ + configurateAnimation: function () { + var offsetTarget, + target, + animation, + duration = this.model.get('duration'); + + target = this.model.get('appendTo'); + if (!(target instanceof jQuery)) { + target = jQuery(target); + } + offsetTarget = this.calculateContainerPosition(target); + this.fixPosition(offsetTarget); + + animation = this.$el.finish().css({ + 'top': offsetTarget.top - 50 + }).fadeTo(1, 0).animate({ + top: offsetTarget.top, + opacity: 1, + zIndex: '1060' + }, this.model.get('startAnimation'), 'swing'); + + if (duration) { + animation.delay(duration) + .animate({ + top: this.model.get("absoluteTop") ? 0 : offsetTarget.top, + opacity: 0, + zIndex: '0' + }); + } + + $(document.body).append(this.$el); + }, + /** + * This method calculates the position of parent container + * to place the message at the head of it + * @param {[HTMLElement]} target : this a HTML element target + * @return {[type]} return a positions left, top, width + */ + calculateContainerPosition: function (target) { + var offset, + width, + target = target || this.model.get('appendTo'); + if (!(target instanceof jQuery)) { + target = jQuery(target); + } + offset = target.offset(); + width = target.outerWidth(); + if (this.model.get("absoluteTop")) { + offset.top = this.getAbsoluteTopScrollElement(target); + } + return { + top: offset.top || 0, + left: offset.left || 0, + width: width || 0 + } + }, + /** + * This method recalculates and sets the position of the component flash message + * @param {[type]} offset this object with positions for to set in the component + */ + fixPosition: function (offset) { + var showWidth = offset.width / 2, + showLeft = offset.width / 4 + offset.left; + if (this.$el.length) { + this.$el.css({ + top: offset.top, + width: showWidth, + left: showLeft, + position: 'absolute' + }); + } + return this; + }, + getAbsoluteTopScrollElement: function () { + var scrollTop = 0; + if (document.body) { + scrollTop = $(document).scrollTop(); + } + return scrollTop; + } + }); + PMDynaform.extendNamespace('PMDynaform.ui.FlashMessageView', FlashMessageView); +}()); + +(function () { + var FileMobile = PMDynaform.model.Field.extend({ + defaults: { + autoUpload: false, + camera: true, + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + disabled: false, + dnd: false, + dndMessage: "Drag or choose local files", + extensions: "pdf, png, jpg, mp3, doc, txt", + group: "form", + height: "100%", + hint: "", + id: PMDynaform.core.Utils.generateID(), + items: [], + label: "Untitled label", + labelButton: "Choose Files", + mode: "edit", + multiple: false, + name: PMDynaform.core.Utils.generateName("file"), + preview: false, + required: false, + size: 1, //1 MB + type: "file", + proxy: [], + valid: true, + validator: null, + value: "", + files: [], + data: { + value: [], + label: null + }, + enableValidate: true + }, + + initialize: function () { + this.attributes.files = []; + this.set("items", []); + this.set("proxy", []); + if (this.get("id") && this.get("id").trim().length !== 0) { + this.set("name", this.get("id")); + } + }, + getAppData: function () { + var data, + idFiles = [], + respData = {}; + data = this.get("data"); + idFiles = _.isObject(data) && !_.isEmpty(data) && data.value ? data.value : idFiles; + respData[this.get("id")] = idFiles; + return respData; + }, + /** + * Validate a file mobile + * @returns {FileMobile} + */ + validate: function () { + var isValid = false, + value, + data = this.getAppData(); + + value = data[this.get("name")]; + if (PMDynaform.core.ProjectMobile && this.get("required") && this.get("enableValidate")) { + if (value && _.isArray(value) && value.length > 0) { + isValid = true; + } + } else { + isValid = true; + } + this.set("valid", isValid); + return this; + }, + getIDImage: function (index) { + return this.attributes.images[index].id; + }, + getBase64Image: function (index) { + return this.attributes.images[index].value; + }, + makeBase64Image: function (base64) { + return "data:image/png;base64," + base64; + }, + /** + * Request Array Image Data + * @param arrayImages + * @returns [{id:"123456789...", base64: "sdhfg%4hd/f24g.."}] || [] + */ + remoteProxyData: function (arrayImages) { + var project = this.get("project"), + response, + requestManager = project && PMDynaform.core.ProjectMobile ? project.getRequestManager() : null, + respData = [], + data; + data = this.formatArrayImagesToSend(arrayImages); + response = requestManager ? requestManager.imagesInfo(data) : project.webServiceManager.imagesInfo(data); + respData = this.formatArrayImages(response); + return respData; + }, + /** + * Format structure of the array of objects(files) + * @param arrayImages + * @returns {Array} + */ + formatArrayImagesToSend: function (arrayImages) { + var i, + item, + imageId, + defaultSize = 100, + dataToSend = []; + for (i = 0; i < arrayImages.length; i += 1) { + imageId = arrayImages[i]; + item = {}; + item.fileId = imageId; + item.version = 1; + if (PMDynaform.core.ProjectMobile) { + item.width = defaultSize; + } + dataToSend.push(item); + } + return dataToSend; + }, + /** + * Format response array + * @param arrayImages + * @returns {*} + */ + formatArrayImages: function (arrayImages) { + var i; + for (i = 0; i < arrayImages.length; i += 1) { + arrayImages[i].id = arrayImages[i]['fileId']; + arrayImages[i].base64 = arrayImages[i]['fileContent']; + delete arrayImages[i].fileId; + delete arrayImages[i].fileContent; + } + return arrayImages; + }, + remoteProxyDataMedia: function (id) { + var prj = this.get("project"), + url; + url = prj.webServiceManager.getFullURLStreaming(id); + return url; + }, + urlFileStreaming: function (id) { + var prj = this.get("project"), + url, + dataToSend; + url = prj.webServiceManager.getFullURLStreaming(id); + dataToSend = { + id: id, + filePath: url + }; + return dataToSend; + }, + getEndpointVariables: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + endpoint = endPointFixed; + } + } + } + return endPointFixed; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var view = this.get("view"); + if (data && view) { + view.setFilesRFC(data); + } + return this; + }, + /** + * Get Array Files Image Control + */ + getFiles: function () { + return this.get("files"); + }, + /** + * Set Array Files + * @param arrayFiles + * @returns {FileMobile} + */ + setFiles: function (arrayFiles) { + if (arrayFiles.length) { + this.set("files", arrayFiles); + } + return this; + }, + /** + * Update data + * @param arrayFiles + * @returns {FileMobile} + */ + updateData: function (arrayFiles) { + var i, + data, + idFiles = [], + max = _.isArray(arrayFiles) ? arrayFiles.length : 0; + for (i = 0; i < max; i += 1) { + idFiles.push(arrayFiles[i].id); + } + this.set("data", { + value: idFiles, + label: null + }); + return this; + }, + /** + * Add Item to Array Files + * @param item + */ + addItemFile: function (item) { + var arrayFiles = this.getFiles(); + if (item) { + arrayFiles.push(item); + } + this.setFiles(arrayFiles); + this.updateData(arrayFiles); + return this; + }, + /** + * Change the file id with a "newID". Using the "oldId" to do that used only for offline purposes + * @param oldId + * @param newId + */ + exchangeMobileDataId: function (oldId, newId){ + var dataArray = this.get('data').value, + filesArray = this.get('files'), + index = dataArray.indexOf(oldId); + if (index >= 0) { + dataArray[index] = newId; + // force to update files id + if (_.isArray(filesArray) && filesArray[index]) { + filesArray[index].id = newId; + } + } + this.setFiles(filesArray); + this.updateData(filesArray); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.FileMobile", FileMobile); +}()); + +(function () { + var ImageFieldModel = PMDynaform.model.Field.extend({ + defaults: { + autoUpload: false, + camera: true, + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + disabled: false, + dnd: false, + extensions: "pdf, png, jpg, mp3, doc, txt", + group: "form", + height: "100%", + hint: "", + id: PMDynaform.core.Utils.generateID(), + items: [], + label: "Untitled label", + labelButton: "Choose Files", + mode: "edit", + multiple: false, + name: PMDynaform.core.Utils.generateName("file"), + preview: false, + required: false, + size: 1, //1 MB + type: "file", + proxy: [], + valid: true, + validator: null, + value: "", + files: [], + data: { + value: [], + label: null + }, + enableValidate: true, + blockPreviewImage: false, // block the preview image when image upload progress + deletedFiles: [], // Images deleted Array + fileInProgress: "" + }, + + initialize: function () { + this.attributes.files = []; + this.set("items", []); + this.set("proxy", []); + if (this.get("id") && this.get("id").trim().length !== 0) { + this.set("name", this.get("id")); + } + }, + /** + * Get the data for this model + */ + getAppData: function () { + var data, + idFiles = [], + respData = {}; + data = this.get("data"); + idFiles = _.isObject(data) && !_.isEmpty(data) && data.value ? data.value : idFiles; + respData[this.get("id")] = idFiles; + return respData; + }, + /** + * Validate a file mobile + * @returns {FileMobile} + */ + validate: function () { + var isValid = false, + value, + data = this.getAppData(); + + value = data[this.get("name")]; + if (PMDynaform.core.ProjectMobile && this.get("required") && this.get("enableValidate")) { + if (value && _.isArray(value) && value.length > 0) { + isValid = true; + } + } else { + isValid = true; + } + this.set("valid", isValid); + return this; + }, + /** + * With the index, this method returns the id + * @param index + * @returns {*} + */ + getIDImage: function (index) { + return this.attributes.images[index].id; + }, + /** + * With the index return the base64 data image + * @param index + * @returns {*} + */ + getBase64Image: function (index) { + return this.attributes.images[index].value; + }, + /** + * This method returns a format for image tag base 64 + * @param base64 + * @returns {string} + */ + makeBase64Image: function (base64) { + return "data:image/png;base64," + base64; + }, + /** + * Request Array Image Data + * @param arrayImages + * @returns [{id:"123456789...", base64: "sdhfg%4hd/f24g.."}] || [] + */ + remoteProxyData: function (arrayImages) { + var project = this.get("project"), + response, + requestManager = project && PMDynaform.core.ProjectMobile ? project.getRequestManager() : null, + respData = [], + data; + data = this.formatArrayImagesToSend(arrayImages); + response = requestManager ? requestManager.imagesInfo(data) : project.webServiceManager.imagesInfo(data); + respData = this.formatArrayImages(response); + return respData; + }, + /** + * Format structure of the array of objects(files) + * @param arrayImages + * @returns {Array} + */ + formatArrayImagesToSend: function (arrayImages) { + var i, + item, + imageId, + defaultSize = 100, + dataToSend = []; + for (i = 0; i < arrayImages.length; i += 1) { + imageId = arrayImages[i]; + item = {}; + item.fileId = imageId; + item.version = 1; + if (PMDynaform.core.ProjectMobile) { + item.width = defaultSize; + } + dataToSend.push(item); + } + return dataToSend; + }, + /** + * Format response array + * @param arrayImages + * @returns {*} + */ + formatArrayImages: function (arrayImages) { + var i; + for (i = 0; i < arrayImages.length; i += 1) { + arrayImages[i].id = arrayImages[i]['fileId']; + arrayImages[i].base64 = arrayImages[i]['fileContent']; + delete arrayImages[i].fileId; + delete arrayImages[i].fileContent; + } + return arrayImages; + }, + /** + * Returns the url for get the image in tag html image + * @param id + * @returns {{filePath: *, id: *}} + */ + urlFileStreaming: function (id) { + var prj = this.get("project"), + url, + dataToSend; + url = prj.webServiceManager.getFullURLStreaming(id); + dataToSend = { + id: id, + filePath: url + }; + return dataToSend; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var view = this.get("view"); + if (data && view) { + view.setFilesRFC(data); + } + return this; + }, + /** + * Get Array Files Image Control + */ + getFiles: function () { + return this.get("files"); + }, + /** + * Set Array Files + * @param arrayFiles + * @returns {FileMobile} + */ + setFiles: function (arrayFiles) { + if (arrayFiles.length) { + this.set("files", arrayFiles); + } + return this; + }, + /** + * Delete file in files attribute and data + * @param idFile + */ + deleteFile: function (idFile) { + var nfiles = _.reject(this.attributes.files, function (obj) {return obj.id === idFile;}), + narr = _.map(nfiles, function (obj) {return obj.id;}); + this.addDeleteFileInProject(idFile); + this.set("files", nfiles); + this.set("data", { + label: "", + value: narr + }); + }, + /** + * Update data + * @param arrayFiles + * @returns {FileMobile} + */ + updateData: function (arrayFiles) { + var i, + data, + values = this.get("data").value, + idFiles = [], + max = _.isArray(arrayFiles) ? arrayFiles.length : 0; + for (i = 0; i < max; i += 1) { + idFiles.push(arrayFiles[i].id); + } + this.set("data", { + value: idFiles, + label: null + }); + return this; + }, + /** + * The method add to data the object with the file information to delete when the submit is pressed + * @param fileId + * @returns {ImageFieldModel} + */ + addDeleteFileInProject: function (fileId) { + var file, + fileDel, + prj = this.get("project"), + data = prj.getDataExtra("__VARIABLE_DOCUMENT_DELETE__"); + if (prj) { + fileDel = { + "appDocUid": fileId, + "name": "", + "version": 1 + }; + this.get("deletedFiles").push(fileDel); + data[this.get("id")] = this.get("deletedFiles"); + prj.setDataExtra("__VARIABLE_DOCUMENT_DELETE__", data); + } + return this; + }, + /** + * Add Item to Array Files + * @param item + */ + addItemFile: function (item) { + var arrayFiles = this.getFiles(); + if (item) { + arrayFiles.push(item); + } + this.setFiles(arrayFiles); + this.updateData(arrayFiles); + return this; + }, + /** + * Change the file id with a "newID". Using the "oldId" to do that used only for offline purposes + * @param oldId + * @param newId + */ + exchangeMobileDataId: function (oldId, newId) { + var dataArray = this.get('data').value, + filesArray = this.get('files'), + index = dataArray.indexOf(oldId); + if (index >= 0) { + dataArray[index] = newId; + // force to update files id + if (_.isArray(filesArray) && filesArray[index]) { + filesArray[index].id = newId; + } + } + this.setFiles(filesArray); + this.updateData(filesArray); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.ImageFieldModel", ImageFieldModel); +}()); + +(function () { + var GeoMobile = PMDynaform.model.Field.extend({ + defaults: { + id: PMDynaform.core.Utils.generateID(), + type: "location", + label: "Untitled label", + mode: "edit", + group: "form", + labelButton: "Map", + name: "name", + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + height: "auto", + value: "", + required: false, + hint: "", + disabled: false, + preview: false, + valid: true, + geoData: null, + interactive: true, + fixedLocation: false + }, + eventsMobile: { + SET_FIXED_LOCATION: "geoMapField/setFixedLocation" + }, + initialize: function () { + this.initControl(); + if (this.get("variable") && this.get("variable").trim().length !== 0) { + this.set("name", this.get("variable")); + } + }, + initControl: function () { + this.attributes.images = []; + this.set("preview", true); + return this; + }, + isValid: function () { + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + getDataRFC: function () { + var geoValue = this.attributes.geoData; + if (geoValue == "null" || geoValue == null) { + geoValue = null; + } else { + if (geoValue.imageId == "" || geoValue.imageId == null || typeof geoValue.imageId == "undefined") { + geoValue = geoValue; + } + } + if (geoValue) { + if (geoValue.data) { + delete geoValue.data; + } + } + return { + name: this.get("name"), + value: geoValue + }; + }, + getAppData: function () { + var data = {}, + geoValue = this.attributes.geoData; + if (geoValue) { + if (geoValue.base64) { + delete geoValue.base64; + } + } + data[this.get("name")] = geoValue; + return data; + }, + validate: function (attrs) { + }, + /** + * Get Image in Base64 + * @param id + * @returns {*} + */ + remoteProxyData: function (id) { + var project = this.get("project"); + if (id) { + return project.webServiceManager.imageInfo(id, 600); + } + }, + getImagesNetwork: function (location) { + var prj = this.get("project"), + url, + restClient, + endpoint, + respData = {}; + endpoint = this.getEndpointVariables({ + type: "getImageGeo", + keys: { + "{fileID}": location.imageId, + "{caseID}": prj.keys.caseID, + } + }); + url = prj.getFullURL(endpoint); + restClient = new PMDynaform.core.Proxy({ + url: url, + method: 'POST', + data: { + fileId: location.imageId, + width: "600", + version: 1 + }, + keys: prj.token, + successCallback: function (xhr, response) { + respData = response; + } + }); + this.set("proxy", restClient); + return respData; + }, + getEndpointVariables: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + endpoint = endPointFixed; + } + } + } + return endPointFixed; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var view; + if (data) { + view = this.get("view"); + if (view) { + view.setLocation(data); + } + } + return this; + }, + /** + * Get GeoData + * @returns {*} + */ + getGeoData: function () { + return this.get("geoData"); + }, + /** + * Set Geo Data + * @param data + * @returns {GeoMobile} + */ + setGeoData: function (data) { + if (data && typeof data === "object") { + this.set("geoData", data); + } + return this; + }, + /** + * Sets fixed location property + * and updates it's own property + */ + setFixedLocation: function (value) { + var prj = this.get("project"); + this.set("fixedLocation", value); + prj.requestManager.channelEvents({ + handler: this.get("id"), + type: this.eventsMobile.SET_FIXED_LOCATION, + bridge: true, + data: {fixedLocation: value}, + callback: function (response) { + //TODO callback actions + } + }); + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.GeoMobile", GeoMobile); +}()); + +(function () { + var Qrcode_mobile = PMDynaform.model.Field.extend({ + defaults: { + id: PMDynaform.core.Utils.generateID(), + type: "scannercode", + label: "Untitled label", + mode: "edit", + group: "form", + labelButton: "Scanner Code", + name: "name", + colSpan: 12, + colSpanLabel: 3, + colSpanControl: 9, + height: "auto", + value: "", + required: false, + hint: "", + disabled: false, + preview: false, + valid: true, + codes: [], + geoData: null, + interactive: true + }, + initialize: function () { + this.initControl(); + if (this.get("variable") && this.get("variable").trim().length !== 0) { + this.set("name", this.get("variable")); + } + }, + initControl: function () { + this.attributes.codes = []; + this.set("preview", true); + return this; + }, + isValid: function () { + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + getAppData: function () { + var data = {}; + data[this.get("name")] = this.get("codes"); + return data; + }, + addCode: function (newCode) { + var codes = this.get("codes"); + codes.push(newCode); + }, + validate: function (attrs) { + + }, + getEndpointVariables: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + endpoint = endPointFixed; + } + } + } + return endPointFixed; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var view; + view = this.get("view"); + if (data && view) { + view.setScannerCode(data); + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.model.Qrcode_mobile", Qrcode_mobile); +}()); + +(function () { + var Signature_mobile = PMDynaform.model.Field.extend({ + defaults: { + id: PMDynaform.core.Utils.generateID(), + type: "signature", + label: "Untitled label", + mode: "edit", + group: "form", + labelButton: "Signature", + name: "name", + colSpanLabel: 3, + colSpanControl: 9, + colSpan: 12, + height: "auto", + value: "", + required: false, + hint: "", + disabled: false, + preview: false, + valid: true, + files: [] + }, + initialize: function () { + this.initControl(); + if (this.get("id") && this.get("id").trim().length !== 0) { + this.set("name", this.get("id")); + } + }, + initControl: function () { + this.attributes.files = []; + this.set("preview", true); + return this; + }, + isValid: function () { + this.set("valid", this.get("validator").get("valid")); + return this.get("valid"); + }, + getAppData: function () { + var i, + data = {}, + response = [], + signatureValue = this.attributes.files; + for (i = 0; i < signatureValue.length; i++) { + if (typeof signatureValue[i].id != "undefined" && signatureValue[i].id != null) { + response.push(signatureValue[i].id); + } + } + data[this.get("name")] = response; + return data; + }, + getDataCustom: function () { + var signatureValue = this.attributes.files; + return { + name: this.get("name"), + value: signatureValue + }; + }, + validate: function (attrs) { + + }, + remoteProxyData: function (id) { + return this.get("project").webServiceManager.imageInfo(id, 300); + }, + remoteGenerateID: function (location) { + var prj = this.get("project"), + url, + restClient, + endpoint, + respData = {}; + endpoint = this.getEndpointVariable({ + type: "generateImageGeo", + keys: { + "{caseID}": prj.keys.caseID + } + }); + url = prj.getFullURL(endpoint); + restClient = new PMDynaform.core.Proxy({ + url: url, + method: 'POST', + data: location, + keys: prj.token, + successCallback: function (xhr, response) { + respData = response; + } + }); + this.set("proxy", restClient); + return respData; + + }, + getEndpointVariables: function (urlObj) { + var prj = this.get("project"), + endPointFixed, + variable, + endpoint; + if (prj.endPointsPath[urlObj.type]) { + endpoint = prj.endPointsPath[urlObj.type] + for (variable in urlObj.keys) { + if (urlObj.keys.hasOwnProperty(variable)) { + endPointFixed = endpoint.replace(new RegExp(variable, "g"), urlObj.keys[variable]); + endpoint = endPointFixed; + } + } + } + return endPointFixed; + }, + /** + * setAppData: Sets the corresponding data that is obtained from the + * service to the component + * @param data {object} valid data for this component + */ + setAppData: function (data) { + var view = this.get("view"); + + if (data && view) { + view.setSignature(data); + } + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.model.Signature_mobile", Signature_mobile); +}()); + +(function () { + var MultipleFileModel = PMDynaform.model.Field.extend({ + defaults: { + skin: "neoclassic", + href: "#", + colSpanLabel: 3, + colSpanControl: 9, + colSpan: 12, + disabled: false, + group: "form", + height: "100%", + hint: "", + id: PMDynaform.core.Utils.generateID(), + label: "Untitled label".translate(), + tabIndex: "", + ariaLabel: "", + labelButton: "Choose Files".translate(), + mode: "edit", + name: PMDynaform.core.Utils.generateName("file"), + required: false, + type: "file", + valid: true, + validator: null, + value: "", + gridDetail: "", + gridDetailArray: [], + toRemoveArray: [], + multiFileCount: 0, + data: { + value: [], + label: [] + }, + file: { + title: "", + extension: "", + size: "" + }, + types: { + "264": "video", + "bmp": "image", + "dib": "image", + "dng": "image", + "dt2": "image", + "emf": "image", + "gif": "image", + "ico": "image", + "icon": "image", + "jpeg": "image", + "jpg": "image", + "pcx": "image", + "pic": "image", + "png": "image", + "psd": "image", + "raw": "image", + "tga": "image", + "thm": "image", + "tif": "image", + "tiff": "image", + "wbmp": "image", + "wdp": "image", + "webp": "image", + "7z": "compress", + "7zip": "compress", + "arc": "compress", + "arj": "compress", + "bin": "compress", + "cab": "compress", + "cbr": "compress", + "cbz": "compress", + "cso": "compress", + "dlc": "compress", + "gz": "compress", + "gzip": "compress", + "jar": "compress", + "rar": "compress", + "tar": "compress", + "tar.gz": "compress", + "tgz": "compress", + "zip": "compress", + "3ga": "audio", + "aac": "audio", + "amr": "audio", + "ape": "audio", + "asf": "audio", + "asx": "audio", + "cda": "audio", + "dvf": "audio", + "flac": "audio", + "gp4": "audio", + "gp5": "audio", + "gpx": "audio", + "logic": "audio", + "m4a": "audio", + "m4b": "audio", + "m4p": "audio", + "midi": "audio", + "mp3": "audio", + "ogg": "audio", + "pcm": "audio", + "snd": "audio", + "uax": "audio", + "wav": "audio", + "wma": "audio", + "wpl": "audio", + "numbers": "xls", + "ods": "xls", + "sdc": "xls", + "sxc": "xls", + "xls": "xls", + "xlsm": "xls", + "xlsx": "xls", + "pdf": "pdf", + "1st": "txt", + "alx": "txt", + "asp": "txt", + "csv": "txt", + "eng": "txt", + "htm": "txt", + "html": "txt", + "log": "txt", + "lrc": "txt", + "lst": "txt", + "nfo": "txt", + "opml": "txt", + "plist": "txt", + "pts": "txt", + "reg": "txt", + "rep": "txt", + "srt": "txt", + "sub": "txt", + "tbl": "txt", + "text": "txt", + "txt": "txt", + "xml": "txt", + "xsd": "txt", + "xsl": "txt", + "xslt": "txt", + "odp": "ppt", + "pot": "ppt", + "potx": "ppt", + "pps": "ppt", + "ppsx": "ppt", + "ppt": "ppt", + "pptm": "ppt", + "pptx": "ppt", + "sdd": "ppt", + "key": "ppt", + "keynote": "ppt", + "xps": "ppt", + "3g2": "video", + "3gp": "video", + "avi": "video", + "bik": "video", + "dash": "video", + "dat": "video", + "dvr": "video", + "flv": "video", + "h264": "video", + "m2t": "video", + "m2ts": "video", + "m4v": "video", + "mkv": "video", + "mod": "video", + "mov": "video", + "mp4": "video", + "mpeg": "video", + "mpg": "video", + "mswmm": "video", + "mts": "video", + "ogv": "video", + "prproj": "video", + "rec": "video", + "rmvb": "video", + "swf": "video", + "tod": "video", + "tp": "video", + "ts": "video", + "vob": "video", + "webm": "video", + "wmv": "video", + "abw": "doc", + "aww": "doc", + "cnt": "doc", + "doc": "doc", + "docm": "doc", + "docx": "doc", + "dot": "doc", + "dotm": "doc", + "dotx": "doc", + "epub": "doc", + "ind": "doc", + "indd": "doc", + "odf": "doc", + "odt": "doc", + "ott": "doc", + "oxps": "doc", + "pages": "doc", + "pmd": "doc", + "pub": "doc", + "pwi": "doc", + "rtf": "doc", + "wpd": "doc", + "wps": "doc", + "wri": "doc" + }, + files: [], + fileCollection: null, + formData: null, + fileArray: [], + messageValidations: "This field is required.".translate(), + enableValidate: true + }, + initialize: function (options) { + if (_.isString(this.get("variable")) && this.get("variable") !== "") { + this.set("name", this.get("variable") ? this.get("variable") : this.get("id")); + } + this.set('fileArray', []); + this.set('gridDetailArray', []); + this.set('toRemoveArray', []); + this.set('multiFileCount', 0); + this.set('extensions', this.processPropertyExtension(this.get("extensions"))); + this.set("fileCollection", new PMDynaform.file.FileCollection()); + this.listenTo(this.get("fileCollection"), 'destroy', this.destroyModel); + this.listenTo(this.get("fileCollection"), 'add', this.addModel); + this.set("validator", new Backbone.Model({ + message: { + required: this.get("requiredFieldErrorMessage") || this.get("messageValidations") + } + })); + return this; + }, + /** + * Function to pre-process the extension before input into template + * @param ext{string} + * @returns {string} + */ + processPropertyExtension: function (ext) { + var resp = "", + val, + arr = []; + if (_.isString(ext)) { + $.each(ext.split(","), function (index, value) { + val = value.replace(/\*./g, "."); + val = val.replace(/\.\*/g, "*"); + arr.push(val); + }); + resp = arr.join(","); + } + return resp; + }, + isValid: function () { + + }, + /** + * Function for set data RFC + * @param data + * @returns {FileUpload} + */ + setData: function (data) { + var value, + index; + try { + value = _.isString(data.value) ? JSON.parse(data.value) : data.value; + for (index = 0; index < data.value.length; index += 1) { + this.addFileModelByJSON(data.value[index]); + } + } catch (e) { + console.error(e); + } + }, + /** + * Function for get data for Rest RFC + * @returns {{name: *, value}} + */ + getData: function () { + var data; + data = this.get("fileCollection").getData(); + return { + name: this.get("name"), + value: data + }; + }, + /** + * RFC + * @returns {{name: *, value: *}} + */ + getKeyLabel: function () { + var names; + names = this.get("fileCollection").getNames(); + return { + name: this.get("id") ? this.get("id").concat("_label") : "", + value: names + } + }, + /** + * Validate a file upload + * @returns {FileUpload} + */ + validate: function () { + var isValid = true, + files = this.get("fileCollection"), + data = this.get("data"); + if (this.get("enableValidate")) { + if (this.get("required") === true && !files.validate()) { + isValid = false; + } + } else { + isValid = true; + } + this.set("valid", isValid); + return this; + }, + /** + * Add file based from file wizard browser RFC + * @param file + * @returns {*} + */ + addFileModel: function (file) { + var files = this.get("fileCollection"), + fileSize, + fileExtension, + fileModel; + + fileModel = files.add(new PMDynaform.file.FileModel({ + file: file, + mode: "edit", + parent: this, + project: this.get("project"), + form: this.get("form"), + size: this.get("size"), + sizeUnity: this.get("sizeUnity"), + extensions: this.get("extensions") + })); + + fileSize = fileModel._isFileSizeValid(file, this.get("size"), this.get("sizeUnity")); + fileExtension = fileModel._isFileExtensionValid(file, this.get("extensions")); + + if (!fileSize) { + fileModel.set("isValid", fileSize); + fileModel.set("errorSize", true); + } + if (!fileExtension) { + fileModel.set("isValid", fileExtension); + fileModel.set("errorType", true); + } + files.updateIndex(); + return fileModel; + }, + /** + * Add file based in JSON from setData RFC + * @param file + * @returns {*} + */ + addFileModelByJSON: function (file) { + var files = this.get("fileCollection"), + fileModel; + + fileModel = files.add(new PMDynaform.file.FileModel({ + appDocUid: file.appDocUid, + file: { + name: file.name + }, + version: file.version, + mode: "view", + parent: this, + project: this.get("project"), + form: this.get("form") + })); + fileModel.set("index", files.indexOf(fileModel)); + fileModel.set("completed", true); + return fileModel; + }, + /** + * Function for get value + * @returns {string} + */ + getValue: function () { + var value = ""; + return value; + }, + destroyModel: function (model) { + var i, + files = this.get("fileCollection"); + files.updateIndex(); + this.get("toRemoveArray").push(model); + this.createRemovedHiddens(model); + this.get('view').removeHiddens(); + if (files.models && files.models.length) { + for (i = 0; i < files.models.length; i += 1) { + this.get('view').createHiddenByModel(files.models[i]); + } + } + this.updateData(); + return this; + }, + updateGridDetail: function (fileModel) { + var textDetail = '', + gridDetail = this.get('gridDetailArray'), + i; + if (_.isArray(gridDetail)) { + if (fileModel.get("isValid")) { + gridDetail.push(fileModel.get('file')['name']); + for (i = 0; i < gridDetail.length; i += 1) { + textDetail += (i > 0 ? ', ' : '') + gridDetail[i]; + } + this.set('gridDetail', textDetail); + } + } + }, + /** + * Removes the removed file in the Grid Detail info considering colon + * and if there is one file in multiple file field + * @param fileModel + */ + removeFromGridDetail: function (fileModel) { + var textDetail = '', + gridDetail = this.get('gridDetailArray'), + i; + if (_.isArray(gridDetail) && fileModel.get('index') !== null) { + // remove from array + gridDetail.splice(fileModel.get('index'), 1); + if (gridDetail.length > 0) { + for (i = 0; i < gridDetail.length; i += 1) { + textDetail += (i > 0 ? ', ' : '') + gridDetail[i]; + } + } else { + textDetail = 'Choose File'.translate(); + } + this.set('gridDetail', textDetail); + } + }, + /** + * Create a inputs hidden from a files for delete in Back End + * @param fileModel + */ + createRemovedHiddens: function (fileModel) { + this.get('view').createAllHiddens('add'); + if (fileModel.get("isValid")) { + this.get('view').createDelHiddens(fileModel); + } + }, + /** + * Reset the input Files in views for load a custom files + * @param fileModel + */ + resetInputFile: function () { + if (this.get('group') !== 'grid') { + this.get('view').resetInputFile(); + } else { + this.get('view').resetInputFileModal(); + } + return this; + }, + /** + * Update the data for getData from Form + */ + updateData: function () { + this.set("data", { + value: this.get("fileCollection").getData(), + label: this.get("fileCollection").getNames() + }); + }, + /** + * Delete files in a field + * @returns {MultipleFileModel} + */ + deleteFiles: function () { + this.get("fileCollection").deleteFiles(); + return this; + }, + /** + * Make the array that contains all deleted files + * @returns {object} + */ + makeVariableDocumentDelete: function() { + var removeArray = this.get("toRemoveArray"), + i, + item, + data = [], + result = {}; + for (i = 0; i < removeArray.length; i += 1) { + item = removeArray[i]; + data.push({ + "appDocUid": item.get("appDocUid"), + "name": item.get("file").name, + "version": item.get("version") + }); + } + result[this.get("name")] = data; + return result; + } + }); + PMDynaform.extendNamespace("PMDynaform.file.MultipleFileModel", MultipleFileModel); +}()); + +(function () { + var MultipleFileView = PMDynaform.view.Field.extend({ + template: _.template($("#tpl-multiplefile").html()), + templateInGrid: _.template($("#tpl-multiplefile-grid").html()), + templateInGridField: _.template($("#tpl-multiplefile-grid-field").html()), + validator: null, + $hiddenFile: null, + $hiddenValue: null, + $hiddenLabel: null, + $data: null, + events: { + "click .btn-uploadfile": "onClickButton", + "click .pm-multiplefile-upload": "onClickUploadModal" + }, + initialize: function (options) { + this.form = options.form ? options.form : null; + this.hiddenFile = null; + this.$hiddenFile = null; + this.$hiddenValue = null; + this.$hiddenLabel = null; + this.uploadModalModel = null; + this.uploadModalView = null; + this.model.on('change:gridDetail', this.gridDetailChange, this); + return this; + }, + /** + * Click button for choose files + * @param event + * @returns {FileUpload} + */ + onClickButton: function (event) { + event.preventDefault(); + event.stopPropagation(); + if (this.model.get("mode") === "edit") { + this.openFileWizardWeb(); + } + return this; + }, + onClickUploadModal: function (event) { + var that = this; + event.preventDefault(); + event.stopPropagation(); + this.uploadModalModel = new PMDynaform.file.UploadModalModel({ + parent: that.model + }); + this.uploadModalView = new PMDynaform.file.UploadModalView({ + model: this.uploadModalModel + }); + this.uploadModalView.renderForm(that.model.get('fileCollection')); + return this; + }, + openFileWizardWeb: function (event) { + this.$el.find(".pmdynaform-multiplefile-control input:file").trigger("click"); + return this; + }, + /** + * Function for render field + * @returns {FileUpload} + */ + render: function () { + if (this.model.get('group') === 'grid') { + this.$el.html(this.templateInGrid(this.model.toJSON())); + } else { + this.$el.html(this.template(this.model.toJSON())); + this.$data = this.$el.find(".file-upload-box"); + this.$hiddenFile = this.$el.find("input:file"); + this.$data.hide(); + this.eventsBinding(); + } + this.loadDataFromAppData(); + this.model.updateData(); + this.populateItemsPrintMode(this.getKeyLabel()); + PMDynaform.view.Field.prototype.render.apply(this, arguments); + return this; + }, + loadDataFromAppData: function () { + var data, + name; + if (this.project.mobileDataControls) { + data = this.project.mobileDataControls; + // for purposes of web grids + if (this.model.get('group') === 'grid' + && data[this.parent.model.get('id')] + && data[this.parent.model.get('id')][this.model.get('row') + 1] + && data[this.parent.model.get('id')][this.model.get('row') + 1][this.model.get('columnId')] + && data[this.parent.model.get('id')][this.model.get('row') + 1][this.model.get('columnId')][0] + && data[this.parent.model.get('id')][this.model.get('row') + 1][this.model.get('columnId')][0].appDocUid !== "") { + this.clearHiddenByModel(); + this.setData({ + value: data[this.parent.model.get('id')][this.model.get('row') + 1][this.model.get('columnId')], + label: data[this.parent.model.get('id')][this.model.get('row') + 1][this.model.get('columnId')] + }); + } + //end for purposes of web grids + if (data[this.model.get("name")]) { + name = this.model.get("name"); + this.setData({ + value: data[name], + label: data[name + "_label"] ? data[name + "_label"] : data[name] + }); + } + } + return this; + }, + /** + * Function for get data from model + * @returns {*} + */ + getData: function () { + return this.model.getData(); + }, + getKeyLabel: function () { + return this.model.getKeyLabel(); + }, + /** + * Change ID, this function is used when the device use a async calls to Rest + * @param arrayNew + * @returns {FileUpload} + */ + changeID: function (arrayNew) { + if (_.isArray(arrayNew)) { + this.model.changeID(arrayNew[0]); + } + return this; + }, + /** + * This function execute with setData2 from form Panel + * @param data + * @returns {FileUpload} + */ + setData: function (data) { + var value, + index; + try { + value = _.isString(data.value) ? JSON.parse(data.value) : data.value; + for (index = 0; index < value.length; index += 1) { + if (this.model.get('group') === 'grid') { + this.createGridMultiFile(value, index); + } else { + this.createFormMultiFile(value, index); + } + } + } catch (e) { + console.error(e); + } + }, + /** + * Creates into a form a file model, creates all hiddens related to file + * append the html tag to parent container + * @param options + * @param index + * @returns {MultipleFileView} + */ + + createFormMultiFile: function (options, index) { + var model, + view, + box = this.$el.find(".pmdynaform-multiplefile-box"); + model = this.model.addFileModelByJSON(options[index]); + view = new PMDynaform.file.FileView({ + model: model, + versionable: this.model.get("enableVersioning") + }); + view.render(); + view.createHiddenForProperty(); + box.append(view.$el); + return this; + }, + /** + * Call hiddens creator, an updates the grid info label. + * @param options + * @param index + * @returns {MultipleFileView} + */ + createGridMultiFile: function (options, index) { + var model; + model = this.model.addFileModelByJSON(options[index]); + this.model.updateGridDetail(model); + this.createHiddenByModel(model); + return this; + }, + /** + * trigger to update Detail info in a grid row + */ + gridDetailChange: function () { + var htmlOutput = this.templateInGridField(this.model.toJSON()), + box = this.$el.find(".pm-multiplefile-grid"); + box.html(htmlOutput); + }, + /** + * Validate a File Upload + * @returns {FileUpload} + */ + validate: function () { + if (this.model.get("mode") !== "view") { + if (this.validator) { + this.validator.$el.remove(); + if (_.isFunction(this.removeStyleError)) { + this.removeStyleError(); + } + } + if (_.isFunction(this.model.validate)) { + this.model.validate(); + } + if (!this.model.get("valid")) { + this.validator = new PMDynaform.view.Validator({ + model: this.model.get("validator") + }); + if (this.model.get('group') === 'grid') { + this.$el.find(".pm-multiplefile-grid").append(this.validator.$el); + } else { + this.$el.find(".pmdynaform-field-control").append(this.validator.$el); + } + + if (_.isFunction(this.applyStyleError)) { + this.applyStyleError(); + } + } + } + return this; + }, + /** + * This function apply style error in this field + * @returns {FileUpload} + */ + applyStyleError: function () { + this.$el.addClass("has-error has-feedback"); + return this; + }, + /** + * THis function remove style error in this field + * @returns {FileUpload} + */ + removeStyleError: function () { + this.$el.removeClass('has-error has-feedback'); + return this; + }, + /** + * Add events to view + * @returns {MultipleFileView} + */ + eventsBinding: function () { + var that = this, + dropBox = this.$el.find(".pmdynaform-file-dropbox"); + + this.$hiddenFile.on('change', this.changeFileControl()); + dropBox.on("drop", this.drop()); + dropBox.on('dragover', this.dragOver()); + dropBox.on('dragleave', this.dragLeave()); + return this; + }, + /** + * This function is trigger when select a file in wizard File browser + * @returns {Function} + */ + changeFileControl: function () { + var that = this; + this.populateItemsPrintMode(this.model.getKeyLabel()); + return function (event, ui) { + var files; + event.preventDefault(); + event.stopPropagation(); + files = event.target.files; + that.processFiles(files); + event.target.value = ""; + that.$el.find(that.hiddenFile).remove(); + return false; + }; + }, + drop: function () { + var that = this; + return function (event) { + var files; + event.preventDefault(); + event.stopPropagation(); + files = event.originalEvent.dataTransfer.files; + that.processFiles(files); + return false; + }; + }, + dragLeave: function () { + var that = this; + return function () { + return false; + }; + }, + dragOver: function () { + var that = this; + return function () { + return false + }; + }, + /** + * Add the file to the model multipleFile + * @param files + * @returns {MultipleFileView} + */ + processFiles: function (files) { + var index = 0, + fileView, + fileModel, + box = this.$el.find(".pmdynaform-multiplefile-box"); + if (files.length) { + for (index = 0; index < files.length; index += 1) { + fileModel = this.model.addFileModel(files[index], "edit"); + //create an instance of a file + fileView = new PMDynaform.file.FileView({ + versionable: this.model.get("enableVersioning"), + model: fileModel, + loading: true + }); + //fire wizard flag + fileModel.set('fromWizard', true); + fileView.render(); + box.append(fileView.$el); + fileModel.fileUploadMultipart(); + fileModel.set('fromWizard', false); + } + } + this.validate(); + this.populateItemsPrintMode(this.model.getKeyLabel()); + return this; + }, + /** + * Function for get value from model + * @returns {*} + */ + getValue: function () { + return this.model.getValue(); + }, + /** + * update the files counter + * @param action + * @returns {MultipleFileView} + */ + createAllHiddens: function (action) { + var files = this.model.get("fileCollection"), + i; + this.removeHiddens(); + switch (action) { + case 'add': + if (files.models && files.models.length) { + for (i = 0; i < files.models.length; i += 1) { + if (files.models[i].get('isValid')) { + this.model.get('view').createHiddenByModel(files.models[i]); + } + } + } + break; + case 'remove': + break; + default: + //TODO Actually have not the default behavior + break; + } + this.model.updateData(); + return this; + }, + /** + * Create a inputs hidden to make the object &b send the post HTML + * @returns {FileView} + */ + createHiddenByModel: function (model) { + var prop, + hidden, + name, + nameLabel, + hiddenLabel, + data = model.getData(); + if (model.get("isValid")) { + for (prop in data) { + if (data.hasOwnProperty(prop)) { + if (this.model.get('group') === 'grid') { + name = this.model.get('nameToPostControl') + "[" + model.get("index") + "]" + "[" + prop + "]"; + } else { + name = "form[" + model.getNameFileParent() + "]" + "[" + model.get("index") + "]" + "[" + prop + "]"; + } + hidden = $("", {name: name, type: "hidden", value: data[prop]}); + this.$el.append(hidden); + this.model.get('fileArray').push(hidden); + } + + } + if (this.model.get('group') === 'grid') { + nameLabel = this.model.get('nameToPostLabelControl') + "[" + model.get("index") + "]"; + hiddenLabel = $("", {name: nameLabel, type: "hidden", value: model.get('file')['name']}); + this.$el.append(hiddenLabel); + this.model.get('fileArray').push(hiddenLabel); + } + + } + return this; + }, + /** + * Remove the inputs hidden fron a file + * @returns {FileView} + */ + removeHiddens: function () { + var index; + if (_.isArray(this.model.get('fileArray'))) { + for (index = 0; index < this.model.get('fileArray').length; index += 1) { + this.model.get('fileArray')[index].remove(); + } + } + return this; + }, + /** + * Create hiddes to send the deleted files by POST + * @param model + * @returns {MultipleFileView} + */ + createDelHiddens: function (model) { + var data = model.getData(), + prop, + prj = this.model.get("project"), + hidden, + name; + for (prop in data) { + if (data.hasOwnProperty(prop)) { + name = this.createNameforHidden(prop, model); + hidden = $("", {name: name, type: "hidden", value: data[prop]}); + if (prj) { + prj.view.$el.find("form").append(hidden); + } + } + } + return this; + }, + /** + * Reset the input file html tag for reset properties + */ + resetInputFile: function () { + var nInput = $("", { + type: "file", + style: "display:none", + multiple: "multiple", + accept: this.model.get("extensions") + }); + this.$hiddenFile.before(nInput).remove(); + this.$hiddenFile = nInput; + this.eventsBinding(); + return this; + }, + /** + * Reset the input file in modal case Grid + */ + resetInputFileModal: function () { + this.uploadModalView.resetInputFile(); + return this; + }, + /** + * Create the name string for create hiddens to delete files in form & send to BackEnd + * @param prop + * @returns {string} + */ + createNameforHidden: function (prop, model) { + var index, + name = "", + indexRow = "", + varName = 'form[__VARIABLE_DOCUMENT_DELETE__]', + propName = "[" + prop + "]", + colName = "[" + this.model.get("columnId") + "]", + toRemove = this.model.get('toRemoveArray'), + parent = this.parent || null, + indexArrayRemove = this.model.get("toRemoveArray").length - 1, + column; + if (this.model.get("group") === "grid") { + column = this.model.get("columnId"); + index = parent.getColumnFileDelete(column, model.getNameFileParent()); + indexRow = "[" + index.row + "]"; + name = varName + "[" + this.parent.model.get("name") + "]" + indexRow + colName + "[" + indexArrayRemove + "]" + propName; + } else { + name = varName + "[" + model.getNameFileParent() + "]" + "[" + toRemove.length + "]" + propName; + } + return name; + }, + /** + * Populate MultipleFile on print Mode + * @param arrayItems + */ + populateItemsPrintMode: function (arrayItems) { + var i, + max, + containerPrint = this.$el.find(".content-print"), + itemsMultipleFile = arrayItems.value; + containerPrint.empty(); + for (i = 0, max = itemsMultipleFile.length; i < max; i += 1) { + containerPrint.append("
  • " + itemsMultipleFile[i] + "
  • "); + } + }, + /** + * Gets all files that was not uploaded completely + * @returns {array} + */ + getFilesNotUploaded: function () { + return this.model.get("fileCollection").getFilesNotUploaded(); + }, + /** + * Show flash message with files no uploaded yet. + * @param files + */ + showFilesNoUploaded: function (files) { + var flashModel, + i, + nameFiles = [], + message = "Form cannot be submitted because file(s) {%%%FILES%%%} (are/is) still uploading".translate(); + for (i = 0; i < files.length; i += 1) { + if (files[i].type) { + message = "Form cannot be submitted because file(s) {%%%FILES%%%} (are/is) didn't upload correctly," + + " remove the files from the form or upload the files again".translate(); + } + nameFiles.push(files[i].name); + } + if (files.length > 0) { + message = message.replace("{%%%FILES%%%}", nameFiles); + flashModel = { + message: message, + startAnimation: 1000, + type: "danger", + duration: 4000, + absoluteTop: true + }; + this.project.flashMessage(flashModel); + } + }, + /** + * Remove the inputs type hidden. + */ + clearHiddenByModel: function () { + $(this.el).find('input[type="hidden"]').remove(); + } + }); + + PMDynaform.extendNamespace("PMDynaform.file.MultipleFileView", MultipleFileView); +}()); + +"use strict"; +(function () { + var FileModel = Backbone.Model.extend({ + defaults: { + xhr: null, + file: null, + percentage: null, + appDocUid: null, + index: null, + updateIndex: false, + version: 1, + isValid: true, + fromWizard: false, + urlBase: "{server}/sys{ws}/en/{skin}/cases/cases_ShowDocument?a={docUID}&v=1", + linkService: "showDocument", + errorSize: false, + errorType: false, + error: null, + completed: false + }, + initialize: function (options) { + return this; + }, + /** + * Return a object with basic propeties to save data + * @returns {{appDocUid: *, name: *, version: number}} + */ + getData: function () { + return { + "appDocUid": this.get("appDocUid"), + "name": this.get("file").name, + "version": this.get("version") + }; + }, + /** + * Return the appDocUid from File + * @returns {{appDocUid: *}} + */ + getValue: function () { + return { + appDocUid: this.get("appDocUid") + }; + }, + /** + * Return the name from file + * @returns {*} + */ + getName: function () { + return this.get("file").name; + }, + /** + * Prepare the data for consume the endPoint and the data form multipart to save it. + * @param file + * @return {Array} + */ + prepareDataToUploadMultipart: function (file) { + var arrayResp = [], + parent = this.get("parent"), + type = parent && parent.get("inp_doc_uid") ? "INPUT" : null, + formData, + fieldName; + fieldName = this.get("parent").get("group") === "form" ? this.get("parent").get("var_name") :this.get("parent").get("id"); + formData = new FormData(); + formData.append('form[]', file); + arrayResp.push({ + "name": file.name, + "fieldName": fieldName, + "docUid": parent.get("inp_doc_uid"), + "appDocType": type, + "formData": formData + }); + return arrayResp; + }, + /** + * Execute the new upload endPoint. + * @return {FileModel} + */ + fileUploadMultipart: function () { + var project = this.get("project"), + index = 0, + xhr, + formData, + appDoc, + that = this; + if (project.webServiceManager && this.get("isValid")) { + formData = this.prepareDataToUploadMultipart(this.get("file")); + if (_.isFunction(project.webServiceManager.uploadMultipart)) { + xhr = project.webServiceManager.uploadMultipart(formData, function (err, data) { + if (err && err.code) { + that.set("error", err); + that.trigger("upload_error"); + } else { + //mark as completed the file upload procedure. + appDoc = data[index].appDocUid; + that.set("appDocUid", appDoc); + that.set("completed", true); + that.trigger("upload_complete"); + } + }, this.progressValue()); + this.set("xhr", xhr); + } + } else { + this.set("updateIndex", true); + this.get('parent').set('multiFileCount', this.get('parent').get('multiFileCount') + 1); + } + return this; + }, + /** + * Parse the name to obtain the extension + * @param path + * @returns {*} + */ + parseExtension: function (path) { + var name, + ext, + indexExt = 1, + parseExt = /(?:\.)([0-9a-z]+$)/i; + name = this.parseName(path); + ext = parseExt.exec(name); + return (ext && _.isArray(ext)) ? ext[indexExt] : ""; + }, + /** + * Parse name from a URL dir path + * @param path + * @returns {*} + */ + parseName: function (path) { + var name, + parsePath = /^.*[\\\/]/; + name = path.replace(parsePath, ''); + return name; + }, + /** + * Update the percentage upload + * @returns {Function} + */ + progressValue: function () { + var that = this; + return function (e) { + var max, current, percentage; + if (e.lengthComputable) { + max = e.total; + current = e.loaded; + percentage = (current * 100) / max; + that.set("percentage", percentage); + } + } + }, + /** + * Get Name from multipleFile Model + * @returns {*} + */ + getNameFileParent: function () { + return this.get("parent").get("name"); + }, + /** + * Perform a file extension validation. + * @param file + * @param {String} extensions A bunch of extensions separated by comma. + * @returns {boolean} + * @private + */ + _isFileExtensionValid: function (file, extensions) { + var allowedExtensions = extensions.trim().toLowerCase(), + fileExtension; + + if (allowedExtensions === "" || allowedExtensions === "*") { + return true; + } + + allowedExtensions = allowedExtensions.split(",").map(function (i) { + return i.replace(/\./, "").trim(); + }); + + fileExtension = file.name.split(".").pop().toLowerCase(); + + return allowedExtensions.indexOf(fileExtension) >= 0; + }, + /** + * Returns the amount in bytes of a value in another unit. + * @param {Number} amount + * @param {String} units A string that specifies the input amount is in, it only supports 'MB' and 'KB'. + * @returns {*} + * @private + */ + _getSizeInBytes: function (amount, units) { + switch (units) { + case 'MB': + amount *= 1024; + case 'KB': + amount *= 1024; + break; + default: + throw new Error('_getSizeInBytes(): Invalid \"units\" parameter'); + } + + return amount; + }, + /** + * Verifies if the file accomplish the size limit. + * @param {File} file The file to be verified. + * @param {Number} maxAllowedSize The amount size. + * @param {String} unit The unit the amount is in, at the moment it only supports 'MB' and 'KB'. + * @returns {boolean} + * @private + */ + _isFileSizeValid: function (file, maxAllowedSize, unit) { + var maxAllowedSize = this._getSizeInBytes(maxAllowedSize, unit); + + return maxAllowedSize === 0 || file.size <= maxAllowedSize; + }, + /** + * Convert bytes to other unit rounded to two decimals + * @param qBytes + * @param unit + * @returns {number} + */ + convertTo: function (qBytes, unit) { + var units = ["bytes", "KB", "MB", "GB"], + constant = 1024, + factor = 1, + exponent = 0, + decimals = 2, + result = 0; + if (qBytes && unit) { + exponent = units.indexOf(unit.toUpperCase()); + factor = Math.pow(constant, exponent); + result = Number((qBytes/factor).toFixed(decimals)); + } + return result; + }, + /** + * Parse de Allow Extensions + * @returns {*} + */ + parseAllowExtensions: function () { + var extensions = this.get("extensions").trim(), + allowExtension; + if (extensions) { + extensions = extensions.replace(/\s*\./g, ''); + allowExtension = extensions.split(","); + } + return allowExtension; + }, + /** + * Return a object to render with a url + * @returns {{ext: *, icon: *, name: *, href: *}|*} + */ + getLinkDownload: function () { + var resp = {}, + proj = this.get("project"); + if (proj && proj.webServiceManager && proj.webServiceManager.showDocument) { + resp = proj.webServiceManager.showDocument({ + uid: this.get("appDocUid"), + type: this.get("linkService"), + version: this.get("version") + }); + } + return resp; + }, + /** + * Calls to endpoint of download + * @param version {string} + * @param callback {function} + * @returns {FileModel} + */ + downloadFileVersion: function (version, callback) { + var project = this.get("project"), + webServiceManager = project.webServiceManager, + dataFile = { + docUID: this.get("appDocUid"), + version: version + }; + webServiceManager.downloadFile(dataFile, function (data) { + callback(data); + }); + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.file.FileModel", FileModel); +}()); + +(function () { + var FileView = Backbone.View.extend({ + template: _.template($("#tpl-multiplefile-file").html()), + loaderTemplate: _.template($("#tpl-multiplefile-version-loader").html()), + $hiddens: [], + events: { + "click .pmdynaform-mfile > .pmdynaform-mfile-actions li[data-action=delete] a": "onClickDelete", + "click .pmdynaform-mfile > .pmdynaform-mfile-actions li[data-action=abort] a": "onClickCancelUpload", + "click .pmdynaform-mfile > .pmdynaform-mfile-actions li[data-action=upload] a": "_fireUploadDialog", + "click .pmdynaform-mfile > .pmdynaform-mfile-actions li[data-action=list] a": "_listVersions", + "click .pmdynaform-mfile > .pmdynaform-mfile-actions li[data-action=unlist] a": "_unlistVersions", + "click .pmdynaform-mfile-versions li[data-action=download] a": "_downloadVersion", + "change .pmdynaform-mfile > .pmdynaform-mfile-input": "_uploadFile" + }, + iconsMap: { + "bmp": "file-image-o", + "dib": "file-image-o", + "dng": "file-image-o", + "dt2": "file-image-o", + "emf": "file-image-o", + "gif": "file-image-o", + "ico": "file-image-o", + "icon": "file-image-o", + "jpeg": "file-image-o", + "jpg": "file-image-o", + "pcx": "file-image-o", + "pic": "file-image-o", + "png": "file-image-o", + "psd": "file-image-o", + "raw": "file-image-o", + "tga": "file-image-o", + "thm": "file-image-o", + "tif": "file-image-o", + "tiff": "file-image-o", + "wbmp": "file-image-o", + "wdp": "file-image-o", + "webp": "file-image-o", + "7z": "file-zip-o", + "7zip": "file-zip-o", + "arc": "file-zip-o", + "arj": "file-zip-o", + "bin": "file-zip-o", + "cab": "file-zip-o", + "cbr": "file-zip-o", + "cbz": "file-zip-o", + "cso": "file-zip-o", + "dlc": "file-zip-o", + "gz": "file-zip-o", + "gzip": "file-zip-o", + "jar": "file-zip-o", + "rar": "file-zip-o", + "tar": "file-zip-o", + "tar.gz": "file-zip-o", + "tgz": "file-zip-o", + "zip": "file-zip-o", + "3ga": "file-audio-o", + "amr": "file-audio-o", + "ape": "file-audio-o", + "asf": "file-audio-o", + "asx": "file-audio-o", + "cda": "file-audio-o", + "dvf": "file-audio-o", + "flac": "file-audio-o", + "gp4": "file-audio-o", + "gp5": "file-audio-o", + "gpx": "file-audio-o", + "logic": "file-audio-o", + "m4a": "file-audio-o", + "m4b": "file-audio-o", + "m4p": "file-audio-o", + "midi": "file-audio-o", + "mp3": "file-audio-o", + "ogg": "file-audio-o", + "aac": "file-audio-o", + "pcm": "file-audio-o", + "snd": "file-audio-o", + "uax": "file-audio-o", + "wav": "file-audio-o", + "wma": "file-audio-o", + "wpl": "file-audio-o", + "numbers": "file-excel-o", + "ods": "file-excel-o", + "sdc": "file-excel-o", + "sxc": "file-excel-o", + "xls": "file-excel-o", + "xlsm": "file-excel-o", + "xlsx": "file-excel-o", + "pdf": "file-pdf-o", + "1st": "file-text-o", + "alx": "file-text-o", + "asp": "file-text-o", + "csv": "file-text-o", + "eng": "file-text-o", + "htm": "file-text-o", + "html": "file-text-o", + "log": "file-text-o", + "lrc": "file-text-o", + "lst": "file-text-o", + "nfo": "file-text-o", + "opml": "file-text-o", + "plist": "file-text-o", + "pts": "file-text-o", + "reg": "file-text-o", + "rep": "file-text-o", + "srt": "file-text-o", + "sub": "file-text-o", + "tbl": "file-text-o", + "text": "file-text-o", + "txt": "file-text-o", + "xml": "file-text-o", + "xsd": "file-text-o", + "xsl": "file-text-o", + "xslt": "file-text-o", + "odp": "file-powerpoint-o", + "pot": "file-powerpoint-o", + "potx": "file-powerpoint-o", + "pps": "file-powerpoint-o", + "ppsx": "file-powerpoint-o", + "ppt": "file-powerpoint-o", + "pptm": "file-powerpoint-o", + "pptx": "file-powerpoint-o", + "sdd": "file-powerpoint-o", + "key": "file-powerpoint-o", + "keynote": "file-powerpoint-o", + "xps": "file-powerpoint-o", + "264": "file-video-o", + "3g2": "file-video-o", + "3gp": "file-video-o", + "avi": "file-video-o", + "bik": "file-video-o", + "dash": "file-video-o", + "dat": "file-video-o", + "dvr": "file-video-o", + "flv": "file-video-o", + "h264": "file-video-o", + "m2t": "file-video-o", + "m2ts": "file-video-o", + "m4v": "file-video-o", + "mkv": "file-video-o", + "mod": "file-video-o", + "mov": "file-video-o", + "mp4": "file-video-o", + "mpeg": "file-video-o", + "mpg": "file-video-o", + "mswmm": "file-video-o", + "mts": "file-video-o", + "ogv": "file-video-o", + "prproj": "file-video-o", + "rec": "file-video-o", + "rmvb": "file-video-o", + "swf": "file-video-o", + "tod": "file-video-o", + "tp": "file-video-o", + "ts": "file-video-o", + "vob": "file-video-o", + "webm": "file-video-o", + "wmv": "file-video-o", + "abw": "file-word-o", + "aww": "file-word-o", + "cnt": "file-word-o", + "doc": "file-word-o", + "docm": "file-word-o", + "docx": "file-word-o", + "dot": "file-word-o", + "dotm": "file-word-o", + "dotx": "file-word-o", + "epub": "file-word-o", + "ind": "file-word-o", + "indd": "file-word-o", + "odf": "file-word-o", + "odt": "file-word-o", + "ott": "file-word-o", + "oxps": "file-word-o", + "pages": "file-word-o", + "pmd": "file-word-o", + "pub": "dofile-word-oc", + "pwi": "file-word-o", + "rtf": "file-word-o", + "wpd": "file-word-o", + "wps": "file-word-o", + "wri": "file-word-o" + }, + /** + * Initialize the view. + * @param options + * @returns {FileView} + */ + initialize: function (options) { + this.$hiddens = []; + this._versionable = options.versionable || false; + this._versions = []; + this._initLoading = options.loading; + this.listenTo(this.model, 'change:percentage', this._updatePercentage); + this.listenTo(this.model, 'change:appDocUid', this.createHiddenForProperty); + this._project = this.model.get('project'); + this._parent = this.model.get("parent"); + + if (this._initLoading) { + this.listenTo(this.model, 'upload_complete', this._onComplete); + this.listenTo(this.model, 'upload_error', this.onError); + } + + this._dom = {}; + return this; + }, + /** + * Execute the button Cancel + * @param e + * @returns {FileView} + */ + onClickCancelUpload: function (e) { + var xhr; + e.preventDefault(); + e.stopPropagation(); + + if (this._initLoading) { + xhr = this.model.get("xhr"); + if (xhr && xhr.abort) { + xhr.abort(); + this.onClickDelete(e); + } + } else if (this._xhr) { + this._xhr.abort(); + this._onComplete(); + } + + return this; + }, + /** + * Resets and displays the file uploading progress bar. + * @private + */ + _showProgressBar: function () { + var progressBar, + progressBarContainer; + if (!this._dom.progressBar) { + progressBarContainer = document.createElement('div'); + progressBarContainer.className = "progress"; + + progressBar = document.createElement('div'); + progressBar.className = "progress-bar progress-bar-success"; + + progressBarContainer.appendChild(progressBar); + + this._dom.progressBar = progressBar; + this._dom.progressBarContainer = progressBarContainer; + } + + this._dom.progressBar.textContent = ""; + this._dom.progressBar.style.width = "0%"; + this._dom.$fileInfo.append(this._dom.progressBarContainer); + this._hideButtonsFromActionList('abort'); + this._dom.$fileActions.show(); + }, + /** + * Render only file view + * @returns {FileView} + */ + render: function () { + var mode = this._parent.get("mode"), + filename = this.model.get("file").name, + ext = this.model.parseExtension(filename), + versionList; + + this.setElement(this.template({ + downloadLink: '#', + viewid: this.cid, + filename: filename, + fileversion: '', + versionable: this._versionable, + mode: mode, + iconClass: this._getIconClass(ext), + details: '', + extensions: this._parent.get("extensions") + })); + + versionList = document.createElement('ul'); + versionList.className = "pmdynaform-mfile-versions"; + this.el.appendChild(versionList); + + this._dom.$fileTitle = this.$el.find('> .pmdynaform-mfile .pmdynaform-mfile-title'); + this._dom.$fileName = this.$el.find('> .pmdynaform-mfile .pmdynaform-mfile-name'); + this._dom.$fileVersion = this.$el.find('> .pmdynaform-mfile .pmdynaform-mfile-version'); + this._dom.$fileInfo = this.$el.find('> .pmdynaform-mfile .pmdynaform-mfile-details'); + this._dom.$fileActions = this.$el.find('> .pmdynaform-mfile .pmdynaform-mfile-actions'); + this._dom.$buttonList = this._dom.$fileActions.find('li[data-action=list]'); + this._dom.fileInput = this.$el.find('#pmdynaform-input-' + this.cid); + this._dom.$versionList = $(versionList); + this._dom.$listLoaderMessage = $(this.loaderTemplate()); + + if (mode === 'edit') { + if (this._initLoading) { + this._showProgressBar(); + } else { + this._onComplete(); + } + + if (!this.model.get("isValid")) { + this.showMessageError(); + } + } else { + this._onComplete(); + } + }, + /** + * Set Message Error + */ + showMessageError: function () { + $(this._dom.progressBar).removeClass('progress-bar-success') + .addClass('progress-bar-danger') + .css("width", '100%') + .text(this.model.get("errorSize") ? this.constructMessageError("size") + : this.constructMessageError("type")); + + this._hideButtonsFromActionList('delete'); + this._dom.$fileActions.show(); + + return this; + }, + /** + * Shows the server's error + */ + _showServerError: function (message) { + var parent = this.model.get("parent"); + if (message) { + $(this._dom.progressBar).removeClass('progress-bar-success') + .addClass('progress-bar-danger') + .text(message); + this._hideButtonsFromActionList('delete'); + this._dom.$fileActions.show(); + if (parent.get("parentIsGrid")) { + parent.removeFromGridDetail(this.model); + } + } + + return this; + }, + /** + * Displays a Flash Message in error mode. + * @param message + * @returns {FileView} + * @private + */ + _showFlashErrorMessage: function (message) { + this._project.flashMessage({ + message: message, + duration: 0, + type: 'danger', + emphasisMessage: 'Error:' + }); + + return this; + }, + /** + * Displays a server error + */ + onError: function () { + var response = this.model.get("error"); + if (response) { + this._showServerError(response.message ? response.message : response.error.message); + } + }, + /** + * Destroys model. + */ + destroy: function () { + this.model.destroy(); + }, + /** + * Builds the message error. + * @param value + * @returns {string} + */ + constructMessageError: function (value, file) { + var sizeUnity = this._parent.get("sizeUnity"), + sizeAllow = this._parent.get("size") + sizeUnity, + typeAllow = this._parent.get("extensions"), + message = ""; + + switch (value) { + case "size": + message = (file ? "\"" + file.name + "\"" : 'File') + " size exceeds the allowable limit of {" + sizeAllow + "}"; + break; + case "type": + message = "Invalid file format " + (file ? 'for "' + file.name + '"': '') + ", please upload a file with one of the following formats {" + typeAllow + "}"; + break; + } + return message; + }, + /** + * update the percentage of progressbar + * @returns {FileView} + */ + _updatePercentage: function (model, value) { + value = Math.floor(value); + this._dom.progressBar.textContent = this._dom.progressBar.style.width = value + '%'; + + return this; + }, + /** + * Sets the view in its final mode. + * @returns {FileView} + * @private + */ + _onComplete: function () { + var that = this, + file = this.model.get("file"); + + setTimeout(function () { + var buttons = ['download'], + mode = that.model.get('parent').get("mode"); + + that._dom.fileInput.val(""); + that._initLoading = false; + that._dom.$fileName.text(file.name); + that._dom.$fileTitle.attr("title", file.name); + // TODO: Set the file details in the format "Created by John Doe on 2017-03-03" + that._dom.$fileInfo.empty().text(""); + that._dom.$fileActions.find('[data-action=download] a').attr('href', that.model.getLinkDownload()); + + if (mode === 'edit') { + buttons.push('delete'); + } + + if (that._versionable) { + buttons.push('list', 'unlist'); + + if (mode === 'edit') { + buttons.push('upload'); + } + } + + that._hideButtonsFromActionList(buttons); + that._dom.$fileActions.show(); + that._renderVersions(that._versions); + }, 300); + + return this; + }, + + createHiddenForProperty: function () { + var parentView = this.model.get('parent').get('view'); + if (parentView) { + parentView.clearHiddenByModel(); + parentView.createAllHiddens('add'); + } + }, + /** + * Returns the icon class for the file + * @param ext + * @returns {*|string} + * @private + */ + _getIconClass: function (ext) { + return this.iconsMap[ext] || "file-o"; + }, + /** + * Hide all action buttons, except by the especified ones. + * @param [exceptions] An array of strings with the exceptions. + * @returns {FileView} + * @private + */ + _hideButtonsFromActionList: function (exceptions) { + var exceptionSelector = [], + itemWidth = 29; // TODO: find a way to find this width dinamically + + if (typeof exceptions === 'string') { + exceptions = [exceptions]; + } + + if (_.isArray(exceptions)) { + exceptions.forEach(function (item) { + exceptionSelector.push('[data-action="' + item + '"]'); + }); + exceptionSelector = exceptionSelector.join(','); + } else { + exceptionSelector = null; + } + + if (exceptionSelector) { + this._dom.$fileActions.find('li').css("display", "").not(exceptionSelector).hide(); + } else { + this._dom.$fileActions.find('li').hide(); + } + + this._dom.$fileTitle.css('width', 'calc(100% - ' + + (this._dom.$fileActions.find(exceptionSelector || "li").size() * itemWidth) + 'px)'); + + return this; + }, + /** + * Render the supplied version in list. + * @param version + * + * @returns {FileView} + * @private + */ + _renderVersionInList: function (version) { + var versionItem = $(this.template({ + downloadLink: "#", + viewid: this.cid + "_v" + version.app_doc_version, + filename: version.app_doc_filename, + fileversion: version.app_doc_version, + versionable: false, + mode: "view", + details: "Uploaded by " + version.app_doc_create_user + " on " + version.app_doc_create_date, + iconClass: this._getIconClass(this.model.parseExtension(version.app_doc_filename)) + })); + + this._dom.$listLoaderMessage.remove(); + + versionItem.find('a').attr("data-version-number", version.app_doc_version); + versionItem.find('a').attr("data-file-name", version.app_doc_filename); + versionItem.find('.pmdynaform-mfile-action-item').not('[data-action=download]').remove() + .end().end().find('.pmdynaform-mfile-actions').show(); + + this._dom.$versionList.append(versionItem); + + return this; + }, + /** + * Renders the supplied versions on the versions list. + * @param {Array} versions + * @private + */ + _renderVersions: function (versions) { + var that = this; + + if (versions.length) { + this._dom.$versionList.empty(); + + versions.forEach(function (version) { + that._renderVersionInList(version); + }); + + } else { + this._dom.$listLoaderMessage.text("0 items"); + } + }, + /** + * Collapse the versions list. + * @param {Event} e + * @private + */ + _unlistVersions: function (e) { + e.preventDefault(); + this._dom.$versionList.stop().slideUp(); + this._dom.$buttonList.attr("data-action", "list").find('a').get(0).className = 'fa fa-chevron-circle-down'; + }, + /** + * Displays the versions list. + * @param {Event} e + * @returns {FileView} + * @private + */ + _listVersions: function (e) { + var appDocUID = this.model.get("appDocUid"), + that = this; + + e.preventDefault(); + + this._dom.$versionList.empty().append(this._dom.$listLoaderMessage.text("loading...")).stop().slideDown(); + this._dom.$buttonList.attr("data-action", "unlist").find('a').get(0).className = 'fa fa-chevron-circle-up'; + + this._project.webServiceManager.getFileVersions(appDocUID, function (err, resp) { + if (err) { + that._showFlashErrorMessage(err.status); + } else { + that._versions = resp.data.sort(function (a, b) { + return parseInt(a.app_doc_version, 10) < parseInt(b.app_doc_version, 10) ? 1 : -1; + }); + + that._renderVersions(that._versions); + } + }); + + return this; + }, + /** + * Start the upload process. + * @param {Event} e + * @private + */ + _uploadFile: function (e) { + var files = e.target.files, + index = 0, + that = this, + errorMessage, + file, + data, + fieldName, + formData = new FormData(); + + e.preventDefault(); + + if (files.length === 1) { + file = files.item(0); + + if (!this.model._isFileExtensionValid(file, this._parent.get("extensions"))) { + errorMessage = this.constructMessageError('type', file); + } else if (!this.model._isFileSizeValid(file, this._parent.get("size"), this._parent.get("sizeUnity"))) { + errorMessage = this.constructMessageError('size', file); + } + + if (errorMessage) { + return this._showFlashErrorMessage(errorMessage); + } + formData.append("form[]", file); + fieldName = this.model.get('parent').get('group') === "form" ? this.model.get('parent').get('var_name') : this.model.get('parent').get('id'); + data = { + name: file.name, + fieldName: fieldName, + docUid: this.model.get("parent").get("inp_doc_uid"), + appDocType: "INPUT", + appDocUid: this.model.get("appDocUid"), + formData: formData + }; + this._dom.$fileName.text(data.name); + this._showProgressBar(); + + this._xhr = this._project.webServiceManager.uploadMultipart([data], function (err, data) { + var newVersion, + oldAppDocUid; + + if (err) { + that._showFlashErrorMessage(err.message); + return that._onComplete(); + } + + newVersion = { + app_doc_uid: data[index].appDocUid, + app_doc_filename: data[index].appDocFilename, + doc_uid: data[index].appDocUid, + app_doc_version: data[index].docVersion, + app_doc_create_date: data[index].appDocCreateDate, + app_doc_create_user: data[index].appDocCreateUser, + app_doc_type: data[index].appDocType, + app_doc_index: data[index].appDocIndex + }; + oldAppDocUid = that.model.get("appDocUid"); + + that._xhr = null; + that._versions.unshift(newVersion); + + that.model.set({ + file: { + name: newVersion.app_doc_filename + }, + version: newVersion.app_doc_version + }).set("appDocUid", newVersion.app_doc_uid); + //The appDocUid update is not being performed in the first call due it is necessary to ensure + // it is called after the name and version update, in order to update the hidden fields. + + if (oldAppDocUid === newVersion.app_doc_uid) { + that.createHiddenForProperty(); + } + that._onComplete(); + }, function (e) { + if (e.lengthComputable) { + that._updatePercentage(null, (e.loaded * 100) / e.total); + } + }); + } else if (files.length > 1) { + this._showFlashErrorMessage("Only one version per file can be uploaded."); + } + + }, + /** + * Get data and create link of download + * @param e + * @private + */ + _downloadVersion: function (e) { + var that = this, + item = e.target, + version = item.getAttribute("data-version-number"), + nameFile = item.getAttribute("data-file-name"), + url; + this.model.downloadFileVersion(version, function (data) { + if (window.navigator && window.navigator.msSaveOrOpenBlob) { + window.navigator.msSaveOrOpenBlob(data, nameFile); + } else { + url = URL.createObjectURL(data); + that._executeFakeLink(url, nameFile); + window.URL.revokeObjectURL(url); + } + }); + e.preventDefault(); + }, + /** + * Execute download + * @param url {string} + * @param nameFile {string} + * @returns {FileView} + * @private + */ + _executeFakeLink: function (url, nameFile) { + var fakeLink = $("", { + "id": "fakeDownloadLink", + "href": url, + "download": nameFile + }).hide(); + fakeLink.appendTo("body"); + fakeLink[0].click(); + fakeLink.remove(); + return this; + }, + _fireUploadDialog: function (e) { + e.preventDefault(); + this._dom.fileInput.click(); + }, + /** + * Delete a file handler + * @returns {FileView} + */ + onClickDelete: function (e) { + var parentView = this.model.get('parent').get('view'); + if (this.model.get("parent").get("mode") === "edit" && parentView) { + this.model.destroy(); + this.remove(); + if (this.model.get('parent').get('group') === 'grid') { + this.model.get('parent').removeFromGridDetail(this.model); + } + this.model.get('parent').resetInputFile(); + } + + e.preventDefault(); + + return this; + } + }); + + PMDynaform.extendNamespace("PMDynaform.file.FileView", FileView); +}()); + +(function () { + var FileCollection = Backbone.Collection.extend({ + model: PMDynaform.file.FileModel, + /** + * Get the values from all Files + * @returns {Array} + */ + getValues: function () { + var index, + resp = []; + for (index = 0; index < this.models.length; index += 1) { + if (_.isFunction(this.models[index].getValue)) { + resp.push(this.models[index].getValue()); + } + } + return resp; + }, + /** + * Get the data{appDocuid, name, version} form all files + * @returns {Array} + */ + getData: function () { + var index, + resp = []; + for (index = 0; index < this.models.length; index += 1) { + if (_.isFunction(this.models[index].getData)) { + resp.push(this.models[index].getData()); + } + } + return resp; + }, + /** + * Get the names from files + * @returns {Array} + */ + getNames: function () { + var index, + resp = []; + for (index = 0; index < this.models.length; index += 1) { + if (_.isFunction(this.models[index].getName)) { + resp.push(this.models[index].getName()); + } + } + return resp; + }, + /** + * Validate the file + * @returns {Array} + */ + validate: function () { + var index, + resp = false; + for (index = 0; index < this.models.length; index += 1) { + if (this.models[index].get("isValid")) { + resp = true; + break; + } + } + return resp; + }, + /** + * Update index valid in all files + * @returns {Array} + */ + updateIndex: function () { + var index, + indexNew = 0; + for (index = 0; index < this.models.length; index += 1) { + if (this.models[index].get("isValid")) { + this.models[index].set("index", indexNew); + indexNew += 1; + } + } + return this; + }, + /** + * Delete files in a field + * @returns {FileCollection} + */ + deleteFiles: function () { + var index = 0; + while (this.models.length > 0) { + this.models[index].destroy(); + } + return this; + }, + /** + * Gets all files the the completed attribute is "false" + */ + getFilesNotUploaded: function() { + var index, + resp = false, + unCompletedFiles= []; + for (index = 0; index < this.models.length; index += 1) { + if (!this.models[index].get("completed") && !this.models[index].get("error")) { + unCompletedFiles.push({ "name": this.models[index].attributes.file.name}); + } + } + return unCompletedFiles; + } + }); + + PMDynaform.extendNamespace("PMDynaform.file.FileCollection", FileCollection); +}()); + +(function () { + var ProgressBar = Backbone.View.extend({ + template: _.template($("#tpl-progressbar").html()), + percentage: 0, + message: "", + title: "", + striped: false, + animate: false, + type: "default", + types: ["default", "info", "success", "warning", "danger", "file"], + col: 12, + initialize: function (options) { + this.percentage = options.percentage ? options.percentage : 0; + this.title = options.title ? options.title : ""; + if (options.type && _.indexOf(this.types, options.type) !== -1) { + this.type = options.type; + } + this.striped = options.striped ? options.striped : false; + this.animate = options.animate ? options.animate : false; + this.message = options.message ? options.message : ""; + this.col = options.col ? options.col : 12; + return this; + }, + /** + * Render the view of progressBar + */ + render: function () { + var obj = { + value: 0, + title: this.title, + col: this.col, + type: this.type, + striped: this.striped, + animate: this.animate + }; + this.setElement(this.template(obj)); + this.setPercentage(this.percentage); + this.setMessage(this.message); + this.$el.find(".progressbar-title").tooltip({ + title: this.title + }); + return this; + }, + /** + * Set the percentage to progressbar + * @param percentage + */ + setPercentage: function (percentage) { + var bar = this.$el.find(".progress-bar"); + bar.width(percentage + "%"); + return this; + }, + /** + * Set the type[color] to progresBar + * @param type + */ + setType: function (type) { + var bar = this.$el.find(".progress-bar"); + bar.removeClass("progress-bar-" + this.type); + if (_.indexOf(this.types, type) !== -1) { + bar.addClass("progress-bar-" + type); + this.type = type; + } + return this; + }, + /** + * Set the message in the progress bar + * @param message + * @returns {ProgressBar} + */ + setMessage: function (message) { + var bar = this.$el.find(".progress-bar"); + bar.html(message); + return this; + }, + /** + * Disable the animation striped in the progressbar + * @param message + * @returns {ProgressBar} + */ + disableAnimation: function (message) { + var bar = this.$el.find(".progress-bar"); + bar.removeClass("active"); + return this; + }, + /** + * Set the progress bar striped for animation + * @param value + * @returns {ProgressBar} + */ + setStriped: function (value) { + var bar = this.$el.find(".progress-bar"); + if (_.isBoolean(value)) { + this.striped = value; + if (value) { + bar.addClass("progress-bar-striped"); + } else { + bar.removeClass("progress-bar-striped"); + } + } + return this; + } + }); + PMDynaform.extendNamespace("PMDynaform.ui.ProgressBar", ProgressBar); +}()); +(function () { + /** + * UploadModalModel class Inherited from MultipleFileModel + * + */ + var UploadModalModel = PMDynaform.file.MultipleFileModel.extend({ + defaults: { + parent: null + }, + /** + * Adds the file model to collection to drive all files in a collection + * validates the size too + * @param file + * @param mode + * @param parentView + * @returns {*} + */ + addFileModel: function (file) { + var parentFile = this.get('parent'), + files = parentFile.get('fileCollection'), + fileSize, + fileExtension, + fileModel; + + fileModel = new PMDynaform.file.FileModel({ + file: file, + mode: "edit", + parent: parentFile, + project: parentFile.get('project'), + form: parentFile.get('form'), + size: parentFile.get('size'), + sizeUnity: parentFile.get('sizeUnity'), + extensions: parentFile.get("extensions") + }); + + fileSize = fileModel._isFileSizeValid(file, parentFile.get("size"), parentFile.get("sizeUnity")); + fileExtension = fileModel._isFileExtensionValid(file, parentFile.get("extensions")); + + if (!fileSize) { + fileModel.set("isValid", fileSize); + fileModel.set("errorSize", true); + } + if (!fileExtension) { + fileModel.set("isValid", fileExtension); + fileModel.set("errorType", true); + } + if (fileModel.get("isValid")) { + fileModel = files.add(fileModel); + files.updateIndex(); + } + return fileModel; + } + + }); + PMDynaform.extendNamespace("PMDynaform.file.UploadModalModel", UploadModalModel); +}()); +(function () { + var UploadModal = Backbone.View.extend({ + timeHide: 1000, + template: _.template($("#tpl-upload-modal").html()), + modal: null, + $hiddenFile: null, + labelButton: "Choose Files".translate(), + labelClose: "Close".translate(), + $hiddens: [], + initialize: function () { + //TODO: no need params. + }, + /** + * Render the modal from a multiple file in a grid field, receive a backbone collection + * @param collection + * @returns {UploadModal} + */ + renderForm: function (collection) { + var that = this, + box, + i, + model, + mode = "edit", + ext = "", + view, + parent = this.model.get("parent"); + + if ($('#modalUpload').length) { + $('#modalUpload').remove(); + } + mode = parent ? parent.get("mode") : mode; + ext = parent ? parent.get("extensions") : ext; + this.modal = $(this.template({ + mode: mode, + labelButton: this.labelButton, + labelClose: this.labelClose, + extensions: ext + })); + $('body').append(this.modal); + + this.show(); + this.eventsBinding(); + this.modal.find('.btn-uploadfile').on('click', function (e) { + that.onClickUploadButton(e); + }); + box = this.modal.find(".pmdynaform-multiplefile-box"); + if (collection instanceof Backbone.Collection) { + for (i = 0; i < collection.length; i += 1) { + model = collection.at(i); + if (!model.get("error")) { + view = new PMDynaform.file.FileView({ + model: model, + versionable: this.model.get("parent").get("enableVersioning") + }); + view.render(); + box.append(view.$el); + } + } + } + this.removeModal(); + return this; + }, + + /** + * show modal form + */ + show: function () { + var modalUpload = $('#modalUpload'); + modalUpload.modal({backdrop: 'static', keyboard: false}, 'show'); + return this; + }, + /** + * Listen event hidden and remove modal if exist + * @returns {UploadModal} + */ + removeModal: function () { + var modalUpload = $('#modalUpload'); + modalUpload.on('hidden.bs.modal', function () { + if (modalUpload.length) { + modalUpload.remove(); + } + }); + return this; + }, + /** + * upload button handler + * @param event + */ + onClickUploadButton: function (event) { + event.preventDefault(); + event.stopPropagation(); + if (this.model.get("parent") && this.model.get("parent").get('mode') === "edit") { + this.openFileWizardWeb(); + } + }, + /*** + * Open Wizard to select upload files + * @param event + */ + openFileWizardWeb: function () { + $('.pm-modal-upload').find("input:file").trigger("click"); + return this; + }, + + /** + * change files handler + * @param event + * @returns {boolean} + */ + changeFileControl: function (event) { + var files, + parent = this.model.get("parent"); + event.preventDefault(); + event.stopPropagation(); + files = event.target.files; + this.processFiles(files); + event.target.value = ""; + parent.get('view').populateItemsPrintMode(parent.getKeyLabel()); + return false; + }, + /** + * process al files to upload to create an instance of a file model an view + * at last render the upload file + * @param files + * @returns {UploadModal} + */ + processFiles: function (files) { + var index = 0, + fileView, + fileModel, + box = this.modal.find(".pmdynaform-multiplefile-box"); + if (files.length) { + for (index = 0; index < files.length; index += 1) { + fileModel = this.model.addFileModel(files[index], "edit", this); + + fileView = new PMDynaform.file.FileView({ + model: fileModel, + loading: true, + versionable: this.model.get("parent").get("enableVersioning") + }); + fileModel.set('fromWizard', true); + fileView.render(); + box.append(fileView.$el); + fileModel.fileUploadMultipart(); + + fileModel.set('fromWizard', false); + this.model.get('parent').updateGridDetail(fileModel); + } + } + return this; + }, + /** + * Reset the input file html tag for reset properties + */ + resetInputFile: function () { + var parent = this.model.get("parent"), + nInput = $("", { + type: "file", + style: "display:none", + multiple: "multiple", + accept: parent.get("extensions") + }); + this.$hiddenFile.before(nInput).remove(); + this.$hiddenFile = nInput; + this.eventsBinding(); + parent.get('view').populateItemsPrintMode(parent.getKeyLabel()); + return this; + }, + eventsBinding: function () { + var that = this; + this.$hiddenFile = this.modal.find("input:file"); + this.$hiddenFile.on('change', function (e) { + that.changeFileControl(e); + }); + } + }); + PMDynaform.extendNamespace("PMDynaform.file.UploadModalView", UploadModal); +}()); + +(function() { + var Spinner = Backbone.View.extend({ + template: _.template($("#tpl-spinner").html()), + initialize: function(options) { + return this; + }, + /** + * Render the view of progressBar + * @chainable + */ + render: function() { + var obj = { + col: this.col + }; + this.setElement(this.template(obj)); + return this; + }, + /** + * Hides the progress html item + * @chainable + */ + hide: function() { + var progress = this.$el.find(".pm-field-loading"); + progress.addClass('hidden'); + return this; + }, + /** + * Shows the progress bar html item + * @chainable + */ + show: function() { + var progress = this.$el.find(".pm-field-loading"); + if(progress.hasClass('hidden')) { + progress.removeClass('hidden'); + } + return this; + } + + }); + PMDynaform.extendNamespace("PMDynaform.ui.Spinner", Spinner); +})(); + diff --git a/workflow/public_html/lib/pmdynaform/build/pmdynaform.html b/workflow/public_html/lib/pmdynaform/build/pmdynaform.html new file mode 100644 index 000000000..82f1e6af0 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/build/pmdynaform.html @@ -0,0 +1,2025 @@ + + + + PMDynaform + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {javascript} + + diff --git a/workflow/public_html/lib/pmdynaform/libs/animate-css/animate.css b/workflow/public_html/lib/pmdynaform/libs/animate-css/animate.css new file mode 100644 index 000000000..dac48f174 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/libs/animate-css/animate.css @@ -0,0 +1,3623 @@ +@charset "UTF-8"; + +/*! + * animate.css -http://daneden.me/animate + * Version - 3.7.0 + * Licensed under the MIT license - http://opensource.org/licenses/MIT + * + * Copyright (c) 2018 Daniel Eden + */ + +@-webkit-keyframes bounce { + from, + 20%, + 53%, + 80%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 40%, + 43% { + -webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + -webkit-transform: translate3d(0, -30px, 0); + transform: translate3d(0, -30px, 0); + } + + 70% { + -webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + -webkit-transform: translate3d(0, -15px, 0); + transform: translate3d(0, -15px, 0); + } + + 90% { + -webkit-transform: translate3d(0, -4px, 0); + transform: translate3d(0, -4px, 0); + } +} + +@keyframes bounce { + from, + 20%, + 53%, + 80%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 40%, + 43% { + -webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + -webkit-transform: translate3d(0, -30px, 0); + transform: translate3d(0, -30px, 0); + } + + 70% { + -webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06); + -webkit-transform: translate3d(0, -15px, 0); + transform: translate3d(0, -15px, 0); + } + + 90% { + -webkit-transform: translate3d(0, -4px, 0); + transform: translate3d(0, -4px, 0); + } +} + +.bounce { + -webkit-animation-name: bounce; + animation-name: bounce; + -webkit-transform-origin: center bottom; + transform-origin: center bottom; +} + +@-webkit-keyframes flash { + from, + 50%, + to { + opacity: 1; + } + + 25%, + 75% { + opacity: 0; + } +} + +@keyframes flash { + from, + 50%, + to { + opacity: 1; + } + + 25%, + 75% { + opacity: 0; + } +} + +.flash { + -webkit-animation-name: flash; + animation-name: flash; +} + +/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ + +@-webkit-keyframes pulse { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 50% { + -webkit-transform: scale3d(1.05, 1.05, 1.05); + transform: scale3d(1.05, 1.05, 1.05); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +@keyframes pulse { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 50% { + -webkit-transform: scale3d(1.05, 1.05, 1.05); + transform: scale3d(1.05, 1.05, 1.05); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +.pulse { + -webkit-animation-name: pulse; + animation-name: pulse; +} + +@-webkit-keyframes rubberBand { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 30% { + -webkit-transform: scale3d(1.25, 0.75, 1); + transform: scale3d(1.25, 0.75, 1); + } + + 40% { + -webkit-transform: scale3d(0.75, 1.25, 1); + transform: scale3d(0.75, 1.25, 1); + } + + 50% { + -webkit-transform: scale3d(1.15, 0.85, 1); + transform: scale3d(1.15, 0.85, 1); + } + + 65% { + -webkit-transform: scale3d(0.95, 1.05, 1); + transform: scale3d(0.95, 1.05, 1); + } + + 75% { + -webkit-transform: scale3d(1.05, 0.95, 1); + transform: scale3d(1.05, 0.95, 1); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +@keyframes rubberBand { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 30% { + -webkit-transform: scale3d(1.25, 0.75, 1); + transform: scale3d(1.25, 0.75, 1); + } + + 40% { + -webkit-transform: scale3d(0.75, 1.25, 1); + transform: scale3d(0.75, 1.25, 1); + } + + 50% { + -webkit-transform: scale3d(1.15, 0.85, 1); + transform: scale3d(1.15, 0.85, 1); + } + + 65% { + -webkit-transform: scale3d(0.95, 1.05, 1); + transform: scale3d(0.95, 1.05, 1); + } + + 75% { + -webkit-transform: scale3d(1.05, 0.95, 1); + transform: scale3d(1.05, 0.95, 1); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +.rubberBand { + -webkit-animation-name: rubberBand; + animation-name: rubberBand; +} + +@-webkit-keyframes shake { + from, + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 10%, + 30%, + 50%, + 70%, + 90% { + -webkit-transform: translate3d(-10px, 0, 0); + transform: translate3d(-10px, 0, 0); + } + + 20%, + 40%, + 60%, + 80% { + -webkit-transform: translate3d(10px, 0, 0); + transform: translate3d(10px, 0, 0); + } +} + +@keyframes shake { + from, + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 10%, + 30%, + 50%, + 70%, + 90% { + -webkit-transform: translate3d(-10px, 0, 0); + transform: translate3d(-10px, 0, 0); + } + + 20%, + 40%, + 60%, + 80% { + -webkit-transform: translate3d(10px, 0, 0); + transform: translate3d(10px, 0, 0); + } +} + +.shake { + -webkit-animation-name: shake; + animation-name: shake; +} + +@-webkit-keyframes headShake { + 0% { + -webkit-transform: translateX(0); + transform: translateX(0); + } + + 6.5% { + -webkit-transform: translateX(-6px) rotateY(-9deg); + transform: translateX(-6px) rotateY(-9deg); + } + + 18.5% { + -webkit-transform: translateX(5px) rotateY(7deg); + transform: translateX(5px) rotateY(7deg); + } + + 31.5% { + -webkit-transform: translateX(-3px) rotateY(-5deg); + transform: translateX(-3px) rotateY(-5deg); + } + + 43.5% { + -webkit-transform: translateX(2px) rotateY(3deg); + transform: translateX(2px) rotateY(3deg); + } + + 50% { + -webkit-transform: translateX(0); + transform: translateX(0); + } +} + +@keyframes headShake { + 0% { + -webkit-transform: translateX(0); + transform: translateX(0); + } + + 6.5% { + -webkit-transform: translateX(-6px) rotateY(-9deg); + transform: translateX(-6px) rotateY(-9deg); + } + + 18.5% { + -webkit-transform: translateX(5px) rotateY(7deg); + transform: translateX(5px) rotateY(7deg); + } + + 31.5% { + -webkit-transform: translateX(-3px) rotateY(-5deg); + transform: translateX(-3px) rotateY(-5deg); + } + + 43.5% { + -webkit-transform: translateX(2px) rotateY(3deg); + transform: translateX(2px) rotateY(3deg); + } + + 50% { + -webkit-transform: translateX(0); + transform: translateX(0); + } +} + +.headShake { + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + -webkit-animation-name: headShake; + animation-name: headShake; +} + +@-webkit-keyframes swing { + 20% { + -webkit-transform: rotate3d(0, 0, 1, 15deg); + transform: rotate3d(0, 0, 1, 15deg); + } + + 40% { + -webkit-transform: rotate3d(0, 0, 1, -10deg); + transform: rotate3d(0, 0, 1, -10deg); + } + + 60% { + -webkit-transform: rotate3d(0, 0, 1, 5deg); + transform: rotate3d(0, 0, 1, 5deg); + } + + 80% { + -webkit-transform: rotate3d(0, 0, 1, -5deg); + transform: rotate3d(0, 0, 1, -5deg); + } + + to { + -webkit-transform: rotate3d(0, 0, 1, 0deg); + transform: rotate3d(0, 0, 1, 0deg); + } +} + +@keyframes swing { + 20% { + -webkit-transform: rotate3d(0, 0, 1, 15deg); + transform: rotate3d(0, 0, 1, 15deg); + } + + 40% { + -webkit-transform: rotate3d(0, 0, 1, -10deg); + transform: rotate3d(0, 0, 1, -10deg); + } + + 60% { + -webkit-transform: rotate3d(0, 0, 1, 5deg); + transform: rotate3d(0, 0, 1, 5deg); + } + + 80% { + -webkit-transform: rotate3d(0, 0, 1, -5deg); + transform: rotate3d(0, 0, 1, -5deg); + } + + to { + -webkit-transform: rotate3d(0, 0, 1, 0deg); + transform: rotate3d(0, 0, 1, 0deg); + } +} + +.swing { + -webkit-transform-origin: top center; + transform-origin: top center; + -webkit-animation-name: swing; + animation-name: swing; +} + +@-webkit-keyframes tada { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 10%, + 20% { + -webkit-transform: scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg); + transform: scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg); + } + + 30%, + 50%, + 70%, + 90% { + -webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); + transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); + } + + 40%, + 60%, + 80% { + -webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); + transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +@keyframes tada { + from { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } + + 10%, + 20% { + -webkit-transform: scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg); + transform: scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg); + } + + 30%, + 50%, + 70%, + 90% { + -webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); + transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); + } + + 40%, + 60%, + 80% { + -webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); + transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); + } + + to { + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +.tada { + -webkit-animation-name: tada; + animation-name: tada; +} + +/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ + +@-webkit-keyframes wobble { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 15% { + -webkit-transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); + transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); + } + + 30% { + -webkit-transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); + transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); + } + + 45% { + -webkit-transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); + transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); + } + + 60% { + -webkit-transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); + transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); + } + + 75% { + -webkit-transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); + transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes wobble { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 15% { + -webkit-transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); + transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); + } + + 30% { + -webkit-transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); + transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); + } + + 45% { + -webkit-transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); + transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); + } + + 60% { + -webkit-transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); + transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); + } + + 75% { + -webkit-transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); + transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.wobble { + -webkit-animation-name: wobble; + animation-name: wobble; +} + +@-webkit-keyframes jello { + from, + 11.1%, + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 22.2% { + -webkit-transform: skewX(-12.5deg) skewY(-12.5deg); + transform: skewX(-12.5deg) skewY(-12.5deg); + } + + 33.3% { + -webkit-transform: skewX(6.25deg) skewY(6.25deg); + transform: skewX(6.25deg) skewY(6.25deg); + } + + 44.4% { + -webkit-transform: skewX(-3.125deg) skewY(-3.125deg); + transform: skewX(-3.125deg) skewY(-3.125deg); + } + + 55.5% { + -webkit-transform: skewX(1.5625deg) skewY(1.5625deg); + transform: skewX(1.5625deg) skewY(1.5625deg); + } + + 66.6% { + -webkit-transform: skewX(-0.78125deg) skewY(-0.78125deg); + transform: skewX(-0.78125deg) skewY(-0.78125deg); + } + + 77.7% { + -webkit-transform: skewX(0.390625deg) skewY(0.390625deg); + transform: skewX(0.390625deg) skewY(0.390625deg); + } + + 88.8% { + -webkit-transform: skewX(-0.1953125deg) skewY(-0.1953125deg); + transform: skewX(-0.1953125deg) skewY(-0.1953125deg); + } +} + +@keyframes jello { + from, + 11.1%, + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + 22.2% { + -webkit-transform: skewX(-12.5deg) skewY(-12.5deg); + transform: skewX(-12.5deg) skewY(-12.5deg); + } + + 33.3% { + -webkit-transform: skewX(6.25deg) skewY(6.25deg); + transform: skewX(6.25deg) skewY(6.25deg); + } + + 44.4% { + -webkit-transform: skewX(-3.125deg) skewY(-3.125deg); + transform: skewX(-3.125deg) skewY(-3.125deg); + } + + 55.5% { + -webkit-transform: skewX(1.5625deg) skewY(1.5625deg); + transform: skewX(1.5625deg) skewY(1.5625deg); + } + + 66.6% { + -webkit-transform: skewX(-0.78125deg) skewY(-0.78125deg); + transform: skewX(-0.78125deg) skewY(-0.78125deg); + } + + 77.7% { + -webkit-transform: skewX(0.390625deg) skewY(0.390625deg); + transform: skewX(0.390625deg) skewY(0.390625deg); + } + + 88.8% { + -webkit-transform: skewX(-0.1953125deg) skewY(-0.1953125deg); + transform: skewX(-0.1953125deg) skewY(-0.1953125deg); + } +} + +.jello { + -webkit-animation-name: jello; + animation-name: jello; + -webkit-transform-origin: center; + transform-origin: center; +} + +@-webkit-keyframes heartBeat { + 0% { + -webkit-transform: scale(1); + transform: scale(1); + } + + 14% { + -webkit-transform: scale(1.3); + transform: scale(1.3); + } + + 28% { + -webkit-transform: scale(1); + transform: scale(1); + } + + 42% { + -webkit-transform: scale(1.3); + transform: scale(1.3); + } + + 70% { + -webkit-transform: scale(1); + transform: scale(1); + } +} + +@keyframes heartBeat { + 0% { + -webkit-transform: scale(1); + transform: scale(1); + } + + 14% { + -webkit-transform: scale(1.3); + transform: scale(1.3); + } + + 28% { + -webkit-transform: scale(1); + transform: scale(1); + } + + 42% { + -webkit-transform: scale(1.3); + transform: scale(1.3); + } + + 70% { + -webkit-transform: scale(1); + transform: scale(1); + } +} + +.heartBeat { + -webkit-animation-name: heartBeat; + animation-name: heartBeat; + -webkit-animation-duration: 1.3s; + animation-duration: 1.3s; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; +} + +@-webkit-keyframes bounceIn { + from, + 20%, + 40%, + 60%, + 80%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + 20% { + -webkit-transform: scale3d(1.1, 1.1, 1.1); + transform: scale3d(1.1, 1.1, 1.1); + } + + 40% { + -webkit-transform: scale3d(0.9, 0.9, 0.9); + transform: scale3d(0.9, 0.9, 0.9); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(1.03, 1.03, 1.03); + transform: scale3d(1.03, 1.03, 1.03); + } + + 80% { + -webkit-transform: scale3d(0.97, 0.97, 0.97); + transform: scale3d(0.97, 0.97, 0.97); + } + + to { + opacity: 1; + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +@keyframes bounceIn { + from, + 20%, + 40%, + 60%, + 80%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + 20% { + -webkit-transform: scale3d(1.1, 1.1, 1.1); + transform: scale3d(1.1, 1.1, 1.1); + } + + 40% { + -webkit-transform: scale3d(0.9, 0.9, 0.9); + transform: scale3d(0.9, 0.9, 0.9); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(1.03, 1.03, 1.03); + transform: scale3d(1.03, 1.03, 1.03); + } + + 80% { + -webkit-transform: scale3d(0.97, 0.97, 0.97); + transform: scale3d(0.97, 0.97, 0.97); + } + + to { + opacity: 1; + -webkit-transform: scale3d(1, 1, 1); + transform: scale3d(1, 1, 1); + } +} + +.bounceIn { + -webkit-animation-duration: 0.75s; + animation-duration: 0.75s; + -webkit-animation-name: bounceIn; + animation-name: bounceIn; +} + +@-webkit-keyframes bounceInDown { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: translate3d(0, -3000px, 0); + transform: translate3d(0, -3000px, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(0, 25px, 0); + transform: translate3d(0, 25px, 0); + } + + 75% { + -webkit-transform: translate3d(0, -10px, 0); + transform: translate3d(0, -10px, 0); + } + + 90% { + -webkit-transform: translate3d(0, 5px, 0); + transform: translate3d(0, 5px, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes bounceInDown { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: translate3d(0, -3000px, 0); + transform: translate3d(0, -3000px, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(0, 25px, 0); + transform: translate3d(0, 25px, 0); + } + + 75% { + -webkit-transform: translate3d(0, -10px, 0); + transform: translate3d(0, -10px, 0); + } + + 90% { + -webkit-transform: translate3d(0, 5px, 0); + transform: translate3d(0, 5px, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.bounceInDown { + -webkit-animation-name: bounceInDown; + animation-name: bounceInDown; +} + +@-webkit-keyframes bounceInLeft { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: translate3d(-3000px, 0, 0); + transform: translate3d(-3000px, 0, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(25px, 0, 0); + transform: translate3d(25px, 0, 0); + } + + 75% { + -webkit-transform: translate3d(-10px, 0, 0); + transform: translate3d(-10px, 0, 0); + } + + 90% { + -webkit-transform: translate3d(5px, 0, 0); + transform: translate3d(5px, 0, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes bounceInLeft { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + 0% { + opacity: 0; + -webkit-transform: translate3d(-3000px, 0, 0); + transform: translate3d(-3000px, 0, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(25px, 0, 0); + transform: translate3d(25px, 0, 0); + } + + 75% { + -webkit-transform: translate3d(-10px, 0, 0); + transform: translate3d(-10px, 0, 0); + } + + 90% { + -webkit-transform: translate3d(5px, 0, 0); + transform: translate3d(5px, 0, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.bounceInLeft { + -webkit-animation-name: bounceInLeft; + animation-name: bounceInLeft; +} + +@-webkit-keyframes bounceInRight { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + from { + opacity: 0; + -webkit-transform: translate3d(3000px, 0, 0); + transform: translate3d(3000px, 0, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(-25px, 0, 0); + transform: translate3d(-25px, 0, 0); + } + + 75% { + -webkit-transform: translate3d(10px, 0, 0); + transform: translate3d(10px, 0, 0); + } + + 90% { + -webkit-transform: translate3d(-5px, 0, 0); + transform: translate3d(-5px, 0, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes bounceInRight { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + from { + opacity: 0; + -webkit-transform: translate3d(3000px, 0, 0); + transform: translate3d(3000px, 0, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(-25px, 0, 0); + transform: translate3d(-25px, 0, 0); + } + + 75% { + -webkit-transform: translate3d(10px, 0, 0); + transform: translate3d(10px, 0, 0); + } + + 90% { + -webkit-transform: translate3d(-5px, 0, 0); + transform: translate3d(-5px, 0, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.bounceInRight { + -webkit-animation-name: bounceInRight; + animation-name: bounceInRight; +} + +@-webkit-keyframes bounceInUp { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + from { + opacity: 0; + -webkit-transform: translate3d(0, 3000px, 0); + transform: translate3d(0, 3000px, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(0, -20px, 0); + transform: translate3d(0, -20px, 0); + } + + 75% { + -webkit-transform: translate3d(0, 10px, 0); + transform: translate3d(0, 10px, 0); + } + + 90% { + -webkit-transform: translate3d(0, -5px, 0); + transform: translate3d(0, -5px, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes bounceInUp { + from, + 60%, + 75%, + 90%, + to { + -webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); + } + + from { + opacity: 0; + -webkit-transform: translate3d(0, 3000px, 0); + transform: translate3d(0, 3000px, 0); + } + + 60% { + opacity: 1; + -webkit-transform: translate3d(0, -20px, 0); + transform: translate3d(0, -20px, 0); + } + + 75% { + -webkit-transform: translate3d(0, 10px, 0); + transform: translate3d(0, 10px, 0); + } + + 90% { + -webkit-transform: translate3d(0, -5px, 0); + transform: translate3d(0, -5px, 0); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.bounceInUp { + -webkit-animation-name: bounceInUp; + animation-name: bounceInUp; +} + +@-webkit-keyframes bounceOut { + 20% { + -webkit-transform: scale3d(0.9, 0.9, 0.9); + transform: scale3d(0.9, 0.9, 0.9); + } + + 50%, + 55% { + opacity: 1; + -webkit-transform: scale3d(1.1, 1.1, 1.1); + transform: scale3d(1.1, 1.1, 1.1); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } +} + +@keyframes bounceOut { + 20% { + -webkit-transform: scale3d(0.9, 0.9, 0.9); + transform: scale3d(0.9, 0.9, 0.9); + } + + 50%, + 55% { + opacity: 1; + -webkit-transform: scale3d(1.1, 1.1, 1.1); + transform: scale3d(1.1, 1.1, 1.1); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } +} + +.bounceOut { + -webkit-animation-duration: 0.75s; + animation-duration: 0.75s; + -webkit-animation-name: bounceOut; + animation-name: bounceOut; +} + +@-webkit-keyframes bounceOutDown { + 20% { + -webkit-transform: translate3d(0, 10px, 0); + transform: translate3d(0, 10px, 0); + } + + 40%, + 45% { + opacity: 1; + -webkit-transform: translate3d(0, -20px, 0); + transform: translate3d(0, -20px, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } +} + +@keyframes bounceOutDown { + 20% { + -webkit-transform: translate3d(0, 10px, 0); + transform: translate3d(0, 10px, 0); + } + + 40%, + 45% { + opacity: 1; + -webkit-transform: translate3d(0, -20px, 0); + transform: translate3d(0, -20px, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } +} + +.bounceOutDown { + -webkit-animation-name: bounceOutDown; + animation-name: bounceOutDown; +} + +@-webkit-keyframes bounceOutLeft { + 20% { + opacity: 1; + -webkit-transform: translate3d(20px, 0, 0); + transform: translate3d(20px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } +} + +@keyframes bounceOutLeft { + 20% { + opacity: 1; + -webkit-transform: translate3d(20px, 0, 0); + transform: translate3d(20px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } +} + +.bounceOutLeft { + -webkit-animation-name: bounceOutLeft; + animation-name: bounceOutLeft; +} + +@-webkit-keyframes bounceOutRight { + 20% { + opacity: 1; + -webkit-transform: translate3d(-20px, 0, 0); + transform: translate3d(-20px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } +} + +@keyframes bounceOutRight { + 20% { + opacity: 1; + -webkit-transform: translate3d(-20px, 0, 0); + transform: translate3d(-20px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } +} + +.bounceOutRight { + -webkit-animation-name: bounceOutRight; + animation-name: bounceOutRight; +} + +@-webkit-keyframes bounceOutUp { + 20% { + -webkit-transform: translate3d(0, -10px, 0); + transform: translate3d(0, -10px, 0); + } + + 40%, + 45% { + opacity: 1; + -webkit-transform: translate3d(0, 20px, 0); + transform: translate3d(0, 20px, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } +} + +@keyframes bounceOutUp { + 20% { + -webkit-transform: translate3d(0, -10px, 0); + transform: translate3d(0, -10px, 0); + } + + 40%, + 45% { + opacity: 1; + -webkit-transform: translate3d(0, 20px, 0); + transform: translate3d(0, 20px, 0); + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } +} + +.bounceOutUp { + -webkit-animation-name: bounceOutUp; + animation-name: bounceOutUp; +} + +@-webkit-keyframes fadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes fadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +.fadeIn { + -webkit-animation-name: fadeIn; + animation-name: fadeIn; +} + +@-webkit-keyframes fadeInDown { + from { + opacity: 0; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInDown { + from { + opacity: 0; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInDown { + -webkit-animation-name: fadeInDown; + animation-name: fadeInDown; +} + +@-webkit-keyframes fadeInDownBig { + from { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInDownBig { + from { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInDownBig { + -webkit-animation-name: fadeInDownBig; + animation-name: fadeInDownBig; +} + +@-webkit-keyframes fadeInLeft { + from { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInLeft { + from { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInLeft { + -webkit-animation-name: fadeInLeft; + animation-name: fadeInLeft; +} + +@-webkit-keyframes fadeInLeftBig { + from { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInLeftBig { + from { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInLeftBig { + -webkit-animation-name: fadeInLeftBig; + animation-name: fadeInLeftBig; +} + +@-webkit-keyframes fadeInRight { + from { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInRight { + from { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInRight { + -webkit-animation-name: fadeInRight; + animation-name: fadeInRight; +} + +@-webkit-keyframes fadeInRightBig { + from { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInRightBig { + from { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInRightBig { + -webkit-animation-name: fadeInRightBig; + animation-name: fadeInRightBig; +} + +@-webkit-keyframes fadeInUp { + from { + opacity: 0; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInUp { + from { + opacity: 0; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInUp { + -webkit-animation-name: fadeInUp; + animation-name: fadeInUp; +} + +@-webkit-keyframes fadeInUpBig { + from { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes fadeInUpBig { + from { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.fadeInUpBig { + -webkit-animation-name: fadeInUpBig; + animation-name: fadeInUpBig; +} + +@-webkit-keyframes fadeOut { + from { + opacity: 1; + } + + to { + opacity: 0; + } +} + +@keyframes fadeOut { + from { + opacity: 1; + } + + to { + opacity: 0; + } +} + +.fadeOut { + -webkit-animation-name: fadeOut; + animation-name: fadeOut; +} + +@-webkit-keyframes fadeOutDown { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } +} + +@keyframes fadeOutDown { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } +} + +.fadeOutDown { + -webkit-animation-name: fadeOutDown; + animation-name: fadeOutDown; +} + +@-webkit-keyframes fadeOutDownBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } +} + +@keyframes fadeOutDownBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, 2000px, 0); + transform: translate3d(0, 2000px, 0); + } +} + +.fadeOutDownBig { + -webkit-animation-name: fadeOutDownBig; + animation-name: fadeOutDownBig; +} + +@-webkit-keyframes fadeOutLeft { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } +} + +@keyframes fadeOutLeft { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } +} + +.fadeOutLeft { + -webkit-animation-name: fadeOutLeft; + animation-name: fadeOutLeft; +} + +@-webkit-keyframes fadeOutLeftBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } +} + +@keyframes fadeOutLeftBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(-2000px, 0, 0); + transform: translate3d(-2000px, 0, 0); + } +} + +.fadeOutLeftBig { + -webkit-animation-name: fadeOutLeftBig; + animation-name: fadeOutLeftBig; +} + +@-webkit-keyframes fadeOutRight { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } +} + +@keyframes fadeOutRight { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } +} + +.fadeOutRight { + -webkit-animation-name: fadeOutRight; + animation-name: fadeOutRight; +} + +@-webkit-keyframes fadeOutRightBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } +} + +@keyframes fadeOutRightBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(2000px, 0, 0); + transform: translate3d(2000px, 0, 0); + } +} + +.fadeOutRightBig { + -webkit-animation-name: fadeOutRightBig; + animation-name: fadeOutRightBig; +} + +@-webkit-keyframes fadeOutUp { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } +} + +@keyframes fadeOutUp { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } +} + +.fadeOutUp { + -webkit-animation-name: fadeOutUp; + animation-name: fadeOutUp; +} + +@-webkit-keyframes fadeOutUpBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } +} + +@keyframes fadeOutUpBig { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(0, -2000px, 0); + transform: translate3d(0, -2000px, 0); + } +} + +.fadeOutUpBig { + -webkit-animation-name: fadeOutUpBig; + animation-name: fadeOutUpBig; +} + +@-webkit-keyframes flip { + from { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) + rotate3d(0, 1, 0, -360deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, -360deg); + -webkit-animation-timing-function: ease-out; + animation-timing-function: ease-out; + } + + 40% { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -190deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -190deg); + -webkit-animation-timing-function: ease-out; + animation-timing-function: ease-out; + } + + 50% { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -170deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -170deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 80% { + -webkit-transform: perspective(400px) scale3d(0.95, 0.95, 0.95) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + transform: perspective(400px) scale3d(0.95, 0.95, 0.95) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + to { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, 0deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } +} + +@keyframes flip { + from { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) + rotate3d(0, 1, 0, -360deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, -360deg); + -webkit-animation-timing-function: ease-out; + animation-timing-function: ease-out; + } + + 40% { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -190deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -190deg); + -webkit-animation-timing-function: ease-out; + animation-timing-function: ease-out; + } + + 50% { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -170deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 150px) + rotate3d(0, 1, 0, -170deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 80% { + -webkit-transform: perspective(400px) scale3d(0.95, 0.95, 0.95) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + transform: perspective(400px) scale3d(0.95, 0.95, 0.95) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + to { + -webkit-transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) + rotate3d(0, 1, 0, 0deg); + transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0) rotate3d(0, 1, 0, 0deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } +} + +.animated.flip { + -webkit-backface-visibility: visible; + backface-visibility: visible; + -webkit-animation-name: flip; + animation-name: flip; +} + +@-webkit-keyframes flipInX { + from { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + opacity: 0; + } + + 40% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 60% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg); + transform: perspective(400px) rotate3d(1, 0, 0, 10deg); + opacity: 1; + } + + 80% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg); + transform: perspective(400px) rotate3d(1, 0, 0, -5deg); + } + + to { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } +} + +@keyframes flipInX { + from { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + opacity: 0; + } + + 40% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 60% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg); + transform: perspective(400px) rotate3d(1, 0, 0, 10deg); + opacity: 1; + } + + 80% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg); + transform: perspective(400px) rotate3d(1, 0, 0, -5deg); + } + + to { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } +} + +.flipInX { + -webkit-backface-visibility: visible !important; + backface-visibility: visible !important; + -webkit-animation-name: flipInX; + animation-name: flipInX; +} + +@-webkit-keyframes flipInY { + from { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + opacity: 0; + } + + 40% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -20deg); + transform: perspective(400px) rotate3d(0, 1, 0, -20deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 60% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 10deg); + transform: perspective(400px) rotate3d(0, 1, 0, 10deg); + opacity: 1; + } + + 80% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -5deg); + transform: perspective(400px) rotate3d(0, 1, 0, -5deg); + } + + to { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } +} + +@keyframes flipInY { + from { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + opacity: 0; + } + + 40% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -20deg); + transform: perspective(400px) rotate3d(0, 1, 0, -20deg); + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; + } + + 60% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 10deg); + transform: perspective(400px) rotate3d(0, 1, 0, 10deg); + opacity: 1; + } + + 80% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -5deg); + transform: perspective(400px) rotate3d(0, 1, 0, -5deg); + } + + to { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } +} + +.flipInY { + -webkit-backface-visibility: visible !important; + backface-visibility: visible !important; + -webkit-animation-name: flipInY; + animation-name: flipInY; +} + +@-webkit-keyframes flipOutX { + from { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } + + 30% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + opacity: 1; + } + + to { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + opacity: 0; + } +} + +@keyframes flipOutX { + from { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } + + 30% { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + transform: perspective(400px) rotate3d(1, 0, 0, -20deg); + opacity: 1; + } + + to { + -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + transform: perspective(400px) rotate3d(1, 0, 0, 90deg); + opacity: 0; + } +} + +.flipOutX { + -webkit-animation-duration: 0.75s; + animation-duration: 0.75s; + -webkit-animation-name: flipOutX; + animation-name: flipOutX; + -webkit-backface-visibility: visible !important; + backface-visibility: visible !important; +} + +@-webkit-keyframes flipOutY { + from { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } + + 30% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -15deg); + transform: perspective(400px) rotate3d(0, 1, 0, -15deg); + opacity: 1; + } + + to { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + opacity: 0; + } +} + +@keyframes flipOutY { + from { + -webkit-transform: perspective(400px); + transform: perspective(400px); + } + + 30% { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, -15deg); + transform: perspective(400px) rotate3d(0, 1, 0, -15deg); + opacity: 1; + } + + to { + -webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + transform: perspective(400px) rotate3d(0, 1, 0, 90deg); + opacity: 0; + } +} + +.flipOutY { + -webkit-animation-duration: 0.75s; + animation-duration: 0.75s; + -webkit-backface-visibility: visible !important; + backface-visibility: visible !important; + -webkit-animation-name: flipOutY; + animation-name: flipOutY; +} + +@-webkit-keyframes lightSpeedIn { + from { + -webkit-transform: translate3d(100%, 0, 0) skewX(-30deg); + transform: translate3d(100%, 0, 0) skewX(-30deg); + opacity: 0; + } + + 60% { + -webkit-transform: skewX(20deg); + transform: skewX(20deg); + opacity: 1; + } + + 80% { + -webkit-transform: skewX(-5deg); + transform: skewX(-5deg); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes lightSpeedIn { + from { + -webkit-transform: translate3d(100%, 0, 0) skewX(-30deg); + transform: translate3d(100%, 0, 0) skewX(-30deg); + opacity: 0; + } + + 60% { + -webkit-transform: skewX(20deg); + transform: skewX(20deg); + opacity: 1; + } + + 80% { + -webkit-transform: skewX(-5deg); + transform: skewX(-5deg); + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.lightSpeedIn { + -webkit-animation-name: lightSpeedIn; + animation-name: lightSpeedIn; + -webkit-animation-timing-function: ease-out; + animation-timing-function: ease-out; +} + +@-webkit-keyframes lightSpeedOut { + from { + opacity: 1; + } + + to { + -webkit-transform: translate3d(100%, 0, 0) skewX(30deg); + transform: translate3d(100%, 0, 0) skewX(30deg); + opacity: 0; + } +} + +@keyframes lightSpeedOut { + from { + opacity: 1; + } + + to { + -webkit-transform: translate3d(100%, 0, 0) skewX(30deg); + transform: translate3d(100%, 0, 0) skewX(30deg); + opacity: 0; + } +} + +.lightSpeedOut { + -webkit-animation-name: lightSpeedOut; + animation-name: lightSpeedOut; + -webkit-animation-timing-function: ease-in; + animation-timing-function: ease-in; +} + +@-webkit-keyframes rotateIn { + from { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: rotate3d(0, 0, 1, -200deg); + transform: rotate3d(0, 0, 1, -200deg); + opacity: 0; + } + + to { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +@keyframes rotateIn { + from { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: rotate3d(0, 0, 1, -200deg); + transform: rotate3d(0, 0, 1, -200deg); + opacity: 0; + } + + to { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +.rotateIn { + -webkit-animation-name: rotateIn; + animation-name: rotateIn; +} + +@-webkit-keyframes rotateInDownLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +@keyframes rotateInDownLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +.rotateInDownLeft { + -webkit-animation-name: rotateInDownLeft; + animation-name: rotateInDownLeft; +} + +@-webkit-keyframes rotateInDownRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +@keyframes rotateInDownRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +.rotateInDownRight { + -webkit-animation-name: rotateInDownRight; + animation-name: rotateInDownRight; +} + +@-webkit-keyframes rotateInUpLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +@keyframes rotateInUpLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +.rotateInUpLeft { + -webkit-animation-name: rotateInUpLeft; + animation-name: rotateInUpLeft; +} + +@-webkit-keyframes rotateInUpRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, -90deg); + transform: rotate3d(0, 0, 1, -90deg); + opacity: 0; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +@keyframes rotateInUpRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, -90deg); + transform: rotate3d(0, 0, 1, -90deg); + opacity: 0; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + opacity: 1; + } +} + +.rotateInUpRight { + -webkit-animation-name: rotateInUpRight; + animation-name: rotateInUpRight; +} + +@-webkit-keyframes rotateOut { + from { + -webkit-transform-origin: center; + transform-origin: center; + opacity: 1; + } + + to { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: rotate3d(0, 0, 1, 200deg); + transform: rotate3d(0, 0, 1, 200deg); + opacity: 0; + } +} + +@keyframes rotateOut { + from { + -webkit-transform-origin: center; + transform-origin: center; + opacity: 1; + } + + to { + -webkit-transform-origin: center; + transform-origin: center; + -webkit-transform: rotate3d(0, 0, 1, 200deg); + transform: rotate3d(0, 0, 1, 200deg); + opacity: 0; + } +} + +.rotateOut { + -webkit-animation-name: rotateOut; + animation-name: rotateOut; +} + +@-webkit-keyframes rotateOutDownLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } +} + +@keyframes rotateOutDownLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, 45deg); + transform: rotate3d(0, 0, 1, 45deg); + opacity: 0; + } +} + +.rotateOutDownLeft { + -webkit-animation-name: rotateOutDownLeft; + animation-name: rotateOutDownLeft; +} + +@-webkit-keyframes rotateOutDownRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } +} + +@keyframes rotateOutDownRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } +} + +.rotateOutDownRight { + -webkit-animation-name: rotateOutDownRight; + animation-name: rotateOutDownRight; +} + +@-webkit-keyframes rotateOutUpLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } +} + +@keyframes rotateOutUpLeft { + from { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: left bottom; + transform-origin: left bottom; + -webkit-transform: rotate3d(0, 0, 1, -45deg); + transform: rotate3d(0, 0, 1, -45deg); + opacity: 0; + } +} + +.rotateOutUpLeft { + -webkit-animation-name: rotateOutUpLeft; + animation-name: rotateOutUpLeft; +} + +@-webkit-keyframes rotateOutUpRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, 90deg); + transform: rotate3d(0, 0, 1, 90deg); + opacity: 0; + } +} + +@keyframes rotateOutUpRight { + from { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + opacity: 1; + } + + to { + -webkit-transform-origin: right bottom; + transform-origin: right bottom; + -webkit-transform: rotate3d(0, 0, 1, 90deg); + transform: rotate3d(0, 0, 1, 90deg); + opacity: 0; + } +} + +.rotateOutUpRight { + -webkit-animation-name: rotateOutUpRight; + animation-name: rotateOutUpRight; +} + +@-webkit-keyframes hinge { + 0% { + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + } + + 20%, + 60% { + -webkit-transform: rotate3d(0, 0, 1, 80deg); + transform: rotate3d(0, 0, 1, 80deg); + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + } + + 40%, + 80% { + -webkit-transform: rotate3d(0, 0, 1, 60deg); + transform: rotate3d(0, 0, 1, 60deg); + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + opacity: 1; + } + + to { + -webkit-transform: translate3d(0, 700px, 0); + transform: translate3d(0, 700px, 0); + opacity: 0; + } +} + +@keyframes hinge { + 0% { + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + } + + 20%, + 60% { + -webkit-transform: rotate3d(0, 0, 1, 80deg); + transform: rotate3d(0, 0, 1, 80deg); + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + } + + 40%, + 80% { + -webkit-transform: rotate3d(0, 0, 1, 60deg); + transform: rotate3d(0, 0, 1, 60deg); + -webkit-transform-origin: top left; + transform-origin: top left; + -webkit-animation-timing-function: ease-in-out; + animation-timing-function: ease-in-out; + opacity: 1; + } + + to { + -webkit-transform: translate3d(0, 700px, 0); + transform: translate3d(0, 700px, 0); + opacity: 0; + } +} + +.hinge { + -webkit-animation-duration: 2s; + animation-duration: 2s; + -webkit-animation-name: hinge; + animation-name: hinge; +} + +@-webkit-keyframes jackInTheBox { + from { + opacity: 0; + -webkit-transform: scale(0.1) rotate(30deg); + transform: scale(0.1) rotate(30deg); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + } + + 50% { + -webkit-transform: rotate(-10deg); + transform: rotate(-10deg); + } + + 70% { + -webkit-transform: rotate(3deg); + transform: rotate(3deg); + } + + to { + opacity: 1; + -webkit-transform: scale(1); + transform: scale(1); + } +} + +@keyframes jackInTheBox { + from { + opacity: 0; + -webkit-transform: scale(0.1) rotate(30deg); + transform: scale(0.1) rotate(30deg); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + } + + 50% { + -webkit-transform: rotate(-10deg); + transform: rotate(-10deg); + } + + 70% { + -webkit-transform: rotate(3deg); + transform: rotate(3deg); + } + + to { + opacity: 1; + -webkit-transform: scale(1); + transform: scale(1); + } +} + +.jackInTheBox { + -webkit-animation-name: jackInTheBox; + animation-name: jackInTheBox; +} + +/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ + +@-webkit-keyframes rollIn { + from { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg); + transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes rollIn { + from { + opacity: 0; + -webkit-transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg); + transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg); + } + + to { + opacity: 1; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.rollIn { + -webkit-animation-name: rollIn; + animation-name: rollIn; +} + +/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */ + +@-webkit-keyframes rollOut { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0) rotate3d(0, 0, 1, 120deg); + transform: translate3d(100%, 0, 0) rotate3d(0, 0, 1, 120deg); + } +} + +@keyframes rollOut { + from { + opacity: 1; + } + + to { + opacity: 0; + -webkit-transform: translate3d(100%, 0, 0) rotate3d(0, 0, 1, 120deg); + transform: translate3d(100%, 0, 0) rotate3d(0, 0, 1, 120deg); + } +} + +.rollOut { + -webkit-animation-name: rollOut; + animation-name: rollOut; +} + +@-webkit-keyframes zoomIn { + from { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + 50% { + opacity: 1; + } +} + +@keyframes zoomIn { + from { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + 50% { + opacity: 1; + } +} + +.zoomIn { + -webkit-animation-name: zoomIn; + animation-name: zoomIn; +} + +@-webkit-keyframes zoomInDown { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -1000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -1000px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomInDown { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -1000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -1000px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomInDown { + -webkit-animation-name: zoomInDown; + animation-name: zoomInDown; +} + +@-webkit-keyframes zoomInLeft { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(-1000px, 0, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(-1000px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(10px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(10px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomInLeft { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(-1000px, 0, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(-1000px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(10px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(10px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomInLeft { + -webkit-animation-name: zoomInLeft; + animation-name: zoomInLeft; +} + +@-webkit-keyframes zoomInRight { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(1000px, 0, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(1000px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(-10px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(-10px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomInRight { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(1000px, 0, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(1000px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(-10px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(-10px, 0, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomInRight { + -webkit-animation-name: zoomInRight; + animation-name: zoomInRight; +} + +@-webkit-keyframes zoomInUp { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 1000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 1000px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomInUp { + from { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 1000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 1000px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + 60% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomInUp { + -webkit-animation-name: zoomInUp; + animation-name: zoomInUp; +} + +@-webkit-keyframes zoomOut { + from { + opacity: 1; + } + + 50% { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + to { + opacity: 0; + } +} + +@keyframes zoomOut { + from { + opacity: 1; + } + + 50% { + opacity: 0; + -webkit-transform: scale3d(0.3, 0.3, 0.3); + transform: scale3d(0.3, 0.3, 0.3); + } + + to { + opacity: 0; + } +} + +.zoomOut { + -webkit-animation-name: zoomOut; + animation-name: zoomOut; +} + +@-webkit-keyframes zoomOutDown { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomOutDown { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomOutDown { + -webkit-animation-name: zoomOutDown; + animation-name: zoomOutDown; +} + +@-webkit-keyframes zoomOutLeft { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(42px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(42px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: scale(0.1) translate3d(-2000px, 0, 0); + transform: scale(0.1) translate3d(-2000px, 0, 0); + -webkit-transform-origin: left center; + transform-origin: left center; + } +} + +@keyframes zoomOutLeft { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(42px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(42px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: scale(0.1) translate3d(-2000px, 0, 0); + transform: scale(0.1) translate3d(-2000px, 0, 0); + -webkit-transform-origin: left center; + transform-origin: left center; + } +} + +.zoomOutLeft { + -webkit-animation-name: zoomOutLeft; + animation-name: zoomOutLeft; +} + +@-webkit-keyframes zoomOutRight { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(-42px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(-42px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: scale(0.1) translate3d(2000px, 0, 0); + transform: scale(0.1) translate3d(2000px, 0, 0); + -webkit-transform-origin: right center; + transform-origin: right center; + } +} + +@keyframes zoomOutRight { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(-42px, 0, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(-42px, 0, 0); + } + + to { + opacity: 0; + -webkit-transform: scale(0.1) translate3d(2000px, 0, 0); + transform: scale(0.1) translate3d(2000px, 0, 0); + -webkit-transform-origin: right center; + transform-origin: right center; + } +} + +.zoomOutRight { + -webkit-animation-name: zoomOutRight; + animation-name: zoomOutRight; +} + +@-webkit-keyframes zoomOutUp { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -2000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -2000px, 0); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +@keyframes zoomOutUp { + 40% { + opacity: 1; + -webkit-transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0); + -webkit-animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); + } + + to { + opacity: 0; + -webkit-transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -2000px, 0); + transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -2000px, 0); + -webkit-transform-origin: center bottom; + transform-origin: center bottom; + -webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1); + } +} + +.zoomOutUp { + -webkit-animation-name: zoomOutUp; + animation-name: zoomOutUp; +} + +@-webkit-keyframes slideInDown { + from { + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes slideInDown { + from { + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.slideInDown { + -webkit-animation-name: slideInDown; + animation-name: slideInDown; +} + +@-webkit-keyframes slideInLeft { + from { + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes slideInLeft { + from { + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.slideInLeft { + -webkit-animation-name: slideInLeft; + animation-name: slideInLeft; +} + +@-webkit-keyframes slideInRight { + from { + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes slideInRight { + from { + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.slideInRight { + -webkit-animation-name: slideInRight; + animation-name: slideInRight; +} + +@-webkit-keyframes slideInUp { + from { + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +@keyframes slideInUp { + from { + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + visibility: visible; + } + + to { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} + +.slideInUp { + -webkit-animation-name: slideInUp; + animation-name: slideInUp; +} + +@-webkit-keyframes slideOutDown { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } +} + +@keyframes slideOutDown { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(0, 100%, 0); + transform: translate3d(0, 100%, 0); + } +} + +.slideOutDown { + -webkit-animation-name: slideOutDown; + animation-name: slideOutDown; +} + +@-webkit-keyframes slideOutLeft { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } +} + +@keyframes slideOutLeft { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } +} + +.slideOutLeft { + -webkit-animation-name: slideOutLeft; + animation-name: slideOutLeft; +} + +@-webkit-keyframes slideOutRight { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } +} + +@keyframes slideOutRight { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } +} + +.slideOutRight { + -webkit-animation-name: slideOutRight; + animation-name: slideOutRight; +} + +@-webkit-keyframes slideOutUp { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } +} + +@keyframes slideOutUp { + from { + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } + + to { + visibility: hidden; + -webkit-transform: translate3d(0, -100%, 0); + transform: translate3d(0, -100%, 0); + } +} + +.slideOutUp { + -webkit-animation-name: slideOutUp; + animation-name: slideOutUp; +} + +.animated { + -webkit-animation-duration: 1s; + animation-duration: 1s; + -webkit-animation-fill-mode: both; + animation-fill-mode: both; +} + +.animated.infinite { + -webkit-animation-iteration-count: infinite; + animation-iteration-count: infinite; +} + +.animated.delay-1s { + -webkit-animation-delay: 1s; + animation-delay: 1s; +} + +.animated.delay-2s { + -webkit-animation-delay: 2s; + animation-delay: 2s; +} + +.animated.delay-3s { + -webkit-animation-delay: 3s; + animation-delay: 3s; +} + +.animated.delay-4s { + -webkit-animation-delay: 4s; + animation-delay: 4s; +} + +.animated.delay-5s { + -webkit-animation-delay: 5s; + animation-delay: 5s; +} + +.animated.fast { + -webkit-animation-duration: 800ms; + animation-duration: 800ms; +} + +.animated.faster { + -webkit-animation-duration: 500ms; + animation-duration: 500ms; +} + +.animated.slow { + -webkit-animation-duration: 2s; + animation-duration: 2s; +} + +.animated.slower { + -webkit-animation-duration: 3s; + animation-duration: 3s; +} + +@media (print), (prefers-reduced-motion) { + .animated { + -webkit-animation: unset !important; + animation: unset !important; + -webkit-transition: none !important; + transition: none !important; + } +} diff --git a/workflow/public_html/lib/pmdynaform/libs/backbone/backbone-min.js b/workflow/public_html/lib/pmdynaform/libs/backbone/backbone-min.js new file mode 100644 index 000000000..26ff009f2 --- /dev/null +++ b/workflow/public_html/lib/pmdynaform/libs/backbone/backbone-min.js @@ -0,0 +1 @@ +(function(t,e){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){t.Backbone=e(t,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore");e(t,exports,i)}else{t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}})(this,function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.push;var o=n.slice;var h=n.splice;e.VERSION="1.1.2";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var u=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,r){if(!c(this,"once",t,[e,r])||!e)return this;var s=this;var n=i.once(function(){s.off(t,n);e.apply(this,arguments)});n._callback=e;return this.on(t,n,r)},off:function(t,e,r){var s,n,a,o,h,u,l,f;if(!this._events||!c(this,"off",t,[e,r]))return this;if(!t&&!e&&!r){this._events=void 0;return this}o=t?[t]:i.keys(this._events);for(h=0,u=o.length;h").attr(t);this.setElement(r,false)}else{this.setElement(i.result(this,"el"),false)}}});e.sync=function(t,r,s){var n=T[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:n,dataType:"json"};if(!s.url){a.url=i.result(r,"url")||M()}if(s.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(s.attrs||r.toJSON(s))}if(s.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(s.emulateHTTP&&(n==="PUT"||n==="DELETE"||n==="PATCH")){a.type="POST";if(s.emulateJSON)a.data._method=n;var o=s.beforeSend;s.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",n);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!s.emulateJSON){a.processData=false}if(a.type==="PATCH"&&k){a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var h=s.xhr=e.ajax(i.extend(a,s));r.trigger("request",r,h,s);return h};var k=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var T={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var S=/\((.*?)\)/g;var H=/(\(\?)?:\w+/g;var A=/\*\w+/g;var I=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,u,{initialize:function(){},route:function(t,r,s){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){s=r;r=""}if(!s)s=this[r];var n=this;e.history.route(t,function(i){var a=n._extractParameters(t,i);n.execute(s,a);n.trigger.apply(n,["route:"+r].concat(a));n.trigger("route",r,a);e.history.trigger("route",n,r,a)});return this},execute:function(t,e){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(I,"\\$&").replace(S,"(?:$1)?").replace(H,function(t,e){return e?t:"([^/?]+)"}).replace(A,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var N=e.History=function(){this.handlers=[];i.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var R=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var P=/msie [\w.]+/;var C=/\/$/;var j=/#.*$/;N.started=false;i.extend(N.prototype,u,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.slice(i.length)}else{t=this.getHash()}}return t.replace(R,"")},start:function(t){if(N.started)throw new Error("Backbone.history has already been started");N.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var r=this.getFragment();var s=document.documentMode;var n=P.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);this.root=("/"+this.root+"/").replace(O,"/");if(n&&this._wantsHashChange){var a=e.$('