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