Remove unused vars and methods
[policy/engine.git] / POLICY-SDK-APP / src / main / webapp / app / policyApp / policy-models / Editor / PolicyTemplateController / OptimizationPolicyController.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2018-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 angular.module('abs').controller('optimizationController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
21     $("#dialog").hide();
22     
23     $scope.policyNavigator;
24     $scope.isCheck = false;
25     $scope.savebutton = true;
26     $scope.refreshCheck = false;
27     
28     if(!$scope.temp.policy.editPolicy  && !$scope.temp.policy.readOnly){
29         $scope.temp.policy = {
30                         policyType : "Config",
31                         configPolicyType : "Optimization"
32         }
33     }
34     
35     $scope.refresh = function(){
36         if($scope.refreshCheck){
37                 $scope.policyNavigator.refresh();
38         }
39         $scope.modal('createNewPolicy', true);
40         $scope.temp.policy = "";
41     };
42     
43     $scope.modal = function(id, hide) {
44         return $('#' + id).modal(hide ? 'hide' : 'show');
45     };
46     
47     $('#ttlDate').datepicker({
48         dateFormat: 'dd/mm/yy',
49         changeMonth: true,
50         changeYear: true,
51         onSelect: function(date) {
52                 angular.element($('#ttlDate')).triggerHandler('input');
53         }
54     });
55     
56         if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly  != undefined){
57                 if ($scope.temp.policy.configName == undefined){
58                         $scope.isCheck = false;
59                 }else{
60                         $scope.isCheck = true;
61                 }
62         }else {
63                 $scope.isCheck = false;
64         }
65                 
66         PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
67                 var j = data;
68                 $scope.data = JSON.parse(j.data);
69                 console.log($scope.data);
70                 $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
71                 console.log($scope.onapNameDictionaryDatas);
72         }, function (error) {
73                 console.log("failed");
74         });
75
76         PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
77                 var j = data;
78                 $scope.data = JSON.parse(j.data);
79                 console.log($scope.data);
80                 $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
81                 console.log($scope.priorityDatas);
82         }, function (error) {
83                 console.log("failed");
84         });
85
86         PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
87                 var j = data;
88                 $scope.data = JSON.parse(j.data);
89                 console.log($scope.data);
90                 var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
91                 var unique = {};
92                 var uniqueList = [];
93                 for(var i = 0; i < inputModelList.length; i++){
94                         if(typeof unique[inputModelList[i]] == "undefined"){
95                                 unique[inputModelList[i]] = "";
96                                 uniqueList.push(inputModelList[i]);
97                         }
98                 }
99                 $scope.optimizationModelsDictionaryDatas = uniqueList;
100                 console.log($scope.optimizationModelsDictionaryDatas);
101         }, function (error) {
102                 console.log("failed");
103         });
104
105         PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
106                 var j = data;
107                 $scope.data = JSON.parse(j.data);
108                 console.log($scope.data);
109                 $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
110                 console.log($scope.riskTypeDictionaryDatas);
111         }, function (error) {
112                 console.log("failed");
113         });
114
115          $scope.choices = [];
116          $scope.attributeDatas = [{"attributes" : $scope.choices}];
117          $scope.isInitEditTemplate = true;  //just initially create the edit template, didn't click add button yet.
118          $scope.addNewChoice = function(value) {
119                  console.log("input value : " + value);
120                  if(value != undefined){
121                         if (value.startsWith('div.')){
122                                 value = value.replace('div.','');
123                         }
124                         var parentElement = document.getElementById("div."+value);
125                         var div = document.getElementById(value+"@0");
126                         if(div != null){
127                                 var clone = div.cloneNode(true); 
128                                 var addElement = parentElement.childElementCount;
129                                 clone.id = ''+value+'@'+addElement;
130                                 clone.value = '';
131                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
132                                         if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){  // Only append child if its value found in ruleData or edit mode
133                                                 if($scope.temp.policy.ruleData[clone.id]){
134                                                     clone.value = $scope.temp.policy.ruleData[clone.id];
135                                                 }
136                                                 if(!clone.className.includes("child_single")){   
137                                                         clone.className += ' child_single'; //single element clone
138                                                 }
139                                                 document.getElementById("div."+value).appendChild(clone);
140                                                 plainAttributeKeys.push(''+value+'@'+addElement);
141                                         }
142                                 }else{ //not view or edit
143                                         if(!clone.className.includes("child_single")){   
144                                                 clone.className += ' child_single'; //single element clone
145                                         }
146                                         document.getElementById("div."+value).appendChild(clone);
147                                         plainAttributeKeys.push(''+value+'@'+addElement);
148                                 }
149                         }else{
150                                 div = document.getElementById("div."+value+"@0");
151                                 
152                                 if(div){
153                                 div.className += ' children_group'; //div with a group of children.
154                                 }                               
155                                 var childElement = parentElement.firstElementChild;
156                                 var countParent = parentElement.childElementCount;
157                                 var childElementString = childElement.innerHTML;
158                                 var find = value+"@0";
159                                 var re = new RegExp(find, 'g');
160                                 childElementString = childElementString.replace(re,value+'@' + countParent);
161                                 var clone = childElement.cloneNode(true);
162                                 for (var ii = 0; ii < parentElement.childNodes.length; ii++){
163                             var childId = parentElement.childNodes[ii].id;
164                             if(ii = parentElement.childNodes.length){
165                                 var childnewId = childId.slice(0, -1);
166                                 var count = childId.slice(-1);
167                             }
168                         }
169                                 var countvalue = parseInt(count) + 1;
170                                 clone.id = childnewId+countvalue;
171                                 clone.value = '';
172                                 clone.innerHTML=childElementString;
173                                 document.getElementById("div."+value).appendChild(clone);
174                                 var selects = clone.getElementsByTagName("select");
175                                 var inputs = clone.getElementsByTagName("input");
176                                 var removeValues = [];
177                                 for(var i=0; i<inputs.length; i++){
178                                         if ($scope.temp.policy.ruleData!=undefined){
179                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
180                                                 if (checkValue!=undefined && checkValue != "undefined"){
181                                                         if($scope.temp.policy.ruleData != null){
182                                                                 var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
183                                                                 document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
184                                                                 plainAttributeKeys.push(inputs[i].id);
185                                                         }
186                                                 } else {
187                                                         plainAttributeKeys.push(inputs[i].id);
188                                                 }
189                                         }else {
190                                                 plainAttributeKeys.push(inputs[i].id);
191                                         }
192                                 }
193                                 
194                                 for(var i=0; i<selects.length; i++){
195                                         if ($scope.temp.policy.ruleData!=undefined){
196                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
197                                                 if (checkValue!=undefined && checkValue!="undefined"){
198                                                         if($scope.temp.policy.ruleData != null){
199                                                                 var checkValue = $scope.temp.policy.ruleData[selects[i].id];
200                                                                 document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
201                                                                 plainAttributeKeys.push(selects[i].id);
202                                                         }
203                                                 } else {
204                                                         plainAttributeKeys.push(selects[i].id);
205                                                 }
206                                         }else {
207                                                 plainAttributeKeys.push(selects[i].id);
208                                         }
209                                 }
210                                 
211                                 for (var k=0; k<removeValues.length; k++){
212                                         var elem = document.getElementById(removeValues[k]);
213                                         elem.parentNode.removeChild(elem);
214                                 }
215                                 var ele = angular.element(document.getElementById("div."+value));
216                         $compile(ele.contents())($scope);
217                     $scope.$apply();
218                         }
219                  }
220          };
221          
222          function findVal(object, key) {
223                     var value;
224                     Object.keys(object).some(function(k) {
225                         if (k === key) {
226                             value = object[k];
227                             return true;
228                         }
229                         if (object[k] && typeof object[k] === 'object') {
230                             value = findVal(object[k], key);
231                             return value !== undefined;
232                         }
233                     });
234                     return value;
235         }
236          
237          $scope.removeChoice = function(value) {
238                  console.log(value);
239                  if(value != undefined){
240                          var c = document.getElementById("div."+value).childElementCount;
241                          
242                          if(c == 1){
243                                  Notification.error("The original one is not removable.");
244                                  return;
245                          }      
246                          document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);     
247                  }
248          };
249          
250          $scope.pullVersion = function(serviceName) {
251                  console.log(serviceName);
252                  if(serviceName != undefined){
253                          var uuu = "policyController/getModelServiceVersionData.htm";
254                          var postData={policyData: serviceName};
255                          $.ajax({
256                                  type : 'POST',
257                                  url : uuu,
258                                  dataType: 'json',
259                                  contentType: 'application/json',
260                                  data: JSON.stringify(postData),
261                                  success : function(data){
262                                          $scope.$apply(function(){
263                                                  $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
264                                          });
265                                  },
266                                  error : function(data){
267                                          alert("Error While Retrieving the Template Layout Pattern.");
268                                  }
269                          });             
270                  }
271          };
272     
273         var splitEqual = '=';
274         var splitComma = ',';
275         var splitcolon = ':';
276         var splitEnum = "],";
277         var plainAttributeKeys = [];
278         var matching = [];
279         var enumKeyList = [];
280         var dictionaryList = [];
281         var dictionaryNameList = [];
282     $scope.addDataToFields = function(serviceName, version){
283         if(serviceName != null && version !=null){
284                 var service=serviceName+"-v"+version;
285                 var myNode = document.getElementById("DynamicTemplate");
286                 myNode.innerHTML = '';
287             var uuu = "policyController/getOptimizationTemplateData.htm";
288             var postData={policyData: service};
289             var dataOrderInfo = "";
290             
291             $.ajax({
292                 type : 'POST',
293                 url : uuu,
294                 dataType: 'json',
295                 contentType: 'application/json',
296                 data: JSON.stringify(postData),
297                 success : function(data){
298                     $scope.$apply(function(){
299                         $scope.optimizationModelData = data[0].optimizationModelData;
300                         $scope.optimizationJsonDate = data[0].jsonValue;
301                         $scope.dataOrderInfo = null;
302                         $scope.dataOrderInfo = data[0].dataOrderInfo;
303                         console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
304                         console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);   
305                         if(data[0].allManyTrueKeys){
306                                 console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
307                         }
308                         console.log("$scope.optimizationJsonDate: " + $scope.optimizationJsonDate);     
309                         var attributes = $scope.optimizationModelData.attributes;
310                         var refAttributes = $scope.optimizationModelData.ref_attributes;
311                         var subAttributes =     $scope.optimizationModelData.sub_attributes;   
312                         console.log("attributes: " +attributes);                        
313                         console.log("subAttributes: " + subAttributes); 
314                         console.log("refAttributes: " + refAttributes); 
315                         
316                         var headDefautlsData  = data[0].headDefautlsData;
317                         if(headDefautlsData != null){
318                                          $scope.temp.policy.onapName = headDefautlsData.onapName;
319                                          $scope.temp.policy.guard = headDefautlsData.guard;
320                                          $scope.temp.policy.riskType = headDefautlsData.riskType;
321                                          $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
322                                          $scope.temp.policy.priority = headDefautlsData.priority;
323                                          
324                         }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
325                                          $scope.temp.policy.onapName = "";
326                                          $scope.temp.policy.guard = "";
327                                          $scope.temp.policy.riskType = "";
328                                          $scope.temp.policy.riskLevel = "";
329                                          $scope.temp.policy.priority = "";
330                         }
331                         
332                         var annotation = $scope.optimizationModelData.annotation;
333                         var dictionary = $scope.microServiceAttributeDictionaryDatas;
334
335                         if (annotation == null || annotation.length<1){
336                                 $scope.isCheck = true;
337                         }else {
338                                 $scope.isCheck = false;
339                                 var annoationList = annotation.split(splitComma);
340                                 for (k = 0; k < annoationList.length; k++){
341                                         var splitAnnotation = annoationList[k].split(splitEqual);
342                                         if (splitAnnotation[1].includes("matching-true")){
343                                                 matching.push(splitAnnotation[0].trim());
344                                         }
345                                 }
346
347                         }
348
349                         if (dictionary!= null && dictionary.length>1){
350                                 for (m=0; m < dictionary.length; m += 1){
351                                         var valueCompare = dictionary[m].value;
352                                         var valueModel = dictionary[m].modelName;
353                                         var conpairService = serviceName;
354                                         if (valueModel.includes('-v')){
355                                                 conpairService = service;
356                                         }
357                                         if(valueModel.localeCompare(conpairService) == 0){
358                                                 console.log(valueCompare);      
359                                                 dictionaryList.push(dictionary[m]);
360                                                 if (!dictionaryNameList.includes(dictionary[m].name)){
361                                                         dictionaryNameList.push(dictionary[m].name)
362                                                 }
363                                         }
364                                 }
365                         }
366
367                                 $scope.temp.policy.ruleGridData = [];
368                                 
369                                 if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
370                                         dataOrderInfo = $scope.dataOrderInfo;
371                                 }
372                                 
373                                 $scope.jsonLayout($scope.optimizationJsonDate);
374                                 
375                     });
376                     
377                     if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){  // If it's veiw or edit
378                         
379                         if($scope.temp.policy.editPolicy){
380                                 $scope.isInitEditTemplate = true;
381                         }
382                         
383                         var checkData = [];
384                         var data = [];
385                             // If ruleData contains extra elements created by clicked add button 
386                                 if($scope.temp.policy.ruleData != null){
387                                         var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
388                                         propNames.forEach(function(name) {
389                                                 data.push(name);
390                                         });
391                                         
392                                         var extraElements = data;
393                                         
394                                         if(plainAttributeKeys != null){
395                                                 for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
396                                                         var newValue = plainAttributeKeys[b].split("*");
397                                                         for(a = 0; a < data.length; a++){
398                                                                 if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
399                                                                         extraElements.splice(a, 1);
400                                                                 }
401                                                         }
402                                         
403                                                 }
404                                         
405                                                 //--- Populate these extra elements created by clicked add button 
406                                                 for(a = 0; a < extraElements.length; a++){                              
407                                                         if(extraElements[a].includes("@")){
408                                                                 var index = extraElements[a].lastIndexOf("@");
409                                                                 if(index > 0){
410                                                                     // Get the number after @
411                                                                     var n = getNumOfDigits(extraElements[a], index+1);
412                                                                                         
413                                                                         var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
414                                                                         console.log("key: " + key);
415                                                                         checkData.push(key);
416                                                                 }
417                                                         }
418                                                 }
419                                                 var unique = checkData.filter(onlyUnique);
420                                                 //if no layout order info, keep the process as before
421                                                 if(!dataOrderInfo){
422                                                         for(i =0; i < unique.length; i++){
423                                                                 //remove @x and let addNewChoice add @1 or @2...
424                                                                 //var newKey = unique[i].substring(0, unique[i].length-2);
425                                                                 var index = unique[i].lastIndexOf("@");
426                                                                 var newKey = unique[i].substring(0, index);
427                                                                 console.log("newKey: " + newKey);       
428                                                                 $scope.addNewChoice(newKey);
429                                                         }
430                                                 }else{
431
432                                                         for (i = 0; i < $scope.labelManyKeys.length; i++) {
433                                                                 console.log("dataOrderInfo["+i+"]"+  dataOrderInfo[i]);
434                                                             var label = $scope.labelManyKeys[i];
435                                                                         // first add parent/label level
436                                                                         for (k = 0; k < unique.length; k++){
437                                                                                 var newKey = unique[k].substring(0, index);
438                                                                             if(label == newKey){
439                                                         //Check this label has bee created or not
440                                                                                 if(!document.getElementById(unique[k])){
441                                                                                         $scope.addNewChoice(newKey);
442                                                                                 }
443                                                                                 unique[k] = "*processed*";
444                                                                                         break;
445                                                                             }
446                                                                         }                                                                               
447                                                         }
448                                                         
449                                                         //---reset to default
450                                                         dataOrderInfo = [];
451                                                         $scope.labelManyKeys = [];
452                                                         
453                                                         //---process none labels
454                                                         for (j = 0; j < unique.length; j++){
455                                                                 if(unique[j] != "*processed*"){
456                                                                         // if not created yet
457                                                                         if(!document.getElementById(unique[j])){
458                                                                                 var index = unique[j].lastIndexOf("@");
459                                                                                 var newKey = unique[j].substring(0, index);
460                                                                             $scope.addNewChoice(newKey);
461                                                                         }
462                                                                 }
463                                                         }
464                                                 }
465                                     }
466                             }
467                             
468                         if($scope.temp.policy.editPolicy){
469                                 //clean all the events of addNewChoice
470                                 $scope.$on('$destroy', addNewChoice);
471                         }
472                             
473                     }
474                     var ele = angular.element(document.getElementById("DynamicTemplate"));
475                         $compile(ele.contents())($scope);
476                     $scope.$apply();
477                 },
478                 error : function(data){
479                     alert("Error While Retrieving the Template Layout Pattern.");
480                 }
481             });
482         }
483     };
484     
485     function getNumOfDigits(str_value, index){
486                 // Get the number after @
487                 var str = str_value.substring(index, str_value.length); 
488                 var c = '';
489                 var n = 0;
490                 for (var x = 0; x < str.length; x++){                                                                   
491                     c = str.charAt(x);
492                             if(!isNaN(c)){ 
493                 n++;                                                     
494                     }else{
495                 break;
496             }
497                 }
498                 return n;
499     }
500     
501     function getDictionary(attribute){
502         var dicName = attribute;
503         if(attribute){
504            if(attribute.includes(":")){
505                    dicName = attribute.split(":")[0];
506            }
507         }
508             var dictionaryRegExp = new RegExp(dicName);
509             listemunerateValues = [];
510             if (dictionaryRegExp.test(dictionaryNameList)) {
511                         for (p=0; p < dictionaryList.length; p += 1) {
512                                 if (dicName == dictionaryList[p].name) {
513                                         listemunerateValues.push(dictionaryList[p].value);
514                                 }
515                         }
516             }
517             return listemunerateValues;
518     }
519     
520     function getList(attribute) {
521         var enumName = attribute;
522         console.log("In getList: attribute => " + attribute);
523         if(attribute){
524            if(attribute.includes(":")){
525                    enumName = attribute.split(":")[0];
526            }
527         }   
528         var baseEnum = $scope.optimizationModelData.enumValues;
529         var enumList = [];
530         if(baseEnum != null){
531                 enumList = baseEnum.split(splitEnum);
532         }
533         var enumAttributes;
534         var patternTest = new RegExp(enumName);
535         for (k=0; k < enumList.length; k += 1){
536                 if(patternTest.test(enumList[k]) == true){
537                         enumAttributes = enumList[k].trim();
538                 }
539         }
540
541         if(enumAttributes){
542                 enumAttributes = enumAttributes.replace("[", "");
543                 enumAttributes = enumAttributes.replace("]", "");
544                 enumAttributes = enumAttributes.replace(/ /g, '');
545                         var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
546                         listemunerateValues  = dropListAfterCommaSplit[1].split(splitComma);
547                 return listemunerateValues;
548              }
549            
550          return [];
551     }
552             
553     function getBooleanList(){
554         var booleanList = [];
555         booleanList.push(true);
556         booleanList.push(false);
557         return booleanList;
558     }
559
560     function isArray(arrayTest) {
561         return Object.prototype.toString.call(arrayTest) === '[object Array]';
562     }
563             
564         var lableList = [];
565         
566     $scope.layOutElementList = [];
567     $scope.layOutOnlyLableList = [];
568     
569     var elementOrderNum = 0;
570             
571         function deconstructJSON(layOutData, level , name) {
572
573                  var array = false;
574                  var label = level;
575                  var stringValue = "java.lang.String";
576                  var string = "string";
577                  var intValue = "int";
578                  var integerValue = "integer";
579                  var double = "double";
580                  var boolean = "boolean";
581                  var baseLevel = level;
582                  var list = "list";
583                  var String = "String";
584                  
585                  var attributekey = "";
586                  
587                 if (name.length > 1){
588                         label = label + name + '.';
589                 }
590                 
591             for (key in layOutData) {
592                 array = isArray(layOutData[key]);
593                 console.log("key: " + key , "value: " + layOutData[key]);
594         
595                 if (!!layOutData[key] && typeof(layOutData[key])=="object") {
596                         
597                         if (array==false && key!=="0"){
598                                 
599                                 if($scope.dataOrderInfo){
600                                     var labelObject = {"label" : key, "level" : label, "array" : array};
601                                     //save it to the list
602                                     $scope.layOutOnlyLableList.push(labelObject);
603                                     
604                                 }else {
605                                         //call label layout
606                                         $scope.labelLayout(label, key, array );
607                                 }
608                                 
609                         }
610                         
611                         if (array == true && key!=0){
612                                 lableList.push(key);
613                         }
614                         
615                         if (lableList.length > 0){
616                                 array = true;
617                         }
618                         if ( key==="0"){
619                                 var newKey = lableList.pop();
620                                 
621                                 if($scope.dataOrderInfo){
622                                         
623                                         var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
624                                         //save it to the list
625                                         $scope.layOutOnlyLableList.push(labelObject);
626                                         
627                                 }else {
628                                         //call label layout 
629                                     $scope.labelLayout(baseLevel, newKey, array );
630                                 }
631                                 
632                                 if (array){
633                                         label = baseLevel + newKey + '@0.';
634                                 } else {
635                                         label = baseLevel + newKey + '.';
636                                 }
637                         }
638                         deconstructJSON(layOutData[key] , label, key);
639                 } else {
640                         var attirbuteLabel = label;
641                         var defaultValue='';
642                         var isRequired = false;
643                         if (layOutData[key].includes('defaultValue-')){
644                                 defaultValue = layOutData[key].split('defaultValue-')[1];
645                         }
646
647                         if (key==="0"){
648                                 array = true;
649                                 attributekey = lableList.pop();
650                                 attirbuteLabel = baseLevel;
651                         } else {
652                                 attributekey = key.split();
653                         }
654                         
655                         if (layOutData[key].includes('required-true')){
656                                 isRequired = true;
657                         }
658                         
659                         var subAttributes = $scope.optimizationModelData.sub_attributes;
660                         
661                         if(subAttributes){                                      
662                                 var jsonObject = JSON.parse(subAttributes);                                     
663                                 var allkeys = Object.keys(jsonObject);
664                                 if(allkeys){
665                                         for (var k = 0; k < allkeys.length; k++) {
666                                                 var keyValue = allkeys[k];
667                                                 console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
668                                                 if(jsonObject[keyValue]){
669                                                         var tempObject = jsonObject[keyValue];
670                                                         if(tempObject && tempObject[key]){
671                                                         if (tempObject[key].includes('required-true')){
672                                                                 isRequired = true;
673                                                         }       
674                                                         }
675                                                 }
676                                         }                                               
677                                 }                                       
678                         }
679                         
680                         var elementObject = {};
681                         switch (layOutData[key].split(splitcolon)[0]){
682                         
683                                 case stringValue:
684                                 case string:
685                                         if($scope.dataOrderInfo){                                                       
686                                                 elementOrderNum++;
687                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
688                                                 $scope.layOutElementList.push(elementObject);
689                                         }else{
690                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
691                                         }
692                                         break;                                          
693                                 case intValue: 
694                                 case integerValue: 
695                                         if($scope.dataOrderInfo){
696                                                 elementOrderNum++;
697                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
698                                                 $scope.layOutElementList.push(elementObject);
699                                         }else{
700                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
701                                         }
702                                         break;                                          
703                                 case double:
704                                         if($scope.dataOrderInfo){
705                                                 elementOrderNum++;
706                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
707                                                 $scope.layOutElementList.push(elementObject);                                                   
708                                         }else{
709                                                 $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
710                                         }
711                                         break;
712                                 case boolean:
713                                         if($scope.dataOrderInfo){
714                                                 elementOrderNum++;
715                                                 elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
716                                                 $scope.layOutElementList.push(elementObject);
717                                         }else{
718                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
719                                         }
720                                         break;
721                                 default:
722                                         if (layOutData[key].includes('dictionary-')){
723                                                 var list = getDictionary(layOutData[key].split('dictionary-')[1]);
724                                         }else{
725                                                 //--- get dropdown values from enumValues
726                                                 var list = getList(layOutData[key]);
727                                         }
728                                         if (list.length===0){ //not dropdown element
729                                                 if($scope.dataOrderInfo){
730                                                         elementOrderNum++;
731                                                         elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
732                                                         $scope.layOutElementList.push(elementObject);
733                                                         
734                                                 }else{
735                                                         $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
736                                                 }                                                       
737                                         }else{
738                                                 if($scope.dataOrderInfo){
739                                                         elementOrderNum++;
740                                                         elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
741                                                         $scope.layOutElementList.push(elementObject);                                                           
742                                                 }else{
743                                                         $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
744                                                 }
745                                         }
746                                         break;
747                         }
748                 }
749             }
750         }  
751
752     $scope.validContionalRequired = function(parentId) {
753         console.log("ng-blur event: parentId : " + parentId);
754         var c = document.getElementById(parentId).children;
755         var i;
756         var hasValue = false;
757         for (i = 0; i < c.length; i++) {
758                 if(c[i].getAttribute("data-conditional")){
759                     console.log(c[i].getAttribute("data-conditional"));
760                     console.log(c[i].value);
761                     if(c[i].value != null && c[i].value.trim() != ""){
762                         hasValue = true;
763                     }
764                 }
765         }
766
767             for (i = 0; i < c.length; i++) {
768                 if(c[i].getAttribute("data-conditional")){
769                         if(hasValue){
770                             c[i].setAttribute("required", true);
771                         }else{
772                                 c[i].removeAttribute("required");
773                         }
774                 }
775             }           
776      }
777                         
778     $scope.jsonLayout = function(layOutData){
779         
780        deconstructJSON(layOutData , "", "");
781                    
782            var orderValue = $scope.dataOrderInfo;
783            var layOutElementList = $scope.layOutElementList;
784            var labelList = $scope.layOutOnlyLableList;
785             
786            //reset to default
787            elementOrderNum = 0;
788            $scope.layOutElementList = [];
789            $scope.layOutOnlyLableList = [];
790            
791            // Only layout in order if order info provided
792            if(orderValue){
793                    
794                    if(orderValue.includes("[")){
795                           orderValue = orderValue.replace("[", "") ;
796                           orderValue = orderValue.replace("]", "") ;
797                    }
798                    
799                    orderValue = orderValue.split(',') ;
800                    
801                    for (i = 0; i < orderValue.length; i++) {
802                            console.log("orderValue["+i+"]"+  orderValue[i]);
803                            var key = orderValue[i].trim();
804                          
805                             //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
806                            if(labelList){
807                                    for (k = 0; k < labelList.length; k++){
808                                            
809                                           var label = labelList[k].label.toString().trim();
810                                           var level = labelList[k].level.toString().trim();
811                                           var array = labelList[k].array;
812                                           
813                                           if(key == label){                                                       
814                                                  $scope.labelLayout(level, label, array);
815                                          //in case to have duplicate label names
816                                                  labelList[k].label = "*processed*";
817                                                  break;
818                                           }
819                                    }
820                            }
821                            //--- then layout each element based on its order defined in YAML file
822                    for (j = 0; j < layOutElementList.length; j++) { 
823                            
824                            var attributekey = layOutElementList[j].attributekey.toString().trim();                                         
825                         
826                            if(key == attributekey){     
827         
828                                    var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
829                                    var defaultValue = layOutElementList[j].defaultValue.toString().trim();
830                                    var isRequired = layOutElementList[j].isRequired;
831                                    
832                                    console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
833                                   
834                                    if (layOutElementList[j].type == "dropBox"){ 
835                                                 $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
836                                 
837                                    }else{
838                                             $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type); 
839         
840                                    }
841                                    
842                                    //in case to have duplicate attribute names
843                                    layOutElementList[j].attributekey = "*processed*";
844                                    break;
845                            }
846                    
847                    }
848                    
849                    }
850            }
851     }
852     
853     
854     $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
855                 $scope.temp.policy.ruleGridData.push(attibuteKey);                      
856                 var br = document.createElement("BR");
857         
858                 var label = document.createElement("Label");
859                 var labeltext = null;
860                 var requiredLabName = "";
861                 if (matching.includes(attibuteKey)){
862                         labeltext = document.createTextNode(attibuteKey + "*!");        
863                         isRequired = true;  //set required as true for matching element
864                 }else {
865                         if(isRequired){
866                                 requiredLabName = attibuteKey + " * ";
867                                 labeltext = document.createTextNode(requiredLabName);
868                         }else{
869                             labeltext = document.createTextNode(attibuteKey);   
870                         }
871                 }
872
873         
874                 var divID = labelValue;
875                 
876                 if (labelValue.length  < 1){
877                         divID = "DynamicTemplate";
878                 }else if (labelValue.endsWith('.')){
879                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
880                 }
881                 
882                 label.appendChild(labeltext);
883                 
884                 var textField = document.createElement("INPUT");
885                 
886                 textField.setAttribute("class" , "form-control");
887                 if(dataType){
888                            if(dataType == "double"){
889                                    textField.setAttribute("type" , "number");
890                                    textField.setAttribute("step" , "any");
891                            }else{
892                               textField.setAttribute("type" , dataType);
893                            }
894                 }
895                 textField.setAttribute("style" , "width:300px;");
896                 textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
897                 var checkKey;
898                 var id = "";
899                 if(attributeManyKey){
900                         checkKey = labelValue + attibuteKey+'@0';
901                         textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+''); 
902                         var divTag = document.createElement("div");
903                         divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
904                         var addButton = document.createElement("BUTTON");
905                         var buttonaddLabel = document.createTextNode("+");       
906                         addButton.appendChild(buttonaddLabel); 
907                         addButton.setAttribute("id", labelValue + attibuteKey);
908                         addButton.setAttribute("class", "btn btn-add-remove");
909                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + attibuteKey+'");');
910                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
911                         var removeButton = document.createElement("BUTTON");
912                         var buttonremoveLabel = document.createTextNode("-");       
913                         removeButton.appendChild(buttonremoveLabel); 
914                         removeButton.setAttribute("class", "btn btn-add-remove");
915                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue + attibuteKey+'");');
916                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
917                         document.getElementById(divID).appendChild(addButton); 
918                         document.getElementById(divID).appendChild(removeButton); 
919                         document.getElementById(divID).appendChild(label); 
920                         id = "div."+labelValue+attibuteKey;
921                         divTag.setAttribute("id", id); 
922                         document.getElementById(divID).appendChild(divTag);
923                         textField.className += ' first_child';  
924                         if(isRequired){
925                                 textField.setAttribute("required", "true");
926                         }                       
927                         divTag.appendChild(textField);                  
928                         document.getElementById(divID).appendChild(divTag); 
929                         
930                 }else{
931                         checkKey = labelValue + attibuteKey;
932                         textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
933                         if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
934                                 if(requiredLabName.includes("*") || isRequired){
935                                         textField.setAttribute("required", "true");
936                                 }
937                         }else if (document.getElementById(divID).hasAttribute('data-conditional')){
938                                 if(requiredLabName.includes("*")){                                      
939                                         var requiredNode = document.createElement('span');
940                                         requiredNode.setAttribute("class", "mstooltip");
941                                         requiredNode.textContent = "?";
942                                         label.appendChild(requiredNode);
943                                         
944                                         var requiredNodeToolTip = document.createElement('span');
945                                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
946                                         requiredNodeToolTip.textContent = "Conditional Required";
947                                         requiredNode.appendChild(requiredNodeToolTip);
948                                         
949                                         textField.setAttribute("data-conditional", divID);
950                                         textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
951                                 }
952                         }
953                 
954                         document.getElementById(divID).appendChild(label);  
955                         document.getElementById(divID).appendChild(textField);  
956                         document.getElementById(divID).appendChild(br); 
957         
958                 }
959
960                 if(divID.includes("@0") && divID.includes("div.")){
961                         var firstChild_Id = divID.split("@0")[0];
962                         var firstChild_element = document.getElementById(firstChild_Id);
963                         if(firstChild_element){
964                                 firstChild_element.className += ' children_group';  //here is a div with a group of children.
965                         }
966                 }
967                 console.log('firstChild_Id: ' + firstChild_Id);
968                 console.log('divID: ' + divID);
969                 
970                 if (defaultValue.length > 0){   
971                         if(defaultValue.includes(":")){
972                                 defaultValue = defaultValue.split(":")[0];
973                                 if(defaultValue === "NA") {
974                                         defaultValue = "";
975                                 }                               
976                         }
977                         if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
978                         document.getElementById(checkKey).value = defaultValue;
979                         }
980                 }
981                 
982                 if($scope.temp.policy.ruleData != null){
983                         if (attributeManyKey){
984                                 var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
985                                 if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
986                                     document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
987                                 }
988                         }else{
989                                 if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
990                                     document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
991                                 }
992                         }
993                 } 
994                 plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey); 
995
996     };
997     
998     $scope.labelManyKeys = [];
999     $scope.labelLayout = function(labelValue, lableName, labelManyKey ){
1000                 var label = document.createElement("Label")
1001                 var divID = labelValue;
1002                 if (labelValue.endsWith('.')){
1003                         var workingLabel = labelValue.substring(0, labelValue.length-1);
1004                 }else {
1005                         var workingLabel = labelValue;
1006                 }
1007                 
1008                 if (labelValue.length  < 1){
1009                         divID = "DynamicTemplate";
1010                 } else if (labelValue.endsWith('.')){
1011                         var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
1012                 }
1013                 
1014                 var subAttributes = $scope.optimizationModelData.subattributes;
1015             var jsonObject = JSON.parse(subAttributes); 
1016             var lablInfo = findVal(jsonObject, lableName);
1017                 console.log("findValue : " + lableName +": "+ lablInfo);
1018                 var star = "";
1019                 var required = null;
1020                 if(lablInfo){
1021                         if(lablInfo.includes("required-true")){
1022                                 star = " *";
1023                                 required = true;
1024                         }else if (lablInfo.includes("required-false")){
1025                                 required = false
1026                         }
1027                 }
1028                 
1029                 var labeltext = document.createTextNode(lableName + star);
1030         
1031                 label.appendChild(labeltext);
1032
1033
1034                 if(labelManyKey){
1035                         var addButton = document.createElement("BUTTON");
1036                         var buttonLabel = document.createTextNode("+");       
1037                         addButton.appendChild(buttonLabel); 
1038                         addButton.setAttribute("class", "btn btn-add-remove");
1039                         addButton.setAttribute("ng-click" ,  'addNewChoice("'+labelValue + lableName+'");');
1040                         addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
1041                         var removeButton = document.createElement("BUTTON");
1042                         var buttonremoveLabel = document.createTextNode("-");       
1043                         removeButton.appendChild(buttonremoveLabel); 
1044                         removeButton.setAttribute("class", "btn btn-add-remove");
1045                         removeButton.setAttribute("ng-click" ,  'removeChoice("'+labelValue +lableName+'");');
1046                         removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly"); 
1047                         document.getElementById(divID).appendChild(addButton); 
1048                         document.getElementById(divID).appendChild(removeButton);
1049                         document.getElementById(divID).appendChild(label);
1050                         var id = "div."+labelValue+lableName;
1051                         var divTag = document.createElement("div");
1052                         divTag.setAttribute("id", id); 
1053                         document.getElementById(divID).appendChild(divTag);
1054                         
1055                         var divTag = document.createElement("div");
1056                         divTag.setAttribute("id", id +'@0');  
1057                         
1058                         divTag.className += ' children_group'; //here is div with a group of children.
1059                         
1060                         if(required){
1061                            divTag.setAttribute("required", required);  
1062                         }else if(required == false){
1063                            divTag.setAttribute("data-conditional", "yes");  
1064                         }
1065                         
1066                         document.getElementById(id).appendChild(divTag);
1067                         
1068                         $scope.labelManyKeys.push(lableName);
1069                         
1070                 }else{
1071                         var divTag = document.createElement("div");
1072                         divTag.setAttribute("id", "div."+labelValue+lableName);
1073                         divTag.className += ' children_group'; //here is div with a group of children.
1074                         if(required){
1075                             divTag.setAttribute("required", required);  
1076                         }else if(required == false){
1077                                 divTag.setAttribute("data-conditional", "yes");  
1078                         }  
1079                         document.getElementById(divID).appendChild(label);  
1080                         document.getElementById(divID).appendChild(divTag);                     
1081                 }
1082     };
1083
1084     $scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
1085                 var br = document.createElement("BR");
1086         
1087                 if (labelLevel.length  < 1){
1088                                 var divID = "DynamicTemplate";
1089                 } else if (labelLevel.endsWith('.')){
1090                                 var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
1091                 }       
1092         
1093         
1094                 var label = document.createElement("Label")
1095                 
1096                 var refAttributes = $scope.optimizationModelData.ref_attributes;
1097                 if(isRequired != true && refAttributes){ //check refAttributes also             
1098                                 var refAttributesList = refAttributes.split(splitComma);
1099                                 for (k = 0; k < refAttributesList.length; k++){
1100                                 var refAttribute = refAttributesList[k].split(splitEqual);                      
1101                                 if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
1102                                         isRequired = true;
1103                                 }
1104                                 }
1105                 }
1106                 
1107                 if (matching.includes(attributeName)){
1108                         var labeltext = document.createTextNode(attributeName + "*!");
1109                         label.appendChild(labeltext);
1110                         isRequired = true;  //set required as true for matching element
1111                 }else {
1112                         var labeltext = document.createTextNode(attributeName);         
1113                         if(isRequired){
1114                             var requiredLabName = attributeName+ " * ";
1115                                 labeltext = document.createTextNode(requiredLabName);
1116                         }else{
1117                             labeltext = document.createTextNode(attributeName); 
1118                         }
1119                 
1120                     label.appendChild(labeltext);               
1121                 }
1122                 label.appendChild(labeltext);
1123                 // if this field is required, but its parent is not required
1124                 if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
1125                         var requiredNode = document.createElement('span');
1126                         requiredNode.setAttribute("class", "mstooltip");
1127                         requiredNode.textContent = "?";
1128                         label.appendChild(requiredNode);
1129                                 
1130                         var requiredNodeToolTip = document.createElement('span');
1131                         requiredNodeToolTip.setAttribute("class", "tooltiptext");
1132                         requiredNodeToolTip.textContent = "Conditional Required";
1133                         requiredNode.appendChild(requiredNodeToolTip);
1134
1135                 }
1136         
1137                 var listField = document.createElement("SELECT");
1138                 listField.setAttribute("class" , "form-control");
1139                 listField.setAttribute("style" , "width:300px;");
1140                 listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
1141                 
1142                 if(isRequired){
1143                     if(document.getElementById(divID).hasAttribute('data-conditional')){
1144                         listField.setAttribute("data-conditional", divID);
1145                         listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
1146                     }else{
1147                                 listField.setAttribute("required", true);
1148                     }
1149                 }
1150                 if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
1151                         var optionFirst = document.createElement('option');
1152                         optionFirst.setAttribute('value', "");
1153                         listField.appendChild(optionFirst);     
1154                 }
1155                 
1156                 for (var i=0; i < listemunerateValues.length; i += 1) {
1157                         if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
1158                                 listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
1159                         }
1160                     var option = document.createElement('option');
1161                     option.setAttribute('value', listemunerateValues[i]);
1162                     option.appendChild(document.createTextNode(listemunerateValues[i]));
1163                     option.setAttribute('value', listemunerateValues[i]);
1164                     listField.appendChild(option);
1165                 }
1166                 listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
1167                 
1168                 enumKeyList.push(attributeName);
1169                 
1170                 document.getElementById(divID).appendChild(label);  
1171                 document.getElementById(divID).appendChild(br); 
1172                                 
1173                 if(many == true){
1174                         document.getElementById(divID).appendChild(listField).multiple = true;
1175                         plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
1176                 }else {
1177                         document.getElementById(divID).appendChild(listField).multiple = false;
1178                         plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
1179                 }
1180         
1181                 if($scope.temp.policy.ruleData != null){
1182                         if (many == true){
1183                                 document.getElementById(labelLevel +attributeName).options[0].selected = false;
1184                                 for (i=0; i < listemunerateValues.length; i += 1) {
1185                                         var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
1186                                         if (testValue === undefined){
1187                                                 testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
1188                                                 }
1189                                         var location = listemunerateValues.indexOf(testValue);
1190                                         if (location!=-1){
1191                                                 document.getElementById(labelLevel +attributeName).options[location].selected = true;
1192                                                 }
1193                                         }                       
1194                                 }else {
1195                                             if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
1196                                     document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];        
1197                                             }
1198                                 }
1199                         }
1200             };
1201     
1202     function onlyUnique(value, index, self) { 
1203         return self.indexOf(value) === index;
1204     };
1205     
1206     $scope.savePolicy = function(policy){
1207         if(policy.itemContent != undefined){
1208                 $scope.refreshCheck = true; 
1209                 $scope.policyNavigator = policy.itemContent;
1210                 policy.itemContent = "";
1211         }
1212         $scope.savebutton = false;
1213         var splitAt = '*';
1214         var dot ='.';
1215         var jsonPolicy = {};
1216         if(plainAttributeKeys != null){
1217                 for(a = 0; a < plainAttributeKeys.length; a++){
1218                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1219                         console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);       
1220                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1221                         var key = splitPlainAttributeKey[0];
1222                         
1223                 if(searchElement == null || searchElement.nodeName == 'BUTTON'){
1224                     searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1225                     key = splitPlainAttributeKey[0]+'@0';
1226                 }
1227                 
1228                         if(searchElement != null){
1229                                 var keySplit = key.split(dot);
1230                                 var elumentLocation = keySplit.length;
1231                                 var enumKey = key;
1232                                 if (elumentLocation > 1){
1233                                         enumKey = keySplit[keySplit.length - 1];
1234                                 }
1235                                 //check it is undefined or not
1236                                 if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
1237                                                 if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
1238                                                         var multiSlect = [];
1239                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1240                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1241                                                                 }
1242                                                         jsonPolicy[key]= multiSlect;
1243                                                 }else{
1244                                                         console.log(" searchElement.value = > " + searchElement.value);
1245                                                         jsonPolicy[key]= searchElement.value;
1246                                                 }
1247                                 } else {
1248                                         if(searchElement.value != null){
1249                                                         console.log(" searchElement.value = > " + searchElement.value);
1250                                                 jsonPolicy[key]= searchElement.value;
1251                                         }
1252                                 }
1253                         }
1254                 }
1255         }
1256         var uuu = "policycreation/save_policy";
1257         var postData={policyData: policy, policyJSON : jsonPolicy};
1258         $.ajax({
1259             type : 'POST',
1260             url : uuu,
1261             dataType: 'json',
1262             contentType: 'application/json',
1263             data: JSON.stringify(postData),
1264             success : function(data){
1265                 $scope.$apply(function(){
1266                         $scope.data=data.policyData;
1267                         if($scope.data == 'success'){
1268                                 $scope.temp.policy.readOnly = 'true';
1269                                 $scope.safetyChecker = data.policyData.split("#")[2];
1270                                 if ($scope.safetyChecker!=undefined) {
1271                                         Notification.success($scope.safetyChecker);
1272                                 }
1273                                 $scope.pushStatus=data.policyData.split("&")[1];
1274                                 if($scope.pushStatus=="successPush"){
1275                                         Notification.success("Policy pushed successfully");
1276                                 }
1277                                 Notification.success("Policy Saved Successfully.");     
1278                         }else if ($scope.data == 'PolicyExists'){
1279                                                 $scope.savebutton = true;
1280                                                 Notification.error("Policy Already Exists with Same Name in Scope.");
1281                                         }
1282                 });
1283                 console.log($scope.data);
1284             },
1285             error : function(data){
1286                 Notification.error("Error Occured while saving Policy.");
1287             }
1288         });
1289     };
1290     
1291     $scope.validatePolicy = function(policy){
1292         document.getElementById("validate").innerHTML = "";
1293         var splitAt = '*';
1294         var dot ='.';
1295         var jsonPolicy = {};
1296         if(plainAttributeKeys != null){
1297                 for(a = 0; a < plainAttributeKeys.length; a++){
1298                         var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
1299                         console.log(splitPlainAttributeKey[1]); 
1300                         var searchElement = document.getElementById(splitPlainAttributeKey[0]);
1301                         var key = splitPlainAttributeKey[0];
1302                         if(searchElement == null || searchElement.nodeName == 'BUTTON'){
1303                                 searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
1304                                 key = splitPlainAttributeKey[0]+'@0';
1305                         }
1306                         if(searchElement != null){
1307                                 if (enumKeyList.indexOf(key) != -1){
1308                                                 if (splitPlainAttributeKey[1].indexOf("true") !== -1){
1309                                                         var multiSlect = [];
1310                                                         for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
1311                                                                 multiSlect.push(searchElement.selectedOptions[i].value);
1312                                                                 }
1313                                                         jsonPolicy[key]= multiSlect;
1314                                                 }else{
1315                                                         jsonPolicy[key]= searchElement.value;
1316                                                 }
1317                                         if(searchElement.getAttribute("required")){
1318                                                 if(!searchElement.value){
1319                                                         return;
1320                                                 }
1321                                         } 
1322                                 } else {
1323                                         if(searchElement.value != null){
1324                                                 jsonPolicy[key]= searchElement.value;
1325                                                 if(searchElement.getAttribute("required")){
1326                                                         if(!searchElement.value){
1327                                                                 return;
1328                                                         }
1329                                                 }                                               
1330                                         }
1331                                 }
1332                         }
1333                 }
1334         }
1335         var uuu = "policyController/validate_policy.htm";        
1336         var postData={policyData: policy, policyJSON : jsonPolicy};
1337                 $.ajax({
1338                         type : 'POST',
1339                         url : uuu,
1340                         dataType: 'json',
1341                         contentType: 'application/json',
1342                         data: JSON.stringify(postData),
1343                         success : function(data){
1344                                 $scope.$apply(function(){
1345                                         $scope.validateData = data.data.replace(/\"/g, "");
1346                                         $scope.data=data.data.substring(1,8);
1347                                                 var size = data.data.length;
1348                                                 if($scope.data == 'success'){
1349                                                         Notification.success("Validation Success.");
1350                                                         $scope.savebutton = false;
1351                                                         if (size > 18){
1352                                                                 var displayWarning = data.data.substring(19,size  - 1);
1353                                                                 document.getElementById("validate").innerHTML = "Safe Policy Warning Message  :  "+displayWarning;
1354                                                                 document.getElementById("validate").style.color = "white";
1355                                                                 document.getElementById("validate").style.backgroundColor = "skyblue";
1356                                                         }
1357                                                 }else{
1358                                                         Notification.error("Validation Failed.");
1359                                                         document.getElementById("validate").innerHTML = $scope.validateData;
1360                                                         document.getElementById("validate").style.color = "white";
1361                                                         document.getElementById("validate").style.backgroundColor = "red";
1362                                                         $scope.savebutton = true;
1363                                                 }
1364                                                 
1365                                 });
1366                                 console.log($scope.data);       
1367                         },
1368                         error : function(data){
1369                                 Notification.error("Validation Failed.");
1370                                 $scope.savebutton = true;
1371                         }
1372                 });
1373     };
1374
1375     function extend(obj, src) {
1376         for (var key in src) {
1377             if (src.hasOwnProperty(key)) obj[key] = src[key];
1378         }
1379         return obj;
1380     }
1381 }]);/**
1382  * 
1383  */