Merge "Refactor getInnerDecisionApply function"
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / DCAEMicroServicePolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
22     $("#dialog").hide();
23     
24     $scope.policyNavigator;
25     $scope.isCheck = false;
26     $scope.savebutton = true;
27     $scope.refreshCheck = false;
28     
29     var layer = 0;
30     
31     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
32         $scope.temp.policy = {
33                         policyType : "Config",
34                         configPolicyType : "Micro Service"
35         }
36     };
37     
38     $scope.refresh = function(){
39         if($scope.refreshCheck){
40                 $scope.policyNavigator.refresh();
41         }
42         $scope.modal('createNewPolicy', true);
43         $scope.temp.policy = "";
44     };
45     
46     $scope.modal = function(id, hide) {
47         return $('#' + id).modal(hide ? 'hide' : 'show');
48     };
49     
50     $('#ttlDate').datepicker({
51         dateFormat: 'dd/mm/yy',
52         changeMonth: true,
53         changeYear: true,
54         onSelect: function(date) {
55                 angular.element($('#ttlDate')).triggerHandler('input');
56         }
57     });
58     
59         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
60                 if ($scope.temp.policy.configName == undefined){
61                         $scope.isCheck = false;
62                 }else{
63                         $scope.isCheck = true;
64                 }
65         }else {
66                 $scope.isCheck = false;
67         }
68                 
69         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
70                 var j = data;
71                 $scope.data = JSON.parse(j.data);
72                 console.log($scope.data);
73                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
74                 console.log($scope.onapNameDictionaryDatas);
75         }, function (error) {
76                 console.log("failed");
77         });
78
79         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
80                 var j = data;
81                 $scope.data = JSON.parse(j.data);
82                 console.log($scope.data);
83                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
84                 console.log($scope.priorityDatas);
85         }, function (error) {
86                 console.log("failed");
87         });
88
89         PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
90                 var j = data;
91                 $scope.data = JSON.parse(j.data);
92                 console.log($scope.data);
93                 $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
94                 console.log($scope.groupPolicyScopeListDatas);
95         }, function (error) {
96                 console.log("failed");
97         });
98
99         PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
100                 var j = data;
101                 $scope.data = JSON.parse(j.data);
102                 console.log($scope.data);
103                 console.log("$scope.data.microServiceConfigNameDictionaryDatas : " + $scope.data.microServiceConfigNameDictionaryDatas);
104                 if($scope.data.microServiceConfigNameDictionaryDatas){
105                     $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
106                 }
107                 console.log($scope.microServiceCongigNameDictionaryDatas);
108         }, function (error) {
109                 console.log("failed");
110         });
111
112         PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
113                 var j = data;
114                 $scope.data = JSON.parse(j.data);
115                 console.log($scope.data);
116                 $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
117                 console.log($scope.microServiceLocationDictionaryDatas);
118         }, function (error) {
119                 console.log("failed");
120         });
121
122         PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
123                 var j = data;
124                 $scope.data = JSON.parse(j.data);
125                 console.log($scope.data);
126                 var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
127                 var unique = {};
128                 var uniqueList = [];
129                 for(var i = 0; i < inputModelList.length; i++){
130                         if(typeof unique[inputModelList[i]] == "undefined"){
131                                 unique[inputModelList[i]] = "";
132                                 uniqueList.push(inputModelList[i]);
133                         }
134                 }
135                 $scope.microServiceModelsDictionaryDatas = uniqueList;
136                 console.log($scope.microServiceModelsDictionaryDatas);
137         }, function (error) {
138                 console.log("failed");
139         });
140
141         PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
142                 var j = data;
143                 $scope.data = JSON.parse(j.data);
144                 console.log($scope.data);
145                 $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
146                 console.log($scope.dcaeUUIDDictionaryDatas);
147         }, function (error) {
148                 console.log("failed");
149         });
150
151         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
152                 var j = data;
153                 $scope.data = JSON.parse(j.data);
154                 console.log($scope.data);
155                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
156                 console.log($scope.riskTypeDictionaryDatas);
157         }, function (error) {
158                 console.log("failed");
159         });
160
161         PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
162                 var j = data;
163                 $scope.data = JSON.parse(j.data);
164                 console.log($scope.data);
165                 $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
166                 console.log($scope.microServiceAttributeDictionaryDatas);
167         }, function (error) {
168                 console.log("failed");
169         });
170             
171
172          $scope.choices = [];
173          $scope.attributeDatas = [{"attributes" : $scope.choices}];
174          addNewChoice = function(value) {
175                  console.log("input key : " + value);
176                  var isFoundInRuleData = false;
177                  if(value != undefined){
178                         if (value.startsWith('div.')){
179                                 value = value.replace('div.','');
180                         }
181                         
182                         console.log(" document.getElementById : div."+value);
183                         var parentElement = document.getElementById("div."+value);
184                         console.log("parentElement : " + parentElement);
185                         var div = document.getElementById(value+"@0");
186                         if(div != null){
187                                 var clone = div.cloneNode(true); 
188                                 var addElement = parentElement.childElementCount;
189                                 clone.id = ''+value+'@'+addElement;
190                                 clone.value = '';
191                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
192                                         if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){  // Only append child if its value found in ruleData or edit mode
193                                                 if($scope.temp.policy.ruleData[clone.id]){
194                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
195                                                     isFoundInRuleData = true;
196                                                 }
197                                                 console.log("  clone.value :" +  clone.value);
198                                                 console.log(" clone.id :" + clone.id);
199                                                 if(!isFoundInRuleData && isInitViewEdit){
200                                                         return;
201                                                 }
202                                                 if(!clone.className.includes("child_single")){
203                                                    clone.className += ' child_single'; //here cloned is single element
204                                                 }
205                                                 document.getElementById("div."+value).appendChild(clone);
206                                                 plainAttributeKeys.push(''+value+'@'+addElement);
207                                         }
208                                 }else{ //not view or edit
209                                         if(!clone.className.includes("child_single")){
210                                             clone.className += ' child_single'; //here cloned is single element
211                                         }
212                                         document.getElementById("div."+value).appendChild(clone);
213                                         plainAttributeKeys.push(''+value+'@'+addElement);
214                                 }
215                         }else{
216                                 
217                                 if(parentElement == null){
218                                         return;
219                                 }
220                                 div = document.getElementById("div."+value+"@0");
221                                 if(div){
222                                         
223                                         if(!div.className.includes('children_group border')){
224                                                 layer++;
225                                                 if(layer > 4){ 
226                                                         layer = 1
227                                                 };
228                                     div.className += ' children_group border' + layer; //here is div with a group of children.
229                                         }
230                                 }
231                                 var childElement = parentElement.firstElementChild;
232                                 var countParent = parentElement.childElementCount;
233                                 var childElementString = childElement.innerHTML;
234                                 var find = value+"@0";
235                                 var re = new RegExp(find, 'g');
236                                 childElementString = childElementString.replace(re,value+'@' + countParent);
237                                 var clone = childElement.cloneNode(true);
238                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
239                             var childId = parentElement.childNodes[ii].id;
240                             if(ii = parentElement.childNodes.length){
241                                 var childnewId = childId.slice(0, -1);
242                                 var count = childId.slice(-1);
243                             }
244                         }
245                                 var countvalue = parseInt(count) + 1;
246                                 clone.id = childnewId+countvalue;
247                                 clone.value = '';
248                                 clone.innerHTML=childElementString;
249                                 document.getElementById("div."+value).appendChild(clone);
250                                 var selects = clone.getElementsByTagName("select");
251                                 var inputs = clone.getElementsByTagName("input");
252                                 var removeValues = [];
253                                 for(var i=0; i<inputs.length; i++){
254                                         if ($scope.temp.policy.ruleData!=undefined){
255                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
256                                                 console.log("  checkValue.value :" +  checkValue);
257                                                 console.log(" inputs["+i+"].id :" + inputs[i].id);
258                                                 if (checkValue!=undefined && checkValue != "undefined"){
259                                                         document.getElementById(inputs[i].id).value = checkValue;
260                                                                 plainAttributeKeys.push(inputs[i].id);
261                                                 } else {
262                                                         plainAttributeKeys.push(inputs[i].id);
263                                                 }
264                                         }else {
265                                                 plainAttributeKeys.push(inputs[i].id);
266                                         }
267                                 }
268                                 
269                                 for(var i=0; i<selects.length; i++){
270                                         if ($scope.temp.policy.ruleData!=undefined){
271                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
272                                                 if (checkValue!=undefined && checkValue!="undefined"){
273                                                         if($scope.temp.policy.ruleData != null){
274                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
275                                                                 var option = document.createElement('option');
276                                                                 option.setAttribute('value', checkValue);
277                                                                 option.appendChild(document.createTextNode(checkValue));
278                                                                 document.getElementById(selects[i].id).appendChild(option);
279                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
280                                                                 plainAttributeKeys.push(selects[i].id);
281                                                         }
282                                                 } else {
283                                                         plainAttributeKeys.push(selects[i].id);
284                                                 }
285                                         }else {
286                                                 plainAttributeKeys.push(selects[i].id);
287                                         }
288                                 }
289                                 
290                                 for (var k=0; k<removeValues.length; k++){
291                                         var elem = document.getElementById(removeValues[k]);
292                                         elem.parentNode.removeChild(elem);
293                                 }
294                                 var ele = angular.element(document.getElementById("div."+value));
295                         $compile(ele.contents())($scope)
296                         }
297                  }
298          };
299          
300         
301          removeChoice = function(value) {
302                  console.log(value);
303                  if(value != undefined){
304                          var c = document.getElementById("div."+value).childElementCount;
305                          
306                          if(c == 1){
307                                  Notification.error("The original one is not removable.");
308                                  return;
309                          }      
310                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
311                  }
312          };
313          
314          function findVal(object, key) {
315                     var value;
316                     Object.keys(object).some(function(k) {
317                         if (k === key) {
318                             value = object[k];
319                             return true;
320                         }
321                         if (object[k] && typeof object[k] === 'object') {
322                             value = findVal(object[k], key);
323                             return value !== undefined;
324                         }
325                     });
326                     return value;
327         }
328          
329          $scope.pullVersion = function(serviceName) {
330                  console.log(serviceName);
331                  if(serviceName != undefined){
332                          var uuu = "policyController/getModelServiceVersioneData.htm";
333                          var postData={policyData: serviceName};
334                          $.ajax({
335                                  type : 'POST',
336                                  url : uuu,
337                                  dataType: 'json',
338                                  contentType: 'application/json',
339                                  data: JSON.stringify(postData),
340                                  success : function(data){
341                                          $scope.$apply(function(){
342                                                  $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
343                                          });
344                                  },
345                                  error : function(data){
346                                          alert("Error While Retriving the Template Layout Pattren.");
347                                  }
348                          });             
349                  }
350          };
351     
352     var splitDash = '-';
353         var splitEqual = '=';
354         var splitComma = ',';
355         var splitcolon = ':';
356         var splitsemicolon = ";";
357         var splitEnum = "],";
358         var plainAttributeKeys = [];
359         var matching = [];
360         var enumKeyList = [];
361         var dictionaryList = [];
362         var dictionaryNameList = [];
363         var isInitViewEdit = false;
364     $scope.addDataToFields = function(serviceName, version){
365         if(serviceName != null && version !=null){
366                 var service=serviceName+"-v"+version;
367                 var myNode = document.getElementById("DynamicTemplate");
368                 myNode.innerHTML = '';
369             var uuu = "policyController/getDCAEMSTemplateData.htm";
370             var postData={policyData: service};
371             
372             console.log("service: " +service);
373             
374             var dataOrderInfo = "";
375             
376             booleanTrueElements = [];
377
378             document.getElementById("msPolicyloader").style.visibility = "visible";
379             
380             $.ajax({
381                 type : 'POST',
382                 url : uuu,
383                 dataType: 'json',
384                 contentType: 'application/json',
385                 data: JSON.stringify(postData),
386                 success : function(data){
387                         
388                         document.getElementById("msPolicyloader").style.visibility = "hidden";
389                         
390                     $scope.$apply(function(){
391                         var plainAttributeKeys = [];
392                         $scope.dcaeModelData = data[0].dcaeModelData;
393                         $scope.dcaeJsonDate = data[0].jsonValue;
394                         $scope.dataOrderInfo = null;
395                         $scope.dataOrderInfo = data[0].dataOrderInfo;
396                         console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
397                         console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);   
398                         
399                         if(data[0].allManyTrueKeys){
400                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
401                         }
402                         console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);     
403                         var attributes = $scope.dcaeModelData.attributes;                       
404                         console.log("attributes: " +attributes);                        
405                         var refAttributes = $scope.dcaeModelData.ref_attributes;
406                         var subAttributes =     $scope.dcaeModelData.sub_attributes;                            
407                         console.log("subAttributes: " + subAttributes); 
408                         console.log("refAttributes: " + refAttributes); 
409                         var headDefautlsData  = data[0].headDefautlsData;
410                         if(headDefautlsData != null){
411                                          $scope.temp.policy.onapName = headDefautlsData.onapName;
412                                          $scope.temp.policy.guard = headDefautlsData.guard;
413                                          $scope.temp.policy.riskType = headDefautlsData.riskType;
414                                          $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
415                                          $scope.temp.policy.priority = headDefautlsData.priority;
416                         }
417                         
418                         var enumAttributes = $scope.dcaeModelData.enumValues;
419                         var annotation = $scope.dcaeModelData.annotation;
420                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
421
422                         if (annotation == null || annotation.length<1){
423                                 $scope.isCheck = true;
424                         }else {
425                                 $scope.isCheck = false;
426                                 var annoationList = annotation.split(splitComma);
427                                 for (k = 0; k < annoationList.length; k++){
428                                         var splitAnnotation = annoationList[k].split(splitEqual);
429                                         if (splitAnnotation[1].includes("matching-true")){
430                                                 matching.push(splitAnnotation[0].trim());
431                                         }
432                                 }
433
434                         }
435
436                         if (dictionary!= null && dictionary.length>1){
437                                 for (m=0; m < dictionary.length; m += 1){
438                                         var keyCompare = dictionary[m].name;
439                                         var valueCompare = dictionary[m].value;
440                                         var valueModel = dictionary[m].modelName;
441                                         var conpairService = serviceName;
442                                         if (valueModel.includes('-v')){
443                                                 conpairService = service;
444                                         }
445                                         if(valueModel.localeCompare(conpairService) == 0){
446                                                 console.log(valueCompare);      
447                                                 dictionaryList.push(dictionary[m]);
448                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
449                                                         dictionaryNameList.push(dictionary[m].name)
450                                                 }
451                                         }
452                                 }
453                         }
454
455                                 $scope.temp.policy.ruleGridData = [];
456                                 
457                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
458                                         dataOrderInfo = $scope.dataOrderInfo;
459                                 }
460                                 
461                                 $scope.jsonLayout($scope.dcaeJsonDate);
462                                 
463                     });
464                     
465                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
466                         isInitViewEdit = true;
467                         var checkData = [];
468                         var data = [];
469                             // If ruleData contains extra elements created by clicked add button 
470                             console.log("$scope.temp.policy.ruleData:" + $scope.temp.policy.ruleData);
471                                 if($scope.temp.policy.ruleData != null){
472                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
473                                         propNames.forEach(function(name) {
474                                                 data.push(name);
475                                         });
476                                         
477                                         var extraElements = data;
478                                         
479                                             if(plainAttributeKeys != null){
480                                                         for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
481                                                                 var newValue = plainAttributeKeys[b].split("*");
482                                                                 for(var a = 0; a < data.length; a++){
483                                                                         if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
484                                                                                 extraElements.splice(a, 1);
485                                                                         }
486                                                                 }
487                                                 }
488                                                 
489                                                 //--- Populate these extra elements created by clicked add button 
490                                                 for(var a = 0; a < extraElements.length; a++){                                  
491                                                         if(extraElements[a].includes("@")){
492                                                                 var index = extraElements[a].lastIndexOf("@");
493                                                                 if(index > 0){
494                                                                     // Get the number after @
495                                                                     var n = getNumOfDigits(extraElements[a], index+1);
496                                                                                         
497                                                                         var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
498                                                                         console.log("key: " + key);
499                                                                         checkData.push(key);
500                                                                 }
501                                                         }
502                                                 }
503                                                 var unique = checkData.filter(onlyUnique);
504                                                 var parentLevelElements = [];
505                                                 if(unique){
506                                                         //--- get all root level exta elments first (only contains one "@")
507                                                         for(var i =0; i < unique.length; i++){
508                                                                 var firstIndex = unique[i].indexOf("@");
509                                                                 var lastIndex = unique[i].lastIndexOf("@");
510                                                                 if(firstIndex == lastIndex){    
511                                                                         var newKey = unique[i].substring(0, firstIndex);
512                                                                         console.log("root element: " + newKey);
513                                                                         parentLevelElements.push(newKey);
514                                                                         unique[i] = "*processed*";
515                                                                 }
516                                                         }                                                       
517                                                 }
518                                                 
519                                                 
520                                                 for (var i = 0; i < $scope.labelManyKeys.length; i++) {
521                                                     var label = $scope.labelManyKeys[i];                                                            
522                                                     if(parentLevelElements){
523                                                         for (var k = 0; k < parentLevelElements.length; k++){
524                                                                 if(label == parentLevelElements[k]){
525                                                                         addNewChoice(label);
526                                                                 }
527                                                         }                                                                       
528                                                     }                                                                           
529                                                 }
530                                                 
531                                                 //if no layout order info, keep the process as before
532                                                 if(!dataOrderInfo){
533                                                         for(var i =0; i < unique.length; i++){
534                                                                 if(unique[i] != "*processed*"){
535                                                                         var index = unique[i].lastIndexOf("@");
536                                                                         var newKey = unique[i].substring(0, index);
537                                                                         console.log("newKey: " + newKey);       
538                                                                         
539                                                                         var newElement = document.getElementById("div."+unique[j]);
540                                                                         //check weather it has been created already
541                                                 if(newElement != null){
542                                                         continue;
543                                                 }else{
544                                                         newElement = document.getElementById(unique[j]);
545                                                         if(newElement != null){
546                                                                 continue;
547                                                         }
548                                                 } 
549                                                 
550                                                                         if(newKey){
551                                                                                 addNewChoice(newKey);
552                                                                         }
553                                                                 }
554                                                         }
555                                                 }else{
556                                                                 //---reset to default
557                                                                 dataOrderInfo = [];
558                                                                 $scope.labelManyKeys = [];
559                                                                 
560                                                                 //---process none labels
561                                                                 for (var j = 0; j < unique.length; j++){
562                                                                         if(unique[j] != "*processed*"){
563                                                                                 // if not created yet
564                                                                                 if(!document.getElementById(unique[j])){
565                                                                                         var index = unique[j].lastIndexOf("@");
566                                                                                         var newKey = unique[j].substring(0, index);
567                                                                                         
568                                                                                         var newElement = document.getElementById("div."+unique[j]);
569                                                                                         
570                                                                                         //check weather it has been created already
571                                                         if(newElement != null){
572                                                                 continue;
573                                                         }else{
574                                                                 newElement = document.getElementById(unique[j]);
575                                                                 if(newElement != null){
576                                                                         continue;
577                                                                 }
578                                                         } 
579                                                         //if not created yet, then create it.                                                                                           
580                                                                                         addNewChoice(newKey);
581                                                                                    
582                                                                                 }
583                                                                         }
584                                                                 }
585                                                         }
586                                             }
587                                 }
588
589                     }
590                     var ele = angular.element(document.getElementById("DynamicTemplate"));
591                         $compile(ele.contents())($scope);
592                     $scope.$apply();
593                     isInitViewEdit = false;                   
594                     
595                 },
596                 error : function(data){
597                     alert("Error While Retriving the Template Layout Pattren.");
598                 }
599             });
600
601         }
602     };
603     
604     function getNumOfDigits(str_value, index){
605                 // Get the number after @
606                 var str = str_value.substring(index, str_value.length); 
607                 var c = '';
608                 var n = 0;
609                 for (var x = 0; x < str.length; x++){                                                                   
610                     c = str.charAt(x);
611                             if(!isNaN(c)){ 
612                 n++;                                                     
613                     }else{
614                 break;
615             }
616                 }
617                 return n;
618     }
619     
620     function getDictionary(attribute){
621         var dicName = attribute;
622         if(attribute){
623            if(attribute.includes(":")){
624                    dicName = attribute.split(":")[0];
625            }
626         }
627             var dictionaryRegExp = new RegExp(dicName);
628             listemunerateValues = [];
629             if (dictionaryRegExp.test(dictionaryNameList)) {
630                         for (p=0; p < dictionaryList.length; p += 1) {
631                                 if (dicName == dictionaryList[p].name) {
632                                         listemunerateValues.push(dictionaryList[p].value);
633                                 }
634                         }
635             }
636             return listemunerateValues;
637     }
638     
639     function getList(attribute) {
640                 var enumName = attribute;
641                 console.log("In getList: attribute => " + attribute);
642                 if(attribute){
643                    if(attribute.includes(":")){
644                            enumName = attribute.split(":")[0];
645                    }
646                 }   
647             var baseEnum = $scope.dcaeModelData.enumValues;
648             var enumList = [];
649             if(baseEnum != null){
650                 enumList = baseEnum.split(splitEnum);
651             }
652                 var enumAttributes;
653                 var patternTest = new RegExp(enumName);
654                 for (k=0; k < enumList.length; k += 1){
655                         if(patternTest.test(enumList[k]) == true){
656                                 enumAttributes = enumList[k].trim();
657                 }
658         }
659
660          if(enumAttributes){
661                 enumAttributes = enumAttributes.replace("[", "");
662                 enumAttributes = enumAttributes.replace("]", "");
663                 enumAttributes = enumAttributes.replace(/ /g, '');
664                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
665                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
666                         //enumKeyList.push(attribute); 
667                 return listemunerateValues;
668          }
669          
670             return [];
671             }
672             
673             function getBooleanList(){
674                 var booleanList = [];
675                 booleanList.push(true);
676                 booleanList.push(false);
677                 return booleanList;
678             }
679             
680
681             function isArray(arrayTest) {
682                 return Object.prototype.toString.call(arrayTest) === '[object Array]';
683             }
684             var lableList = [];
685             
686             $scope.layOutElementList = [];
687             $scope.layOutOnlyLableList = [];
688             
689             var elementOrderNum = 0;
690             
691                 function deconstructJSON(layOutData, level , name) {
692
693                          var array = false;
694                          var label = level;
695                          var stringValue = "java.lang.String";
696                          var string = "string";
697                          var intValue = "int";
698                          var integerValue = "integer";
699                          var double = "double";
700                          var boolean = "boolean";
701                          var baseLevel = level;
702                          var list = "list";
703                          var String = "String";
704                          
705                          var attributekey = "";
706                          
707                         if (name.length > 1){
708                                 label = label + name + '.';
709                         }
710                         
711                     for (key in layOutData) {
712                         array = isArray(layOutData[key]);
713                         console.log("key: " + key , "value: " + layOutData[key]);
714                 
715                         if (!!layOutData[key] && typeof(layOutData[key])=="object") {
716                                 
717                                 if (array==false && key!=="0"){
718                                         
719                                         if($scope.dataOrderInfo){
720                                             var labelObject = {"label" : key, "level" : label, "array" : array};
721                                             //save it to the list
722                                             $scope.layOutOnlyLableList.push(labelObject);
723                                             
724                                         }else {
725                                                 //call label layout
726                                                 $scope.labelLayout(label, key, array );
727                                         }
728                                         
729                                 }
730                                 
731                                 if (array == true && key!=0){
732                                         lableList.push(key);
733                                 }
734                                 
735                                 if (lableList.length > 0){
736                                         array = true;
737                                 }
738                                 if ( key==="0"){
739                                         var newKey = lableList.pop();
740                                         
741                                         if($scope.dataOrderInfo){
742                                                 
743                                                 var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
744                                                 //save it to the list
745                                                 $scope.layOutOnlyLableList.push(labelObject);
746                                                 
747                                         }else {
748                                                 //call label layout 
749                                             $scope.labelLayout(baseLevel, newKey, array );
750                                         }
751                                         
752                                         if (array){
753                                                 label = baseLevel + newKey + '@0.';
754                                         } else {
755                                                 label = baseLevel + newKey + '.';
756                                         }
757                                 }
758                                 deconstructJSON(layOutData[key] , label, key);
759                         } else {
760                                 var attirbuteLabel = label;
761                                 var defaultValue='';
762                                 var description='';
763                                 var isRequired = false;
764                                 if (layOutData[key].includes('defaultValue-')){
765                                         defaultValue = layOutData[key].split('defaultValue-')[1];
766                                 }
767                                 
768                                 if (layOutData[key].includes('description-')){
769                                         description = layOutData[key].split('description-')[1];
770                                 }                               
771                                 
772
773                                 if (key==="0"){
774                                         array = true;
775                                         attributekey = lableList.pop();
776                                         attirbuteLabel = baseLevel;
777                                 } else {
778                                         attributekey = key.split();
779                                 }
780                                 
781                                 if (layOutData[key].includes('required-true')){
782                                         isRequired = true;
783                                 }
784                                 
785                                 var subAttributes = $scope.dcaeModelData.sub_attributes;
786                                 
787                                 if(subAttributes){                                      
788                                         var jsonObject = JSON.parse(subAttributes);     
789                                         
790                                     var lablInfo = findVal(jsonObject, attributekey);
791                                         console.log("deconstructJSON:findValue : " + attributekey +": "+ lablInfo);
792                                         if (lablInfo){
793                                                 if(lablInfo.includes('required-true')){
794                                                         isRequired = true;
795                                                 }       
796                                                 if(lablInfo.includes('defaultValue-')){
797                                                         defaultValue = lablInfo.split('defaultValue-')[1];
798                                                 }
799                                                 
800                                                 if(lablInfo.includes('description-')){
801                                                         description = lablInfo.split('description-')[1];
802                                                 }
803                                                 
804                                         }else{                                  
805                                            var allkeys = Object.keys(jsonObject);
806                                            if(allkeys){
807                                                    for (var k = 0; k < allkeys.length; k++) {
808                                                           var keyValue = allkeys[k];
809                                                           console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
810                                                           if(jsonObject[keyValue]){
811                                                                  var tempObject = jsonObject[keyValue];
812                                                                  if(tempObject && tempObject[key]){
813                                                                  if (tempObject[key].includes('required-true')){
814                                                                         isRequired = true;
815                                                                  }      
816                                                                  
817                                                                  if(tempObject[key].includes('defaultValue-')){
818                                                                         defaultValue = tempObject[key].split('defaultValue-')[1];
819                                                                  }
820                                                                  
821                                                                  if(tempObject[key].includes('description-')){
822                                                                          description = tempObject[key].split('description-')[1];
823                                                                   }
824
825                                                                  }
826                                                           }
827                                                    }                                            
828                                            }                                    
829                                         } 
830                                 }
831                                 
832                                 var elementObject = {};
833                                 switch (layOutData[key].split(splitcolon)[0]){
834                                 
835                                         case stringValue:
836                                         case string:
837                                                 if($scope.dataOrderInfo){                                                       
838                                                         elementOrderNum++;
839                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
840                                                         $scope.layOutElementList.push(elementObject);
841                                                 }else{
842                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
843                                                 }
844                                                 break;                                          
845                                         case intValue: 
846                                         case integerValue: 
847                                                 if($scope.dataOrderInfo){
848                                                         elementOrderNum++;
849                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
850                                                         $scope.layOutElementList.push(elementObject);
851                                                 }else{
852                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
853                                                 }
854                                                 break;                                          
855                                         case double:
856                                                 if($scope.dataOrderInfo){
857                                                         elementOrderNum++;
858                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double",  "description":description};
859                                                         $scope.layOutElementList.push(elementObject);                                                   
860                                                 }else{
861                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
862                                                 }
863                                                 break;
864                                         case boolean:
865                                                 if($scope.dataOrderInfo){
866                                                         elementOrderNum++;
867                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
868                                                         $scope.layOutElementList.push(elementObject);
869                                                 }else{
870                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
871                                                 }
872                                                 break;
873                                         default:
874                                                 if (layOutData[key].includes('dictionary-')){
875                                                         var list = getDictionary(layOutData[key].split('dictionary-')[1]);
876                                                 }else{
877                                                         //--- get dropdown values from enumValues
878                                                         var list = getList(layOutData[key]);
879                                                 }
880                                                 if (list.length===0){ //not dropdown element
881                                                         if($scope.dataOrderInfo){
882                                                                 elementOrderNum++;
883                                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
884                                                                 $scope.layOutElementList.push(elementObject);
885                                                                 
886                                                         }else{
887                                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
888                                                         }                                                       
889                                                 }else{
890                                                         if($scope.dataOrderInfo){
891                                                                 elementOrderNum++;
892                                                                 elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
893                                                                 $scope.layOutElementList.push(elementObject);                                                           
894                                                         }else{
895                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
896                                                         }
897                                                 }
898                                                 break;
899                                 }
900                         }
901                     }
902                 }  
903                 
904                 
905             $scope.validContionalRequired = function(parentId) {
906                 console.log("ng-blur event: parentId : " + parentId);
907                 var c = document.getElementById(parentId).children;
908                 var i;
909                 var hasValue = false;
910                 for (i = 0; i < c.length; i++) {
911                         if(c[i].getAttribute("data-conditional")){
912                             console.log(c[i].getAttribute("data-conditional"));
913                             console.log(c[i].value);
914                             if(c[i].value != null && c[i].value.trim() != ""){
915                                 hasValue = true;
916                             }
917                         }
918                 }
919
920                     for (i = 0; i < c.length; i++) {
921                         if(c[i].getAttribute("data-conditional")){
922                                 if(hasValue){
923                                     c[i].setAttribute("required", true);
924                                 }else{
925                                         c[i].removeAttribute("required");
926                                 }
927                         }
928                     }           
929              }
930                                 
931             $scope.jsonLayout = function(layOutData){
932                 
933                    deconstructJSON(layOutData , "", "");
934                    
935                    var orderValue = $scope.dataOrderInfo;
936                    var layOutElementList = $scope.layOutElementList;
937                    var labelList = $scope.layOutOnlyLableList;
938                     
939                    //reset to default
940                    elementOrderNum = 0;
941                    $scope.layOutElementList = [];
942                    $scope.layOutOnlyLableList = [];
943                    
944                    // Only layout in order if order info provided
945                    if(orderValue){
946                            
947                            if(orderValue.includes("[")){
948                                   orderValue = orderValue.replace("[", "") ;
949                                   orderValue = orderValue.replace("]", "") ;
950                            }
951                            
952                            orderValue = orderValue.split(',') ;
953                            
954                            for (var i = 0; i < orderValue.length; i++) {
955                                    console.log("orderValue["+i+"]"+  orderValue[i]);
956                                    var key = orderValue[i].trim();
957                                  
958                                     //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
959                                    if(labelList){
960                                            for (var k = 0; k < labelList.length; k++){
961                                                    
962                                                   var label = labelList[k].label.toString().trim();
963                                                   var level = labelList[k].level.toString().trim();
964                                                   var array = labelList[k].array;
965                                                   
966                                                   if(key == label){                                                       
967                                                          $scope.labelLayout(level, label, array);
968                                                          //in case to have duplicate label names
969                                                          labelList[k].label = "*processed*";
970                                                          break;
971                                                   }
972                                            }
973                                    }
974                                    //--- then layout each element based on its order defined in YAML file
975                                    for (var j = 0; j < layOutElementList.length; j++) { 
976                                            
977                                            var attributekey = layOutElementList[j].attributekey.toString().trim();                                         
978                                         
979                                            if(key == attributekey){     
980
981                                                    var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
982                                                    var defaultValue = layOutElementList[j].defaultValue.toString().trim();
983                                                    var description = layOutElementList[j].description;
984                                                    var isRequired = layOutElementList[j].isRequired;
985                                                    
986                                                    console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
987                                                    console.log("layOutElementList[" +j+ "]: type:" + layOutElementList[j].type);
988                                                    if (layOutElementList[j].type == "dropBox"){ 
989                                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
990                                         
991                                                    }else{
992                                                             $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);    
993         
994                                                    }
995                                                    
996                                                    //in case to have duplicate attribute names
997                                                    layOutElementList[j].attributekey = "*processed*";
998                                                    break;
999                                            }
1000                                    }
1001                            }
1002                    }
1003             }
1004             
1005             
1006             $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType,  description){
1007                         $scope.temp.policy.ruleGridData.push(attibuteKey);                      
1008                 var br = document.createElement("BR");
1009                 
1010                 var label = document.createElement("Label");
1011                 var labeltext = null;
1012                 var requiredLabName = "";
1013                 if (matching.includes(attibuteKey)){
1014                         labeltext = document.createTextNode(attibuteKey + "*!");        
1015                         isRequired = true;  //set required as true for matching element
1016                 }else {
1017                         if(isRequired){
1018                                 requiredLabName = attibuteKey + " * ";
1019                                 labeltext = document.createTextNode(requiredLabName);
1020                         }else{
1021                             labeltext = document.createTextNode(attibuteKey);   
1022                         }
1023                 }
1024
1025                 
1026                 var divID = labelValue;
1027                 
1028                 if (labelValue.length  < 1){
1029                         divID = "DynamicTemplate";
1030                 }else if (labelValue.endsWith('.')){
1031                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1032                 }
1033                 
1034                 label.appendChild(labeltext);
1035                 
1036                 var textField = document.createElement("INPUT");
1037                 
1038                 textField.setAttribute("class" , "form-control");
1039                 if(dataType){
1040                         if(dataType == "double"){
1041                                 textField.setAttribute("type" , "number");
1042                                 textField.setAttribute("step" , "any");
1043
1044                         }else if(dataType == "boolean"){  //gw1218 testing boolean
1045                                 var booleanDiv = document.createElement("div");
1046
1047                                 booleanDiv.setAttribute("class" , "onoffswitch");
1048
1049                                 //var checkField = document.createElement("INPUT");
1050                                 textField.setAttribute("type" , "checkbox");
1051                                 textField.setAttribute("name" , "onoffswitch");
1052                                 textField.setAttribute("class" , "onoffswitch-checkbox");
1053                                 textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
1054                                 if(defaultValue.substring(0,defaultValue.indexOf(":")) == "true") {
1055                                         textField.setAttribute("checked" , true);
1056                                 }else{
1057                                         textField.removeAttribute("checked");
1058                                 }
1059
1060                                                 var booleanlabel = document.createElement("Label");
1061                                                 booleanlabel.setAttribute("class" , "onoffswitch-label");
1062                                                 booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
1063                                         
1064                                                 var span1 = document.createElement("span");
1065                                                 span1.setAttribute("class" , "onoffswitch-inner");
1066                                                 
1067                                                 var span2 = document.createElement("span");
1068                                                 span2.setAttribute("class" , "onoffswitch-switch"); 
1069                                                 
1070                                                 
1071                                                 booleanlabel.appendChild(span1);        
1072                                                 booleanlabel.appendChild(span2);        
1073                                                 booleanDiv.appendChild(textField);      
1074                                                 booleanDiv.appendChild(booleanlabel);    
1075                                                 
1076                                                 document.getElementById(divID).appendChild(label);  
1077                                                 document.getElementById(divID).appendChild(booleanDiv);         
1078
1079                                                 //return;
1080                            } else{
1081                               textField.setAttribute("type" , dataType);
1082                            }
1083                            
1084                                 
1085
1086                 }
1087                 
1088                 if(dataType != "boolean"){
1089                         textField.setAttribute("style" , "width:300px;");
1090                         textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1091                         if(description && description != "null"){
1092                                 textField.setAttribute("title", description);
1093                         }
1094                 }
1095
1096                 var checkKey;
1097                 var id = "";
1098                 if(attributeManyKey){
1099                         checkKey = labelValue + attibuteKey+'@0';
1100                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
1101                         var divTag = document.createElement("div");
1102                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
1103                         var addButton = document.createElement("BUTTON");
1104                         var buttonaddLabel = document.createTextNode("+");       
1105                         addButton.appendChild(buttonaddLabel); 
1106                         addButton.setAttribute("id", labelValue + attibuteKey);
1107                         addButton.setAttribute("class", "btn btn-add-remove");
1108                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
1109                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1110                         var removeButton = document.createElement("BUTTON");
1111                         var buttonremoveLabel = document.createTextNode("-");       
1112                         removeButton.appendChild(buttonremoveLabel); 
1113                         removeButton.setAttribute("class", "btn btn-add-remove");
1114                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue + attibuteKey+'");');
1115                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1116                         document.getElementById(divID).appendChild(addButton); 
1117                         document.getElementById(divID).appendChild(removeButton); 
1118                         document.getElementById(divID).appendChild(label); 
1119                         id = "div."+labelValue+attibuteKey;
1120                         //var divTag = document.createElement("div");
1121                         divTag.setAttribute("id", id); 
1122                         document.getElementById(divID).appendChild(divTag);
1123                         textField.className += ' first_child';  
1124                         if(isRequired){
1125                                 textField.setAttribute("required", "true");
1126                         }       
1127                         
1128                         divTag.appendChild(textField);                  
1129                         document.getElementById(divID).appendChild(divTag); 
1130                         
1131                 }else if (dataType != "boolean"){
1132                         checkKey = labelValue + attibuteKey;
1133                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
1134                         if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
1135                                 if(requiredLabName.includes("*") || isRequired){
1136                                         textField.setAttribute("required", "true");
1137                                 }
1138                         }else if (document.getElementById(divID).hasAttribute('data-conditional')){
1139                                 if(requiredLabName.includes("*")){                                      
1140                                         var requiredNode = document.createElement('span');
1141                                         requiredNode.setAttribute("class", "mstooltip");
1142                                         requiredNode.textContent = "?";
1143                                         label.appendChild(requiredNode);
1144                                         
1145                                         var requiredNodeToolTip = document.createElement('span');
1146                                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
1147                                         requiredNodeToolTip.textContent = "Conditional Required";
1148                                         requiredNode.appendChild(requiredNodeToolTip);
1149                                         
1150                                         textField.setAttribute("data-conditional", divID);
1151                                         textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1152                                 }
1153                         }
1154             
1155                         document.getElementById(divID).appendChild(label);  
1156                         document.getElementById(divID).appendChild(textField);  
1157                         document.getElementById(divID).appendChild(br); 
1158
1159                 }
1160
1161                 if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
1162                         var firstChild_Id = divID.split("@0")[0];
1163                         var firstChild_element = document.getElementById(firstChild_Id);
1164                         if(firstChild_element){
1165                         
1166                                 if(!firstChild_element.className.includes('children_group border')){
1167                                         layer++;
1168                                         if(layer > 4){ 
1169                                                 layer = 1
1170                                         };
1171                                         firstChild_element.className += ' children_group border' + layer; //here is div with a group of children.
1172                                 }
1173                         }
1174                 }
1175                 console.log('firstChild_Id: ' + firstChild_Id);
1176                 console.log('divID: ' + divID);
1177                 
1178                 if(dataType != "boolean" && defaultValue.length > 0){   
1179                         if(defaultValue.includes(":")){
1180                                 defaultValue = defaultValue.split(":")[0];
1181                                 if(defaultValue === "NA") {
1182                                         defaultValue = "";
1183                                 }                               
1184                         }
1185                         if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
1186                         document.getElementById(checkKey).value = defaultValue;
1187                         }
1188                 }
1189                 
1190                 if($scope.temp.policy.ruleData != null){
1191                         //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1192                         if (attributeManyKey){
1193                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
1194                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
1195                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
1196                                 }
1197                         }else{
1198                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
1199                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
1200                                 }
1201                         }
1202                 } 
1203                 
1204                 if (dataType != "boolean"){
1205                     plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);     
1206                 }else{
1207                     plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");    
1208                 }
1209     };
1210   
1211     $scope.labelManyKeys = [];
1212     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
1213                 var label = document.createElement("Label")
1214                 var divID = labelValue;
1215                 if (labelValue.endsWith('.')){
1216                         var workingLabel = labelValue.substring(0, labelValue.length-1);
1217                 }else {
1218                         var workingLabel = labelValue;
1219                 }
1220                 
1221                 if (labelValue.length  < 1){
1222                         divID = "DynamicTemplate";
1223                 } else if (labelValue.endsWith('.')){
1224                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1225                 }
1226                 
1227                 var subAttributes = $scope.dcaeModelData.sub_attributes;
1228             var jsonObject = JSON.parse(subAttributes); 
1229             var lablInfo = findVal(jsonObject, lableName);
1230                 console.log("findValue : " + lableName +": "+ lablInfo);
1231                 var star = "";
1232                 var required = null;
1233                 if(lablInfo){
1234                         if(typeof lablInfo === 'string' ){
1235                            if(lablInfo.includes("required-true")){
1236                                    star = " *";
1237                                    required = true;
1238                             }else if (lablInfo.includes("required-false")){
1239                                    required = false
1240                             }
1241                         }
1242                 }
1243                 
1244                 var labeltext = document.createTextNode(lableName + star);
1245         
1246                 label.appendChild(labeltext);
1247
1248
1249                 if(labelManyKey){
1250                         var addButton = document.createElement("BUTTON");
1251                         var buttonLabel = document.createTextNode("+");       
1252                         addButton.appendChild(buttonLabel); 
1253                         addButton.setAttribute("class", "btn btn-add-remove");
1254                         addButton.setAttribute("onclick" ,  'addNewChoice("'+labelValue + lableName+'");');
1255                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1256                         var removeButton = document.createElement("BUTTON");
1257                         var buttonremoveLabel = document.createTextNode("-");       
1258                         removeButton.appendChild(buttonremoveLabel); 
1259                         removeButton.setAttribute("class", "btn btn-add-remove");
1260                         removeButton.setAttribute("onclick" ,  'removeChoice("'+labelValue +lableName+'");');
1261                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
1262                         document.getElementById(divID).appendChild(addButton); 
1263                         document.getElementById(divID).appendChild(removeButton);
1264                         document.getElementById(divID).appendChild(label);
1265                         var id = "div."+labelValue+lableName;
1266                         var divTag = document.createElement("div");
1267                         divTag.setAttribute("id", id); 
1268                         document.getElementById(divID).appendChild(divTag);
1269                         
1270                         var divTag = document.createElement("div");
1271                         divTag.setAttribute("id", id +'@0');  
1272                         
1273                         if(!divTag.className.includes('children_group border')){
1274                                 layer++;
1275                                 if(layer > 4){ 
1276                                         layer = 1
1277                                 };
1278                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1279                         }
1280                         if(required){
1281                            divTag.setAttribute("required", required);  
1282                         }else if(required == false){
1283                            divTag.setAttribute("data-conditional", "yes");  
1284                         }
1285                         
1286                         document.getElementById(id).appendChild(divTag);
1287                         
1288                         $scope.labelManyKeys.push(lableName);
1289                         
1290                 }else{
1291                         var divTag = document.createElement("div");
1292                         divTag.setAttribute("id", "div."+labelValue+lableName);
1293                         
1294                         if(!divTag.className.includes('children_group border')){
1295                                 layer++;
1296                                 if(layer > 4){ 
1297                                         layer = 1
1298                                 };
1299                                 divTag.className += ' children_group border' + layer; //here is div with a group of children.
1300                         }
1301                         if(required){
1302                             divTag.setAttribute("required", required);  
1303                         }else if(required == false){
1304                                 divTag.setAttribute("data-conditional", "yes");  
1305                         }  
1306                         document.getElementById(divID).appendChild(label);  
1307                         document.getElementById(divID).appendChild(divTag);                     
1308                 }
1309     };
1310
1311     $scope.dropBoxLayout = function(labelLevel, attributeName, many , defaultValue, listemunerateValues, isRequired, description){
1312                         var br = document.createElement("BR");
1313                 
1314                         if (labelLevel.length  < 1){
1315                                         var divID = "DynamicTemplate";
1316                         } else if (labelLevel.endsWith('.')){
1317                                         var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
1318                         }       
1319                 
1320                 
1321                         var label = document.createElement("Label")
1322                         
1323                         var refAttributes = $scope.dcaeModelData.ref_attributes;
1324                         if(isRequired != true && refAttributes){ //check refAttributes also             
1325                                         var refAttributesList = refAttributes.split(splitComma);
1326                                         for (k = 0; k < refAttributesList.length; k++){
1327                                         var refAttribute = refAttributesList[k].split(splitEqual);                      
1328                                         if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
1329                                                 isRequired = true;
1330                                         }
1331                                         }
1332                         }
1333                         
1334                         if (matching.includes(attributeName)){
1335                                 var labeltext = document.createTextNode(attributeName + "*!");
1336                                 label.appendChild(labeltext);
1337                                 isRequired = true;  //set required as true for matching element
1338                         }else {
1339                                 var labeltext = document.createTextNode(attributeName);         
1340                                 if(isRequired){
1341                                     var requiredLabName = attributeName+ " * ";
1342                                         labeltext = document.createTextNode(requiredLabName);
1343                                 }else{
1344                                     labeltext = document.createTextNode(attributeName); 
1345                                 }
1346                         
1347                             label.appendChild(labeltext);               
1348                         }
1349                         label.appendChild(labeltext);
1350                         // if this field is required, but its parent is not required
1351                         if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
1352                                 var requiredNode = document.createElement('span');
1353                                 requiredNode.setAttribute("class", "mstooltip");
1354                                 requiredNode.textContent = "?";
1355                                 label.appendChild(requiredNode);
1356                                         
1357                                 var requiredNodeToolTip = document.createElement('span');
1358                                 requiredNodeToolTip.setAttribute("class", "tooltiptext");
1359                                 requiredNodeToolTip.textContent = "Conditional Required";
1360                                 requiredNode.appendChild(requiredNodeToolTip);
1361
1362                 }
1363
1364                 var listField = document.createElement("SELECT");
1365                 listField.setAttribute("class" , "form-control");
1366                 listField.setAttribute("style" , "width:300px;");
1367                 listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1368
1369                 if(description && description != "null"){
1370                         listField.setAttribute("title", description);
1371                 }
1372
1373                 if(isRequired){
1374                         if(document.getElementById(divID).hasAttribute('data-conditional')){
1375                                 listField.setAttribute("data-conditional", divID);
1376                                 listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1377                         }else{
1378                                 listField.setAttribute("required", true);
1379                         }
1380                 }
1381                 if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
1382                         var optionFirst = document.createElement('option');
1383                         var optionValue = "";
1384                         if($scope.temp.policy.ruleData != null){
1385                                 if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1386                                         optionValue = $scope.temp.policy.ruleData[labelLevel + attributeName];  
1387                                 }
1388                         } 
1389                         optionFirst.setAttribute('value', optionValue);
1390                         optionFirst.appendChild(document.createTextNode(optionValue));
1391                         listField.appendChild(optionFirst);     
1392                 }
1393                 var ruleFormationCheck = false;
1394                 if(listemunerateValues.length !== 0 && typeof listemunerateValues[0] == "string" && listemunerateValues[0].includes("dictionary:")) {
1395                         var ruleCheck = listemunerateValues[0].split("&");
1396                         var dictParams = ruleCheck[0].split(":");
1397                         var dictParamsSplit = dictParams[1].split("@");
1398                         if (ruleCheck[1] != undefined  && ruleCheck[1] == 'Rule') {
1399                                 ruleFormationCheck = true;
1400                         }
1401                         PolicyAppService.getData(dictParamsSplit[0]).then(function (data) {
1402                                 var j = data;
1403                                 $scope.data = JSON.parse(j.data);
1404                                 console.log($scope.data);
1405                                 $scope.listDictionarys = JSON.parse($scope.data[dictParamsSplit[1]]);
1406                                 for (i=0; i < $scope.listDictionarys.length; i += 1) {
1407                                         option = document.createElement('option');
1408                                         option.setAttribute('value', $scope.listDictionarys[i]);
1409                                         option.appendChild(document.createTextNode($scope.listDictionarys[i]));
1410                                         listField.appendChild(option);
1411                                 }
1412                         }, function (error) {
1413                                 console.log("failed");
1414                         });
1415
1416                 }
1417                 else{
1418                         for (i=0; i < listemunerateValues.length; i += 1) {
1419                                 if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
1420                                         listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
1421                                 }
1422                                 
1423                             option = document.createElement('option');
1424                             option.setAttribute('value', listemunerateValues[i]);
1425                             option.appendChild(document.createTextNode(listemunerateValues[i]));
1426                             option.setAttribute('value', listemunerateValues[i]);
1427                             listField.appendChild(option);
1428                         }
1429                 }
1430                 listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
1431
1432                 enumKeyList.push(attributeName);
1433
1434                 document.getElementById(divID).appendChild(label);  
1435                 document.getElementById(divID).appendChild(br); 
1436
1437                 if(many == true){
1438                         document.getElementById(divID).appendChild(listField).multiple = true;
1439                         plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
1440                 }else {
1441                         document.getElementById(divID).appendChild(listField).multiple = false;
1442                         plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
1443
1444                         if (defaultValue){
1445                                 if(defaultValue.includes(':')){
1446                                         defaultValue = defaultValue.split(':')[0];
1447                                 }
1448                                 var location = listemunerateValues.indexOf(defaultValue);
1449                                 document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
1450                         }
1451                 }
1452
1453                 if (ruleFormationCheck) {
1454                         var optionInput = document.createElement("INPUT");
1455                         optionInput.setAttribute("type" , "text");
1456                         optionInput.setAttribute("id" , ''+ labelLevel + attributeName + '.input');
1457                         optionInput.setAttribute("name" , "ruleName");
1458                         optionInput.setAttribute("value" , "  ");
1459                         optionInput.setAttribute("style" , "width:300px;");
1460                         optionInput.setAttribute("ng-disabled" , "temp.policy.readOnly");
1461                         optionInput.removeAttribute("required");
1462
1463                         document.getElementById(divID).appendChild(optionInput);
1464
1465                         var optionButton = document.createElement("BUTTON");
1466                         optionButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1467                         var buttonLabel = document.createTextNode("+");       
1468                         optionButton.appendChild(buttonLabel); 
1469                         optionButton.setAttribute("class", "btn btn-add-remove");
1470                         optionButton.setAttribute("onclick" , 'addDynamicOptions("'+ labelLevel + attributeName + '");');
1471                         optionButton.removeAttribute("required");
1472
1473
1474                         document.getElementById(divID).appendChild(optionButton);
1475                         document.getElementById(divID).appendChild(br); 
1476                 }
1477
1478                 if($scope.temp.policy.ruleData != null){
1479                         if (many == true){
1480                                 document.getElementById(labelLevel +attributeName).options[0].selected = false;
1481                                 for (i=0; i < listemunerateValues.length; i += 1) {
1482                                         var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
1483                                         if (testValue === undefined){
1484                                                 testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
1485                                         }
1486                                         var location = listemunerateValues.indexOf(testValue);
1487                                         if (location!=-1){
1488                                                 document.getElementById(labelLevel +attributeName).options[location].selected = true;
1489                                         }
1490                                 }                       
1491                         }else {
1492                                 if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1493                                         document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];    
1494                                 }
1495                         }
1496                 }
1497         };
1498
1499         addDynamicOptions = function(id) { 
1500                 var option = document.createElement("option");
1501                 var value = document.getElementById(id+".input").value;
1502                 option.setAttribute('value', value);
1503                 option.appendChild(document.createTextNode(value));
1504                 document.getElementById(id).options.add(option);
1505                 document.getElementById(id+".input").value = "";
1506         };
1507
1508         function onlyUnique(value, index, self) { 
1509                 return self.indexOf(value) === index;
1510         };
1511
1512
1513         function checkDictionary(value){
1514                 for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
1515                         if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
1516                                 return true;
1517                         }
1518                 }
1519
1520         }
1521         $scope.savePolicy = function(policy){
1522                 if(policy.itemContent != undefined){
1523                         $scope.refreshCheck = true; 
1524                         $scope.policyNavigator = policy.itemContent;
1525                         policy.itemContent = "";
1526                 }
1527                 $scope.savebutton = false;
1528                 var splitAt = '*';
1529                 var dot ='.';
1530                 var jsonPolicy = {};
1531                 if(plainAttributeKeys != null){
1532                         for(a = 0; a < plainAttributeKeys.length; a++){
1533                                 var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1534                                 console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
1535                                 var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1536                                 var key = splitPlainAttributeKey[0];
1537                                 if(searchElement == null){
1538                                         searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1539                                         key = splitPlainAttributeKey[0]+'@0';
1540                                 }else if (searchElement.nodeName == 'BUTTON'){
1541                                         searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1542                                         key = splitPlainAttributeKey[0]+'@0';
1543                                 }
1544                                 if(searchElement != null){
1545                                         var keySplit = key.split(dot);
1546                                         var elumentLocation = keySplit.length;
1547                                         var enumKey = key;
1548                                         if (elumentLocation > 1){
1549                                                 enumKey = keySplit[keySplit.length - 1];
1550                                         }
1551                                         //check it is undefined or not
1552                                         if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
1553                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
1554                                                         var multiSlect = [];
1555                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1556                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1557                                                                 }
1558                                                         jsonPolicy[key]= multiSlect;
1559                                                 }else{
1560                                                         console.log(" searchElement.value = > " + searchElement.value);
1561                                                         if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
1562                                                                 jsonPolicy[key]= false;
1563                                                                 for(var i=0; i<booleanTrueElements.length; i++){                                                                        
1564                                                                         if(booleanTrueElements[i] == key){
1565                                                                                 jsonPolicy[key]= true;
1566                                                                         }
1567                                                                 }
1568
1569                                                         }else{
1570                                                                 jsonPolicy[key]= searchElement.value;
1571                                                         }
1572                                                 }
1573                                 } else {
1574                                         if(searchElement.value != null){
1575                                                 jsonPolicy[key]= searchElement.value;                                           
1576                                                         console.log(" searchElement.value = > " + searchElement.value);
1577                                                         if(splitPlainAttributeKey[1] == "boolean"){
1578                                                                 jsonPolicy[key]= false;
1579                                                                 for(var i=0; i<booleanTrueElements.length; i++){                                                                        
1580                                                                         if(booleanTrueElements[i] == key){
1581                                                                                 jsonPolicy[key]= true;
1582                                                                         }
1583                                                                 }
1584                                                         }
1585                                         }
1586                                 }
1587                         }
1588                 }
1589         }
1590         var uuu = "policycreation/save_policy";
1591         var postData={policyData: policy, policyJSON : jsonPolicy};
1592         $.ajax({
1593             type : 'POST',
1594             url : uuu,
1595             dataType: 'json',
1596             contentType: 'application/json',
1597             data: JSON.stringify(postData),
1598             success : function(data){
1599                 $scope.$apply(function(){
1600                         $scope.data=data.policyData;
1601                         if($scope.data == 'success'){
1602                                 $scope.temp.policy.readOnly = 'true';
1603                                 $scope.safetyChecker = data.policyData.split("#")[2];
1604                                 if ($scope.safetyChecker!=undefined) {
1605                                         Notification.success($scope.safetyChecker);
1606                                 }
1607                                 $scope.pushStatus=data.policyData.split("&")[1];
1608                                 if($scope.pushStatus=="successPush"){
1609                                         Notification.success("Policy pushed successfully");
1610                                 }
1611                                 Notification.success("Policy Saved Successfully.");     
1612                         }else if ($scope.data == 'PolicyExists'){
1613                                                 $scope.savebutton = true;
1614                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1615                                         }
1616                 });
1617                 console.log($scope.data);
1618             },
1619             error : function(data){
1620                 Notification.error("Error Occured while saving Policy.");
1621             }
1622         });
1623     };
1624     
1625     var booleanTrueElements = [];
1626     $scope.validatePolicy = function(policy){
1627         document.getElementById("validate").innerHTML = "";
1628         var splitAt = '*';
1629         var dot ='.';
1630         var jsonPolicy = {};
1631         if(plainAttributeKeys != null){
1632                 for(a = 0; a < plainAttributeKeys.length; a++){
1633                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1634                         console.log(splitPlainAttributeKey[1]); 
1635                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1636                         var key = splitPlainAttributeKey[0];
1637                         if(searchElement == null){
1638                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1639                                 key = splitPlainAttributeKey[0]+'@0';
1640                         }else if (searchElement.nodeName == 'BUTTON'){
1641                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1642                                 key = splitPlainAttributeKey[0]+'@0';
1643                         }
1644                         if(searchElement != null){
1645                                 if (enumKeyList.indexOf(key) != -1){
1646                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1647                                                         var multiSlect = [];
1648                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1649                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1650                                                                 }
1651                                                         jsonPolicy[key]= multiSlect;
1652                                                 }else{
1653                                                         jsonPolicy[key]= searchElement.value;
1654                                                 }
1655                                         if(searchElement.getAttribute("required")){
1656                                                 if(!searchElement.value){
1657                                                         return;
1658                                                 }
1659                                         } 
1660                                 } else {
1661                                         if(searchElement.value != null){
1662                                                 jsonPolicy[key]= searchElement.value;
1663                                                 if(searchElement.getAttribute("required")){
1664                                                         if(!searchElement.value){
1665                                                                 return;
1666                                                         }
1667                                                 }                                               
1668                                         }
1669                                 }
1670                         }
1671                 }
1672                 
1673                 
1674                 var checkedValue = $('.onoffswitch-checkbox:checked').val();
1675                 
1676             var x = document.getElementsByClassName("onoffswitch-checkbox");
1677             
1678                              
1679                 if(checkedValue){
1680                         console.log("checkedValue:" + checkedValue);
1681                         for(var i=0; i<x.length; x++){
1682                        console.log("checkbox id: " + x[i].id);
1683                            booleanTrueElements.push(x[i].id)
1684                         }    
1685                 }
1686         }
1687         var uuu = "policyController/validate_policy.htm";
1688
1689         console.log("$scope.isCheck:" + $scope.isCheck);
1690         
1691         if($scope.isCheck == true){
1692                 if(("configName" in policy) == false){
1693                                 Notification.error("Validation Failed: configName is required");
1694                                 $scope.savebutton = true;
1695                                 return;
1696                 }
1697                 if(("location" in policy) == false){
1698                                 Notification.error("Validation Failed: location is required");
1699                                 $scope.savebutton = true;
1700                                 return;
1701                 }
1702                 if(("uuid" in policy) == false){
1703                                 Notification.error("Validation Failed: uuid is required");
1704                                 $scope.savebutton = true;
1705                                 return;
1706                 }
1707                 if(("policyScope" in policy) == false){
1708                                 Notification.error("Validation Failed: policyScope is required");
1709                                 $scope.savebutton = true;
1710                                 return;
1711                 }
1712         }        
1713         
1714         var postData={policyData: policy, policyJSON : jsonPolicy};
1715                 $.ajax({
1716                         type : 'POST',
1717                         url : uuu,
1718                         dataType: 'json',
1719                         contentType: 'application/json',
1720                         data: JSON.stringify(postData),
1721                         success : function(data){
1722                                 $scope.$apply(function(){
1723                                         $scope.validateData = data.data.replace(/\"/g, "");
1724                                         $scope.data=data.data.substring(1,8);
1725                                                 var size = data.data.length;
1726                                                 if($scope.data == 'success'){
1727                                                         Notification.success("Validation Success.");
1728                                                         $scope.savebutton = false;
1729                                                         if (size > 18){
1730                                                                 var displayWarning = data.data.substring(19,size  - 1);
1731                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1732                                                                 document.getElementById("validate").style.color = "white";
1733                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1734                                                         }
1735                                                 }else{
1736                                                         Notification.error("Validation Failed.");
1737                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1738                                                         document.getElementById("validate").style.color = "white";
1739                                                         document.getElementById("validate").style.backgroundColor = "red";
1740                                                         $scope.savebutton = true;
1741                                                 }
1742                                                 
1743                                 });
1744                                 console.log($scope.data);       
1745                         },
1746                         error : function(data){
1747                                 Notification.error("Validation Failed.");
1748                                 $scope.savebutton = true;
1749                         }
1750                 });
1751     };
1752
1753     function extend(obj, src) {
1754         for (var key in src) {
1755             if (src.hasOwnProperty(key)) obj[key] = src[key];
1756         }
1757         return obj;
1758     }
1759     
1760         // Switch Click
1761         $('.Switch').click(function() {
1762                         // Check If Enabled (Has 'On' Class)
1763                         if ($(this).hasClass('On')){
1764                                 // Try To Find Checkbox Within Parent Div, And Check It
1765                                 $(this).parent().find('input:checkbox').attr('checked', true);
1766                                 // Change Button Style - Remove On Class, Add Off Class
1767                                 $(this).removeClass('On').addClass('Off');
1768                         } else { // If Button Is Disabled (Has 'Off' Class)
1769                                 // Try To Find Checkbox Within Parent Div, And Uncheck It
1770                                 $(this).parent().find('input:checkbox').attr('checked', false); 
1771                                 // Change Button Style - Remove Off Class, Add On Class
1772                                 $(this).removeClass('Off').addClass('On');      
1773                         }       
1774                 });
1775          // Loops Through Each Toggle Switch On Page
1776         $('.Switch').each(function() {
1777                         // Search of a checkbox within the parent
1778                         if ($(this).parent().find('input:checkbox').length){
1779                                 
1780                                 // If checkbox doesnt have the show class then hide it
1781                                 if (!$(this).parent().find('input:checkbox').hasClass("show")){
1782                                         $(this).parent().find('input:checkbox').hide(); }
1783                         
1784                                 // Look at the checkbox's checkked state
1785                                 if ($(this).parent().find('input:checkbox').is(':checked')){
1786                                         // Checkbox is not checked, Remove the On Class and Add the Off Class
1787                                         $(this).removeClass('On').addClass('Off');
1788                                 } else {                        
1789                                         // Checkbox Is Checked Remove Off Class, and Add the On Class
1790                                         $(this).removeClass('Off').addClass('On');
1791                                 }
1792                         }
1793                 });
1794
1795 }]);