//AJS.$("#rowForcustomfield_19800").hide()
	var apCount = 0;
	var userName = "";
	var currentStatus = AJS.$("#status-val").text().trim();
	var transitionURI = AJS.$("#action_id_51").attr("href");
	AJS.$("#action_id_51").attr("href","#");
	AJS.$("#customfield_17601-val").parent().parent().hide();
	$("#linkingmodule").hide();
	eIURI = AJS.$("#action_id_21").attr("href");
	AJS.$("#action_id_21").attr("href","#");

	if(currentStatus == "Implementation"){
		//This is action plan
		AJS.$("#action_id_81").attr("href","#");
	}
	if(currentStatus == "Evaluate Impact"){
		//This is action plan
		AJS.$("#action_id_61").attr("href","#");
	}

	var createActionPlanURI = AJS.$("#action_id_11").attr("href");
	AJS.$("#action_id_11").attr("href","#");


	actionPlanInstructions ="";
	console.log("*******************OUTSIDE INIT*******************");
	var dialogHTML = '<section id="demo-dialog" class="aui-dialog2 aui-dialog2-large aui-layer" role="dialog" aria-hidden="true"><header class="aui-dialog2-header"><h2 id="headingTitle" class="aui-dialog2-header-main">Create</h2><button class="aui-dialog2-header-close" aria-label="close"><span class="aui-icon aui-icon-small aui-iconfont-close-dialog"></span></button></header><div class="aui-dialog2-content"><div id="progressBar" ><aui-spinner></aui-spinner></div><div id="buContentDiv"></div></div><footer class="aui-dialog2-footer"><div class="aui-dialog2-footer-actions"><button id="dialog-submit-button" class="aui-button aui-button-primary">Create</button><button id="warning-dialog-cancel" class="aui-button aui-button-link">Cancel</button></div></footer></section>';
	if(AJS.$("#demo-dialog").length == 0){
		AJS.$("body").append(dialogHTML);
	}


	function preparePopup(){
	AJS.dialog2("#demo-dialog").on("hide", function() {
		AJS.$("#buContentDiv").contents().remove();
	});
			AJS.dialog2("#demo-dialog").on("show", function() {
				AJS.$("#progressBar").show();
				var currentIssueKey = AJS.Meta.get("issue-key");
				var regChangePopUpIssueType = AJS.$("#headingTitle").attr("issueType");
				setTimeout(function(){ 
						AJS.$.ajax({
							url: "/casemanagement/rest/predictapi/latest/issuelink/" + currentIssueKey + "/"+ regChangePopUpIssueType +"/",
							type: 'get',
							dataType: 'json',
							async: false,
							success: function(data) {
								AJS.$("#progressBar").hide()
								var index=0;
								var innerHTML = '<form class="aui" action="#">';

								if(regChangePopUpIssueType == "Evaluate Impact"){		
									if(data ==null || data.results == null || data.results.length==0){
										console.log('should not be called on submit....');
										/*var aTag = document.createElement('a');
										aTag.setAttribute('href',eIURI);
										aTag.className = "aui-button toolbar-trigger issueaction-workflow-transition";
										aTag.click();
										AJS.dialog2("#demo-dialog").hide();*/
										$("#buContentDiv").find("#evmsg").remove();
									   $("#buContentDiv").append('<span id="evmsg">Evaluate Impact for selected Business Unit(s) is already in open state</span>');
										return;
									}
								}
								if(data!=null){
									userName = data.loggedUser;
									data.results.forEach(function (item) {
										var className="";
										var regInstructions = actionPlanInstructions;
										//$("#customfield_21800-val").click();
										//console.log($("#customfield_21800").text().trim());
										console.log('before regtext add');
										var regText = $("#customfield_21600-val").text().trim();
										console.log('regtext:: ' +regText);
										if (regText != ''){
										regText = regText.substring(regText.indexOf("::start")+7,regText.indexOf("footer::end"));
										}
										//$("#customfield_21800-val").parent().hide();
										if (regInstructions != '' && regInstructions != null){
											regInstructions = actionPlanInstructions+'\n\n'+ regText;
										  }else{
											regInstructions = regText;
										  }
										if(index >0){
											className="aui-page-panel";
										}
										 if(regChangePopUpIssueType == "Evaluate Impact"){		
										 innerHTML +='<div>&nbsp;</div><div class="field-group '+ className + '"><label for="text-input">Business Unit</label><input disabled id="bu_' + item.id + '" value="'+ item.text+'"  class="text" type="text" name="bunames">&nbsp;<input class="checkbox" value="'+ item.id+'" type="checkbox"  name="buChkbox"  checked id="buChkbox"></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Instructions</label><textarea id="txt_area_' + item.id + '"  class="single-user-picker" name="txt_area" >'+regInstructions+'</textarea></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Assignee</label><select id="bu_assignee_' + item.id + '"  class="single-user-picker" name="assignee" data-user-type="assignee"></select></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Due Date</label><input id="duedate_' + item.id + '" name="bu_duedate"  class="aui-date-picker" type="date" min="2015-01-01"></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Magnitude-BU</label><select id="bu_magnitude_' + item.id + '"  class="select predict-cf-select" name="bu_magnitude" type = "text"></select></div>'; 
										}else{
											  innerHTML +='<div>&nbsp;</div><div class="field-group '+ className + '"><label for="text-input">Business Unit</label><input disabled id="bu_' + item.id + '" value="'+ item.text+'"  class="text" type="text" name="bunames">&nbsp;<input class="checkbox" value="'+ item.id+'" type="checkbox"  name="buChkbox"  checked id="buChkbox"></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Instructions</label><textarea id="txt_area_' + item.id + '"  class="single-user-picker" name="txt_area" >'+regInstructions+'</textarea></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Assignee</label><select id="bu_assignee_' + item.id + '"  class="single-user-picker" name="assignee" data-user-type="assignee" ></select></div>';
										 innerHTML +='<div class="field-group "><label for="text-input">Due Date</label><input id="duedate_' + item.id + '" name="bu_duedate"  class="aui-date-picker" type="date" min="2015-01-01"></div>';
										}
										index++
									});
								}else{
									$("#buContentDiv").find("#acmsg").remove();
									$("#buContentDiv").append('<span id ="acmsg">Action plan for selected Business Unit(s) is already in open state</span>');
									return;
								}
								innerHTML += '</form>';
								AJS.$("#buContentDiv").html(innerHTML);
								//AJS.$('#demo-range-2').datePicker({'overrideBrowserDefault': true});
								data.results.forEach(function (item) {
										CKEDITOR.replace('txt_area_'+item.id, {		toolbar :
																	[
															{ name: 'document', items : [ 'NewPage','Preview' ] },
															{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
															{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
															{ name: 'insert', items : [ 'Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
																	 ,'Iframe' ] },
															{ name: 'styles', items : [ 'Styles','Format' ] },
															{ name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
															{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
															{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
															{ name: 'tools', items : [ 'Maximize','-','About' ] }
																	]})
										if(!item.regChangeProcessOwnerType){
											createSingleUserPicker("bu_assignee_"+item.id,item.regChangeProcessOwner,cm_selectedProjectKey + "-" + item.regChangeProcessOwner);
											AJS.$('#bu_assignee_' + item.id + '\\-field').attr('isGroup',true);
											AJS.$('#bu_assignee_' + item.id + '\\-field').attr('disabled','disabled');
										}else{
											createSingleUserPicker("bu_assignee_"+item.id,item.regChangeProcessOwner,item.regChangeProcessOwner+ "@" + cm_selectedProjectKey);
											AJS.$('#bu_assignee_' + item.id + '\\-field').attr('isGroup',false);
										}
										createMagnitudeSelector("bu_magnitude_"+item.id);
										
										console.log('selected PO ' + item.regChangeProcessOwner);
										var user = userName.substring(0,userName.lastIndexOf("@"));
										if (item.regChangeProcessOwner != user){
											$("#bu_magnitude_"+ item.id).attr("disabled","disabled");
										}
										//AJS.$('#duedate_'+item.id).datePicker({'overrideBrowserDefault': true});
								});
								
								

								
								  AJS.$('input[type=checkbox][name=buChkbox]').change(function() {
									if ($(this).is(':checked')) {
										enableControl($(this)[0].value);
									}
									else {
									  disableControl($(this)[0].value);
									}
								  });
								  
								  AJS.$(".single-user-picker.aui-ss-select").change(function() {
												console.log('assignee change '+ this.value);
												console.log('userName '+ userName);
												   var assgn = this.id;	
												  var buId = assgn.substring(assgn.lastIndexOf("_") ,assgn.length);
												  if ( $("#bu_magnitude"+buId).length > 0 ){
														if (this.value != userName){
													 $("#bu_magnitude"+buId).attr("disabled","disabled");
													 }else{
														  $("#bu_magnitude"+buId).removeAttr("disabled");
												   }
												}
												
										}
											);
							} 
					});

				}, 1);
			});

	}
	AJS.toInit(function($) {
		console.log("*******************INSIDE INIT*******************");
	if(AJS.$("#demo-dialog").length >0){
	/*setTimeout(function(){
	AJS.dialog2("#demo-dialog").show();
	}, 3);*/
		//var regChangePopUpIssueType = "";

		AJS.$("#action_id_71").click(function(){
			var closeTransitionURI = AJS.$("#action_id_71").attr("href");
			var currentIssueKey = AJS.Meta.get("issue-key");
				 AJS.$.ajax({
				url: "/casemanagement/rest/predictapi/latest/issuelink/" + currentIssueKey + "/Reg Change Action Plan,Evaluate Impact/Open/",
				type: 'get',
				dataType: 'json',
				async: false,
				success: function(data) {
					apCount = data.length;
				} 
			 });
			
			
			if(apCount <=0){
			  AJS.$("#action_id_71").attr("href",closeTransitionURI);
			  return true;
			}else{
			  
						var dialog = new AJS.Dialog({
							width: 650, 
							height: 200, 
							id: "warning-dialog", 
							closeOnOutsideClick: true
						});
						
						dialog.addHeader("Warning");
						
						var html = '<div><span class="aui-icon aui-icon-small aui-iconfont-error"></span>All open "Action Plans" / "Evaluate Impact" must be closed in order to close this Regulatory Change Task.</div>';
						html += '<span id="loadingContinue" class="aui-icon aui-icon-wait"></span>';
						// add panel 1
						dialog.addPanel("Panel 1", html, "panel-body");
						dialog.get("panel:0").setPadding(10);
				
					
						dialog.addLink("Cancel", function (dialog) {
							AJS.$("#action_id_71").attr("href","#");
							dialog.remove();
							return false;
						}, "#");
						
						dialog.show();
						return false;
			  
			}
		});

		AJS.$("#action_id_51").click(function(){
			var currentIssueKey = AJS.Meta.get("issue-key");
				 AJS.$.ajax({
				url: "/casemanagement/rest/predictapi/latest/issuelink/" + currentIssueKey + "/Reg Change Action Plan,Evaluate Impact/Open/",
				type: 'get',
				dataType: 'json',
				async: false,
				success: function(data) {
					apCount = data.length;
				} 
			 });
			
			
			if(apCount <=0){
			  AJS.$("#action_id_51").attr("href",transitionURI);
			  return true;
			}else{
			  
						var dialog = new AJS.Dialog({
							width: 650, 
							height: 200, 
							id: "warning-dialog", 
							closeOnOutsideClick: true
						});
						
						dialog.addHeader("Warning");
						
						var html = '<div><span class="aui-icon aui-icon-small aui-iconfont-error"></span>There are open "Action Plans" / "Evaluate Impact" associated with this Reg Change Task.  If you proceed, all of these action plans will be closed.</div>';
						html += '<span id="loadingContinue" class="aui-icon aui-icon-wait"></span>';
						// add panel 1
						dialog.addPanel("Panel 1", html, "panel-body");
						dialog.get("panel:0").setPadding(10);
				
						dialog.addButton("Continue", function (dialog) {
						  dialog.remove();   
						  AJS.$("#action_id_51").attr("href",transitionURI);
						  AJS.$("#action_id_51").click()
						  return true;
						  
						});
						
						dialog.addLink("Cancel", function (dialog) {
							AJS.$("#action_id_51").attr("href","#");
							dialog.remove();
							return false;
						}, "#");
						
						dialog.show();
			  
			}
		});

		AJS.$("#warning-dialog-cancel").click(function(){
			AJS.$("#buContentDiv").contents().remove();
			AJS.dialog2("#demo-dialog").hide();
		})

		AJS.$("#dialog-submit-button").click(function(){
			console.log('in submit');
			var currentIssueKey = AJS.Meta.get("issue-key");
			var buObjList = new Array();
			var nodeList = AJS.$('input[type=checkbox][name=buChkbox]:checked');
			var regChangePopUpIssueType = AJS.$("#headingTitle").attr("issueType");
			var createEval = false;
			for(var index=0;index<nodeList.length;index++){
				var buNode = new Object();
				buNode["buId"] = nodeList[index].value;
				buNode["assignee"] = AJS.$('#bu_assignee_' + nodeList[index].value).val()[0];
				buNode["dueDate"] = AJS.$('#duedate_'+ nodeList[index].value).val();
				buNode["description"] = CKEDITOR.instances["txt_area_"+nodeList[index].value].getData();
				buNode["parentKey"] = currentIssueKey;
				if (regChangePopUpIssueType == "Evaluate Impact"){
				console.log('mag bu 1' + AJS.$('#bu_magnitude_' + nodeList[index].value).val());
				buNode["magnitudeBu"] = AJS.$('#bu_magnitude_' + nodeList[index].value).val();
				}
				var group = AJS.$('#bu_assignee_' + nodeList[index].value + '-field').attr('isGroup');
				if(group == "true"){
					buNode["assigneeType"] = 2;
				}else{
					buNode["assigneeType"] = 1;
				}				
				buNode["issueType"] = regChangePopUpIssueType;
				buObjList.push(buNode);
				
				if (AJS.$('#bu_assignee_' + nodeList[index].value + '-field').val() != ""){
					createEval = true;
				}
			}	
			  
			  console.log('eval flag.. '+ createEval);
				console.log('nodeList.length.. '+ nodeList.length);
				if (!createEval && nodeList.length > 0){
						if (regChangePopUpIssueType == "Evaluate Impact" || regChangePopUpIssueType == "Reg Change Action Plan"){
							console.log('Warnings here....');
												var dialog = new AJS.Dialog({
												width: 650, 
												height: 200, 
												id: "warning-dialog", 
												closeOnOutsideClick: true
											});
											
											dialog.addHeader("Warning");
											
											var html = '<div><span class="aui-icon aui-icon-small aui-iconfont-error"></span>Reg change process owner is not set of this Business Unit</div>';
											html += '<span id="loadingContinue" class="aui-icon aui-icon-wait"></span>';
											// add panel 1
											dialog.addPanel("Panel 1", html, "panel-body");
											dialog.get("panel:0").setPadding(10);
									
										
											dialog.addLink("Cancel", function (dialog) {
												//AJS.$("#action_id_71").attr("href","#");
												dialog.remove();
												return false;
											}, "#");
											
											dialog.show();
											return;			
						
									  }
								}
			
			
			
			
				console.log('payload'  + buObjList.length);
				console.log('buObjList type.. '+ buObjList[0].issueType);
				 AJS.$.ajax({
					url: "/casemanagement/rest/predictapi/latest/issues",
					type: 'POST',
					dataType: 'json',
					 contentType:"application/json; charset=utf-8",
					data: JSON.stringify(buObjList),
					async: false,
					success: function(data) {
						if(regChangePopUpIssueType == "Evaluate Impact"){
							var aTag = document.createElement('a');
							aTag.setAttribute('href',eIURI);
							aTag.className = "aui-button toolbar-trigger issueaction-workflow-transition";
							aTag.click();
				
						}else{	
							JIRA.Issue.reload();
						}	
					} 
				 });
				 AJS.$("#buContentDiv").contents().remove();
			AJS.dialog2("#demo-dialog").hide();
		})


	}

		AJS.$("#action_id_11,#action_id_81,#action_id_61").click(function(){
			AJS.$("#headingTitle").html("Create Regulatory Action Plan");
			AJS.$("#headingTitle").attr("issueType","Reg Change Action Plan");
			regChangePopUpIssueType = "Reg Change Action Plan";
			AJS.$.ajax({
				url: "/treeapi/rcm/actionplan/instruction/" + cm_selectedProjectKey ,
				type: 'get',
				dataType: 'json',
				success: function(data) {
					actionPlanInstructions = data.description;
					preparePopup();
					AJS.dialog2("#demo-dialog").show();
				} 
		});
			
		})

		AJS.$("#action_id_21").click(function(){
			AJS.$("#headingTitle").html("Create Evaluate Impact");
			AJS.$("#headingTitle").attr("issueType","Evaluate Impact");
			regChangePopUpIssueType = "Evaluate Impact";
			AJS.$.ajax({
				url: "/treeapi/rcm/evaluateimpact/instruction/" + cm_selectedProjectKey ,
				type: 'get',
				dataType: 'json',
				success: function(data) {
					actionPlanInstructions = data.description;
					preparePopup();
					AJS.dialog2("#demo-dialog").show();
				} 
			});
			
		})	
		
	})
		function enableControl(buId){
			if(AJS.$('#bu_assignee_' + buId + '\\-field').attr('isGroup') == "false"){
				AJS.$('#bu_assignee_' + buId + '\\-field').removeAttr('disabled');
			}	
			AJS.$('#duedate_'+ buId).removeAttr('disabled');
		}

		function disableControl(buId){
			AJS.$('#bu_assignee_' + buId + '\\-field').attr('disabled','disabled');
			AJS.$('#duedate_'+ buId).attr('disabled','disabled');
		}

	function createSingleUserPicker(elementId,defaultUser,defaultUserWithKey) {
		$assigneeComponent = new AJS.SingleSelect({
			element: $("#" + elementId),
			submitInputVal: true,
			showDropdownButton: false,
			errorMessage: AJS.format("There is no such user \'\'{0}\'\'.", "'{0}'"),
			ajaxOptions: {
				url:  AJS.contextPath() + "/rest/api/2/user/picker",
				query: true, // keep going back to the sever for each keystroke
				data: function (query) {
					return {
						query: query + "@" + cm_selectedProjectKey,
					}
				},
				formatResponse: JIRA.UserPickerUtil.formatResponse
			}
		});
		$assigneeComponent.setSelection(new AJS.ItemDescriptor({
				value: defaultUserWithKey,
				label: defaultUser,
				icon: ""
		}));
	}
	function createMagnitudeSelector(elementId){
	if ($("#"+elementId).length > 0 ){
	AJS.$.ajax({
				url: "/treeapi/rcm/magnitudes/" + cm_selectedProjectKey ,
				type: 'get',
				dataType: 'json',
				success: function(data) {
				console.log('got mag data');	
				var results = data.results;
					var arr = [];
					$('#'+elementId).find('option').remove();
					$('#'+elementId).append($("<option></option>"));
						for(var i = 0; i < results.length; i++) {
							arr.push({id: results[i].id, text: results[i].text});
						}
					$.each(arr, function(key, value) {  
							$('#'+elementId)
								.append($("<option></option>")
									   .attr("value",value.id)
									   .text(value.text));
						});

				} 
			});
	   }
	} 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");