//filter for boq
function applyBOQfilter(LEVEL,BOQCODE){
    
    
    
    var myids = [];
    var ids = [];
    //viewer.clearThemingColors( viewer.model );


  
  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['BOQ Code (Pro_BOQ Sec_Page_Item)','L3 (Level)','BOQ Code'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           if(elements[i].properties.length == 2){
           if(elements[i].properties[0].displayName.includes('BOQ Code')){
               try{
                  if(elements[i].properties[1].displayValue  == LEVEL){
                      if(elements[i].properties[0].displayValue == BOQCODE){
                          ids.push(elements[i].dbId);
                      }
                  }
               }catch(err){console.log(elements[i].dbId)}
                
               }else{
                   if(elements[i].properties[0].displayValue == LEVEL ){
                       if(elements[i].properties[1].displayValue ==  BOQCODE){
                           ids.push(elements[i].dbId);
                           
                       }
                   }
                  
               }
           }
       
            
          
          
           
     }
     if(ids.length > 0){
               viewer.isolate(ids);
               //viewer.select(ids);
               //keepGrids();
               viewer.fitToView(ids);
               let red = new THREE.Vector4(1, 0, 0, 1);
               var tree = viewer.model.getData().instanceTree;
                ids.forEach((ele) =>{
                   
                   tree.enumNodeChildren(ele, function (children) {
                //viewer.setThemingColor( children, red, viewer.model );
            }, false);

               } );
                       
               
     }else{
         viewer.hide(1);
         //keepGrids();
     }


}

, function(){//console.log("nooo");
});
}

// activites progrss
var eleActivity=[];
var progress_val ;
var globalcheck =[];
function getActivitesProgress(actName,listitem){
  var sum = 0,count =0;
  var Name = "GD";
  var myids = [];
  var myelements;
  var loop =true;
  eleActivity=[];
  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }
  
  
      function success(elements){


       for(var i=0; i<elements.length; i++){
           
           var activity,activity1;
           try{
           if(elements[i].properties[0].displayName == 'L2'){
               
               activity = elements[i].properties[0].displayValue;
               activity1 = elements[i].properties[1].displayValue;
               
           }else{
               
               activity = elements[i].properties[1].displayValue;
               activity1 = elements[i].properties[0].displayValue;
               
           }
           
           
          
           if( activity === actName){
               
               count ++;
               var progressindex = idswithprogerss.indexOf(elements[i].dbId);
                var data;
               if(progressindex != -1 ){
                   sum = sum + parseInt(Forgeid_Progress[progressindex].progress);
                    data = {
               "Element" : elements[i].dbId,
               "Activity" : activity,
               "progress" : parseInt(Forgeid_Progress[progressindex].progress)
           };
               }
               else{
                   data = {
                       "Element" : elements[i].dbId,
                       "Activity" : activity,
                       "progress" : 0
                       
                   };
               }
           eleActivity.push(data);
           
           }
       
       
       }catch(err){}
       
       if(i == elements.length - 1 ){
           console.log(actName + " Count " + count );
           var avg = Math.round(sum/count);
           if(avg == 100){
               listitem.innerHTML =
               '<div class="pull-right progresscircle"><span class="badge badge-pill badge-success " style = "font-size:60%"> Complete </span></div>'
               +  ' <div class="clearfix "><div class="c100 p' + avg + ' mrcode green center"><span>'+ avg + '%</span><div class="slice"><div class="bar"></div><div class="fill"></div></div></div></div>';
           }else{
               
          
           listitem.innerHTML =listitem.innerHTML +  ' <div class="clearfix "><div class="c100 p' + avg + ' mrcode green center"><span>'+ avg + '%</span><div class="slice"><div class="bar"></div><div class="fill"></div></div></div></div>';
           }
         
       }
     }
     
     

}
    
    
     viewer.model.getBulkProperties(myids,['L2','Activity_Code'] ,success , null)
        
       



}


function GoTothreeD(){
if(document.getElementById("mySidenav").classList.contains("sidenav1")){
    $("#MyViewerDiv").addClass("viewer3").removeClass("viewer1");
$("#mySidenav").addClass("sidenav3").removeClass("sidenav1");
viewer.resize();
$("#mySidenav").css("display","none");
$(".fa-street-view").addClass("fa-list").removeClass("fa-street-view");
}
else{
if(document.getElementById("mySidenav").classList.contains("sidenav3")){
    $("#MyViewerDiv").addClass("viewer1").removeClass("viewer3");
$("#mySidenav").addClass("sidenav1").removeClass("sidenav3");
viewer.resize();
$("#mySidenav").css("display","");
$(".fa-list").addClass("fa-street-view").removeClass("fa-list");
}}



    
}


function applyRoomNoFilter(RoomNo){
    
    
    
    var myids = [];
    var ids = [];
    //viewer.clearThemingColors( viewer.model );


  
  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['Room Number'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
           
               try{
                  if(elements[i].properties[0].displayValue  == RoomNo){
                      
                          ids.push(elements[i].dbId);
                      
                  }
               }catch(err){console.log(elements[i].dbId)}
                
               
           
       
            
          
          
           
     }
     if(ids.length > 0){
               viewer.isolate(ids);
               //keepGrids();
               viewer.fitToView(ids);
                       
               
     }else{
         viewer.hide(1);
         //keepGrids();
     }


}

, function(){//console.log("nooo");
});
}

function ElementsCalc(){
var Area = document.getElementById('grandtotArea');
     var Volume = document.getElementById('grandtotVolume');
     var Length = document.getElementById('grandtotLength');
     
    var myids = viewer.getSelection();
    var ids = [];
    var area = 0;
    var volume =0;
    var length =0;
    
    if(myids.length > 0){
viewer.model.getBulkProperties(myids,['Area','Volume','Length','Quantity (m2)'] ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           for(var j =0 ;j < 3;j++){
               
               try{
                   
                   if(elements[i].properties[j].displayName  == 'Area'){
                      
                          area = area + elements[i].properties[j].displayValue * 0.000001;
                  }else{
                      if(elements[i].properties[j].displayName  == 'Quantity (m2)'){
                      
                          area = area + elements[i].properties[j].displayValue;
                  }
                  }
                  
                  if(elements[i].properties[j].displayName  == 'Volume'){
                      
                          volume = volume + elements[i].properties[j].displayValue * 0.000000001;
                  }
                  
                  if(elements[i].properties[j].displayName  == 'Length'){
                      
                          length = length + elements[i].properties[j].displayValue * 0.001;
                  }
                  
               }catch(err){console.log(elements[i].dbId)}
               
           }
               
                
     }
     
    
     
     Area.innerHTML = Math.round(area * 100) /100 + " m²";
     Volume.innerHTML = Math.round(volume * 100) /100 + " m³";
     Length.innerHTML = Math.round(length * 100) /100 + " m";

}, function(){});
}else{
         Area.innerHTML = "na";
     Volume.innerHTML = "na";
     Length.innerHTML = "na";
}
}

function searchByActivityId(activity){
    
    
    
    var myids = [];
    var ids = [];


  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['L2','Activity_Code','Activity-1','Activity-2','Activity-3'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
           
               try{
                //   if(elements[i].properties[0].displayName == 'L2'){
                //   if(elements[i].properties[0].displayValue  == activity && elements[i].properties[1].displayValue !=""){
                      
                //           ids.push(elements[i].dbId);
                      
                //   }
                //   }else{
                //       if(elements[i].properties[1].displayValue  == activity && elements[i].properties[0].displayValue !=""){
                      
                //           ids.push(elements[i].dbId);
                      
                //   }
            //   }
                elements[i].properties.forEach(prop => {
                    if(prop.displayValue.includes(activity + " - ")){
                        ids.push(elements[i].dbId);
                        
                    }
                });
                
                   
               }catch(err){}
  
           
     }
     if(ids.length > 0){
         
               viewer.isolate(ids);
               viewer.select(ids);
              // keepGrids();
               viewer.fitToView(ids);

      
     }else{
         
         viewer.hide(1);
         //keepGrids();
     }


}

, function(){//console.log("nooo");
});
}

//keep grids (dont hide grids)
var gridsid = [];
function keepGrids(){
  
  if(gridsid.length < 1){
    var myids = [];
    var ids = [];

  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['Name'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
               try{
                  if(elements[i].properties[0].displayValue  == 'Model Lines' || elements[i].properties[0].displayValue  == 'Model Text'){
                      
                          ids.push(elements[i].dbId);
                          //viewer.setThemingColor(elements[i].dbId,new THREE.Vector4(0,0,0,0),viewer.model);
                      
                  }
               }catch(err){}
                
               
     }
     gridsid = ids;
     viewer.show(ids);
     
     keepGridsColoring(ids);
}

, function(){//console.log("nooo");
});


}else{
    viewer.show(gridsid);
    keepGridsColoring(gridsid);
}


}


function hideGrids(){
  
  if(gridsid.length < 1){
    var myids = [];
    var ids = [];

  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['Name'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
               try{
                  if(elements[i].properties[0].displayValue  == 'Model Lines' || elements[i].properties[0].displayValue  == 'Model Text'){
                      
                          ids.push(elements[i].dbId);
                          //viewer.setThemingColor(elements[i].dbId,new THREE.Vector4(0,0,0,0),viewer.model);
                      
                  }
               }catch(err){}
                
               
     }
     gridsid = ids;
     viewer.hide(ids);
     

}

, function(){//console.log("nooo");
});


}else{
    viewer.hide(gridsid);
}


}

function keepGridsColoring(ids){
    
    var tree = viewer.model.getData().instanceTree;
                ids.forEach((ele) =>{
                   
                   tree.enumNodeChildren(ele, function (children) {
                       viewer.setThemingColor(children,new THREE.Vector4(0,0,0,0),viewer.model);
                //viewer.setThemingColor( children, red, viewer.model );
            }, false);

               } );
}

function updateBOQtable(){

/*
<tr onclick="applyBOQfilter('01','P2.J.070.A')">
<th scope="row">01</th>
<td>P2.J.070.A</td>
<td>Finishing; Flooring - Epoxy Coating Type FLH-801, Internal sidewalk/walkway</td>
<td>m²</td>
<td>3723.3</td>
<td><input class="form-control" style="width:100px" type="text"/></td>
*/
    var BOQtable = document.getElementById('BOQtable');
    var BOQGrandTotal = document.getElementById('BOQGrandTotal');
    BOQtable.innerHTML = "";
    BOQGrandTotal.innerHTML = "";
    
     
    var doc_urn = viewer.model.getData().urn;

        retrieveBOQdb(doc_urn).then(function(returndata){
        //console.log(returndata.data.BOQs[0].BOQ);
        
        if(returndata.data.BOQs[0].BOQ !== null){
            var sumQuntities =0;
            var sumCumulative =0;
            var sumCurrent =0;
            returndata.data.BOQs.forEach(ele => {
               var row = "";
               row = row + '<tr onclick="applyBOQfilter(\'' + ele.Level +'\',\'' + ele.BOQ + '\')">';
               row = row + '<th class="boq_level" scope="row">' + ele.Level + '</th>';
               row = row + '<th class="boq_code">' + ele.BOQ + '</td>';
               row = row + '<th class="" title="' + ele.Descreption + '">' + ele.Descreption + '</td>';
               row = row + '<th>' + ele.Unit + '</td>';
               row = row + '<th>' + ele.Quantity + '</td>';
               row = row + '<th class="commCertified">' + ele["Total Certified"] + '</td>';
               row = row + '<th class="currCertified">' + ele["Certified Qty"]  + '</td></tr>';
               //row = row + '<td style="width:150px;"><div style="width:100px;"><input class="input_Certif"  type="number" style="width:70px;"><button class="addbtn" type="button">+</button></div></td></tr>';
               sumQuntities = sumQuntities + parseFloat(ele.Quantity);
               sumCumulative = sumCumulative + parseFloat(ele["Total Certified"]);
               sumCurrent = sumCurrent + parseFloat(ele["Certified Qty"]);
               
               sumQuntities = Math.round(sumQuntities * 100) /100;
               sumCumulative = Math.round(sumCumulative * 100) /100;
               sumCurrent = Math.round(sumCurrent * 100) /100;
               
               BOQtable.innerHTML = BOQtable.innerHTML + row;
            });
            
            BOQGrandTotal.innerHTML  = BOQGrandTotal.innerHTML  + '<tr class="clickabletr" style="background:rgba(34,34,34,1)"><th scope="row">Grand Total</th><td></td><td></td><td>mix</td><td>' + sumQuntities + '</td><td id="sumCumulative">' + sumCumulative + '</td><td id="sumCurrent">' + sumCurrent +'</td></tr>';
            
        }
        
});
}


function updateActivitiesList(){

    var ActivitiesList = document.getElementById('ActivitiesList');
    ActivitiesList.innerHTML = "";
    var index =0;
    var doc_urn = viewer.model.getData().urn;

        retrieveactivitesdb(doc_urn).then(function(returndata){
        //console.log(returndata);
        if(returndata.data.EpoxyActivities[0].Activity_ID !== null){
            
            returndata.data.EpoxyActivities.forEach(ele => {
               
               // calculate durations
               var today = new Date();
               var finaldate = new Date(ele.Finish);
               var durations = Math.round((finaldate - today) / (1000*3600*24));
               
               var status;
               if(durations > 0 ){
                    status = '<div class="pull-right progresscircle"><span class="badge badge-pill badge-success " style = "font-size:60%">' + durations + ' days</span>' +  '</div>';
                    
               }
                else {
                    status = '<div class="pull-right progresscircle"><span class="badge badge-pill badge-danger pull-right" style = "font-size:60%">' + durations + ' days</span>' + ' </div>';
                }
                    
               //
               
               var row ="";
               
               //`Activity_ID`, `Activity_Name`, `urn`, `Duration`, `Start`, `Finish`, `Progress`
              row = row + '<a href="#" class="list-group-item list-group-item-action Activity-item"  onclick="searchByActivityId(\'' + ele.Activity_ID + '\')">';
              row = row + '<h6 class="list-group">' + ele.Activity_ID + '</h6>';
              row = row + status;
              row = row + '<br><small calss="list-group">' +  ele.Activity_Name + '</small>';
              row = row + '<br>';
              row = row + '<div>';
              row = row + '<small calss="list-group"> Start Date : ' + ele.Start + '</small> - ';
              row = row + '<small calss="list-group pull-right"> Finish Date : ' + ele.Finish + '</small>';
              row = row + '</div>';
              row = row + '</a>';
              
              
               ActivitiesList.innerHTML = ActivitiesList.innerHTML + row;
               
               index ++;
            if(index == returndata.data.EpoxyActivities.length -1 ){
                setTimeout(() => {
                $(".progresscircle").each(function(key,value){getActivitesProgress($("#ActivitiesList a h6")[key].innerText,value)});
                },1000);
            }

            });
            
        }
        
});
}


function retrieveBOQdb(urn){
                return $.getJSON("./includes/boqtable.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            

            
function retrieveactivitesdb(urn){
                return $.getJSON("./includes/getActivites.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function retrieveWorkorderdb(urn){
                return $.getJSON("./includes/getWorkOrder.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            } 
            
function updateBOQdb(Level,BOQ,sumCurrent,sumCumulative,urn){
                return $.getJSON("./includes/updateboqtable.php?Level=" + Level +"&BOQ=" + BOQ + "&sumCurrent=" + sumCurrent + "&sumCumulative=" + sumCumulative + "&urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function retrieveProgress(urn){
                return $.getJSON("./includes/getProgressElements.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }

function retrieveProjectdata(){
                return $.getJSON("./includes/getprop.php").then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function updateElementProgress(progress,area,id,forgeid,urn){

                return $.getJSON("./includes/updateEleProgress.php?docid=" + id +"&forgeid=" + forgeid + "&area=" + area + "&progress=" + progress + "&urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function updateWorkorderdb(forgeid,name,activity,week,urn){

                return $.getJSON("./includes/setWorkorder.php?forgeid=" + forgeid +"&name=" + name + "&activity=" + activity + "&week=" + week + "&urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function delWorkorderdb(forgeid,week,urn){

                return $.getJSON("/includes/detWorkOrder.php?forgeid=" + forgeid + "&week=" + week + "&urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
        
            
            
function retrievetabledb(urn){
                return $.getJSON("./wallguards/includes/tablegenerator.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }


$(document).on('click', 'button.addbtn', function() {
    var input_value = parseFloat($(this).closest('td').find('.input_Certif').val());
    var currCertified_val = parseFloat($(this).closest('td').prev('.currCertified').text());
    var commCertified_val = parseFloat($(this).closest('tr').find('.commCertified').text());
    
    var boq_level = $(this).closest('tr').find('.boq_level').text();
    var boq_code = $(this).closest('tr').find('.boq_code').text();
   console.log(boq_level + " " + boq_code);
   //update currCertified
   $(this).closest('td').prev('.currCertified').text(input_value + currCertified_val);
   //update cummulative 
   $(this).closest('tr').find('.commCertified').text(input_value + commCertified_val);
   
   var sumCumulative =0;
   var sumCurrent =0;
   //sum of all commCertified
   $(".currCertified").each(function(){
       
       sumCurrent= sumCurrent + parseFloat($(this).text());
   });
   $(".commCertified").each(function(){
       
       sumCumulative= sumCumulative + parseFloat($(this).text());
   });
   //update grand totals
   document.getElementById('sumCurrent').innerText = sumCurrent;
   document.getElementById('sumCumulative').innerText = sumCumulative;
   
   //update database
   
   var doc_urn = viewer.model.getData().urn;
   
   updateBOQdb(boq_level,boq_code,(input_value + currCertified_val),(input_value + commCertified_val),doc_urn).then(function(returndata){
        
        if(returndata.data.Certified[0].updated == "OK"){
            
            //alert(returndata.data.Certified[0].updated)
            
        }
        
});
   
   
});


$(function(){
  $('body').on('click', '.Activity-item', function(){
    $('.list-group-item').removeClass('active');
    $(this).closest('.list-group-item').addClass('active');
  });
});


$(function(){
	$('#search_activitiesList').keyup(function(){	
		var current_query = $('#search_activitiesList').val();
		if (current_query !== "") {
			$(".Activity-item").hide();
			$(".Activity-item").each(function(){
				var current_keyword = $(this).text();
				if (current_keyword.indexOf(current_query) >=0) {
					$(this).show();    	 	
				};
			});    	
		} else {
			$(".Activity-item").show();
		};
	});
});


function getSelectionArea(progress){
    progressbar(true);
    var myids = viewer.getSelection();
    var attributes = ['Volume','BOQ Code','L3 (Level)','Value','id' , 'BOQ Code (Pro_BOQ Sec_Page_Item)' ,'Quantity (m2)'];
    if(myids.length > 0){
       viewer.model.getBulkProperties(myids,attributes ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
               delay(elements,attributes,progress,i,elements.length)
               
               
           
     }
    
    

});
}
}


function progressbar(isValid){
    
    //
     var overlay = document.querySelector('.overlay1');
    var sidenav = document.querySelector('.sidenav');
    var viewer = document.getElementById('MyViewerDiv');

    
    if(isValid){
        //show 
    overlay.classList.remove('hidden');
    sidenav.classList.add('freeze');
    viewer.classList.add('freeze');
        
    }else{
        //hide
        overlay.classList.add('hidden');
        sidenav.classList.remove('freeze');
        viewer.classList.remove('freeze');
    }
}

var mycounter = 0;
function delay(elements,attributes,progress,i,total) {
  setTimeout(() => {
    var level,boq,area,id,forgeid,area1,length;
    try{
     forgeid = elements[i].dbId;
    }catch(err){
        
    }
          
           try{
               for(var j =0; j < attributes.length ;j++){
               try{
               if(elements[i].properties[j].displayName == "Volume"){
                   
                   area = elements[i].properties[j].displayValue * 0.000000001 * (progress/100);
                   area1 = elements[i].properties[j].displayValue * 0.000000001;
               }else if(elements[i].properties[j].displayName.includes("BOQ Code")){
                   boq = elements[i].properties[j].displayValue;
                   
               }else if(elements[i].properties[j].displayName == "L3 (Level)"){
                   level = elements[i].properties[j].displayValue;
                   
               }
               else if(elements[i].properties[j].displayName == 'Id' || elements[i].properties[j].displayName == 'Value' ){
                   id = elements[i].properties[j].displayValue;
                   
               }
                else if(elements[i].properties[j].displayName == "Quantity (m2)"){
                   length = elements[i].properties[j].displayValue;
                  length = parseFloat(length) ;
                   
               }
               }catch(err){
                   if(boq == 'BSH_6.1_001_A'){
                       
                       area = length *  (progress/100);
                       area1 = length  ;
                   }
                   
                  //console.log(length);
               }
               
           }
           }catch(err){
               
           }
           
              //send data then return old data 
                // get which row to add this data
                //console.log($('#BOQtable tr'));
                var doc_urn = viewer.model.getData().urn;
                var currCertified_val,commCertified_val;
                
                   updateElementProgress(progress,area1,id,forgeid,doc_urn).then(function(returndata){
                       
                       
                
            
                       if(returndata.data.Progress[0].updated == "OK"){
                           
                           $('#BOQtable tr').each(function(){
                    if($(this).closest('tr').find('.boq_level').text() == level){
                        if($(this).closest('tr').find('.boq_code').text() == boq){
                            var value1 = parseFloat($(this).closest('tr').find('.currCertified').text());
                            var value2 = parseFloat($(this).closest('tr').find('.commCertified').text());
                            $(this).closest('tr').find('.currCertified').text(Math.round((value1 + area) * 100) /100);
                            $(this).closest('tr').find('.commCertified').text(Math.round((value2 + area) * 100) /100);
                            
                            currCertified_val=Math.round((value1 + area) * 100) /100;
                            commCertified_val=Math.round((value2 + area) * 100) /100;
                        }
                    }
                    
                });
            
                           delay(currCertified_val);
                       }
                       
                       else{
                           
                           lastvalue = area1 * parseFloat(returndata.data.Progress[0].updated) /100;
                           $('#BOQtable tr').each(function(){
                    if($(this).closest('tr').find('.boq_level').text() == level){
                        if($(this).closest('tr').find('.boq_code').text() == boq){
                            var value1 = parseFloat($(this).closest('tr').find('.currCertified').text());
                            var value2 = parseFloat($(this).closest('tr').find('.commCertified').text());
                            $(this).closest('tr').find('.currCertified').text(Math.round((value1 + area - lastvalue) * 100) /100);
                            $(this).closest('tr').find('.commCertified').text(Math.round((value2 + area - lastvalue) * 100) /100);
                            
                            currCertified_val=  Math.round((value1 + area - lastvalue) * 100) /100;
                            commCertified_val=  Math.round((value2 + area - lastvalue) * 100) /100;
                        }
                    }
                    
                });
                           delay(currCertified_val);
                       }
                       updateBOQdb(level,boq,currCertified_val,commCertified_val,doc_urn).then(function(returndata){
                           if(returndata.data.Certified[0].updated == "OK"){
                               updateGrandTot();
                            getProgressdb();
                           }
                           mycounter++;
                           if(mycounter == total ){
                               progressbar(false);
                               mycounter = 0;
                               
                               $(".progresscircle .clearfix").each(function (){
                                   $(this)[0].remove();
                                   
                               });
                               $(".progresscircle").each(function(key,value){
                                   setTimeout(() =>{
                                   getActivitesProgress($("#ActivitiesList a h6")[key].innerText,value)
                                   },500);
                                   
                               });
                           } 
                           
                       });
       
        
});
           
           // 
           
          
  }, 500);
}

var isGray = false;
function setGrayModel(){
    
  // object count 
  if(!isGray){
  var objcount = viewer.model.getData().instanceTree.objectCount;

  let gray = new THREE.Vector4(127/255, 127/255, 127/255, 1);
  for(var value = 1; value < objcount;value++){
      viewer.setThemingColor( value, gray, viewer.model);
  }
  isGray = true;
  presetProgress();
  }else{
      viewer.clearThemingColors( viewer.model );
      isGray = false;
  }
}


function setProgress(){
    if(viewer.getSelection().length > 0){
        
        var progress = document.getElementById("progress_input");
        if(progress.value != ""){
            
            var progVal = parseInt(progress.value);
            let progressColor = getProgressColor(progVal);
            setPrgressColor(viewer.getSelection(),progressColor);
           //updateBOQtable()
           
           getSelectionArea(progVal);
        }
    }else{
        alert("Select Element First !");
    }
    
    
}

function presetProgress(){
    Forgeid_Progress.forEach(function(ele){
        
        var progVal = parseInt(ele.progress);
        var progressColor = getProgressColor(progVal);
        var ids = [ele.forgeid];
            setPrgressColor(ids,progressColor);
    });
}

function setPrgressColor(ids,color){
      var tree = viewer.model.getData().instanceTree;
      
      try{
          
                ids.forEach((ele) =>{
                   viewer.setThemingColor(ele,color,viewer.model);
                   tree.enumNodeChildren(ele, function (children) {
                       viewer.setThemingColor(children,color,viewer.model);
                       
                        tree.enumNodeChildren(children, function (children1) {
                       viewer.setThemingColor(children1,color,viewer.model);
                       
                       tree.enumNodeChildren(children1, function (children2) {
                       viewer.setThemingColor(children2,color,viewer.model);
                
            }, false);
                
            }, false);
            
                //viewer.setThemingColor( children, red, viewer.model );
            }, false);

               } );
      }catch(err){
          
      }
}

var Forgeid_Progress = [];
var idswithprogerss = [];
function getProgressdb(){
    Forgeid_Progress = [];
    idswithprogerss = [];
    var doc_urn = viewer.model.getData().urn;
    retrieveProgress(doc_urn).then(function(returndata){
    if(returndata.data.Progress[0].Forge_id !== null){
        
        returndata.data.Progress.forEach(function(ele){
            Forgeid_Progress.push(
                { 
                    forgeid:parseInt(ele.Forge_id),
                    progress:ele.Progress
                    
                }
            );
            idswithprogerss.push(parseInt(ele.Forge_id));
        });
        //presetProgress();
            
        }
        
    });
    
}

function getProgressColor(progVal){
    var color;
     if(progVal >= 1 && progVal <= 24){
         
                return color = new THREE.Vector4(1,0,0,0.5);
            }
            else if(progVal >= 25  &&  progVal <= 49){
                
                return color = new THREE.Vector4(1,0.647,0,0.5);
            }
            else if(progVal >= 50  &&  progVal <= 69){
                //254,238,0
                return color = new THREE.Vector4(0.996,0.9334,0,0.5);
            }
            else if(progVal >= 70  &&  progVal <= 89){
                //173,255,47
                return color = new THREE.Vector4(0.6784,1,0.184,0.5);
                
            }
            else if(progVal >= 90  &&  progVal <= 99){
                //124,252,0
                return color = new THREE.Vector4(0.486,0.9882,0,0.5);
            }
            else if(progVal == 100){
                return color = new THREE.Vector4(0,1,0,0.7);
            }
            
            
}

const promise = 
function getCurrentBOQ(){
    
        var doc_urn = viewer.model.getData().urn;
        retrieveBOQdb(doc_urn).then(function(returndata){
        //console.log(returndata.data.BOQs[0].BOQ);
        
        if(returndata.data.BOQs[0].BOQ !== null){
            var sumQuntities =0;
            var sumCumulative =0;
            var sumCurrent =0;
            returndata.data.BOQs.forEach(ele => {
               var row = "";
               row = row + '<tr onclick="applyBOQfilter(\'' + ele.Level +'\',\'' + ele.BOQ + '\')">';
               row = row + '<th class="boq_level" scope="row">' + ele.Level + '</th>';
               row = row + '<td class="boq_code">' + ele.BOQ + '</td>';
               row = row + '<td class="" title="' + ele.Descreption + '">' + ele.Descreption + '</td>';
               row = row + '<td>' + ele.Unit + '</td>';
               row = row + '<td>' + ele.Quantity + '</td>';
               row = row + '<td class="commCertified">' + ele["Total Certified"] + '</td>';
               row = row + '<td class="currCertified">' + ele["Certified Qty"]  + '</td></tr>';
               //row = row + '<td style="width:150px;"><div style="width:100px;"><input class="input_Certif"  type="number" style="width:70px;"><button class="addbtn" type="button">+</button></div></td></tr>';
               sumQuntities = sumQuntities + parseFloat(ele.Quantity);
               sumCumulative = sumCumulative + parseFloat(ele["Total Certified"]);
               sumCurrent = sumCurrent + parseFloat(ele["Certified Qty"]);
               
               sumQuntities = Math.round(sumQuntities * 100) /100;
               sumCumulative = Math.round(sumCumulative * 100) /100;
               sumCurrent = Math.round(sumCurrent * 100) /100;
               
               BOQtable.innerHTML = BOQtable.innerHTML + row;
            });
            
            BOQGrandTotal.innerHTML  = BOQGrandTotal.innerHTML  + '<tr class="clickabletr" style="background:rgba(34,34,34,1)"><th scope="row">Grand Total</th><td></td><td></td><td>mix</td><td>' + sumQuntities + '</td><td id="sumCumulative">' + sumCumulative + '</td><td id="sumCurrent">' + sumCurrent +'</td></tr>';
            
        }
        
});
}

function updateGrandTot(){
    var sumCumulative =0;
   var sumCurrent =0;
   //sum of all commCertified
   $(".currCertified").each(function(){
       
       sumCurrent= sumCurrent + parseFloat($(this).text());
   });
   $(".commCertified").each(function(){
       
       sumCumulative= sumCumulative + parseFloat($(this).text());
   });
   //update grand totals
   document.getElementById('sumCurrent').innerText = Math.round(sumCurrent * 100)/100 ;
   document.getElementById('sumCumulative').innerText = Math.round(sumCumulative *100)/100;
}



/// working order 

function itemSelection(activity,id){
    //DCPL2CP12GFF1070
    filterByActivityId(activity);
      setTimeout(() => {
    viewer.select(id);
      },200);
}


function filterByActivityId(activity){
    
    
    
    var myids = [];
    var ids = [];


  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['L2'];
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }

       
       
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       //console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           
           
               try{
                  if(elements[i].properties[0].displayValue  == activity){
                      
                          ids.push(elements[i].dbId);
                      
                  }
               }catch(err){}
  
           
     }
     if(ids.length > 0){
         
               viewer.isolate(ids);
               //keepGrids();
               viewer.fitToView(ids);

      
     }else{
         
         viewer.hide(1);
         //keepGrids();
     }


}

, function(){//console.log("nooo");
});
}
var m =0;
function setSquenceOfWork(week){
    
    var selection = viewer.getSelection();
    var doc_urn = viewer.model.getData().urn;
    var i = 0;
    var exsistCount = 0;
    if(selection.length > 0){
        selection.forEach(function(ele){
            
            viewer.model.getProperties( ele, function(prop){
                    
                    var Activity,Name;
                    prop.properties.forEach(function (item){
                        if(item["displayCategory"].includes("Element")){
                            
                        if(item["displayName"] == "L2"){
                            //console.log(item["displayName"] + ":" + item["displayValue"]);
                            Activity = item["displayValue"];
                        }
                        if(item["displayName"] == "Name"){
                            //console.log(item["displayName"] + ":" + item["displayValue"]);
                            Name = item["displayValue"];
                        }
                        
                        }
                    });
                    
                    updateWorkorderdb(ele,Name,Activity,week,doc_urn).then(function(returndata){
                        if(returndata.data.workingOrder[0].INSERT == "OK"){
                            if(week == 1){
                                var FirstWeek = document.getElementById("FirstWeek");
                                FirstWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + Activity + '\',' + parseInt(ele) +')">' + Activity + '_' + Name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                firstweekArry.push(ele);
                            }
                            if(week == 2){
                                var SecondWeek = document.getElementById("SecondWeek");
                                SecondWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + Activity + '\',' + parseInt(ele) +')">' + Activity + '_' + Name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                secweekArry.push(ele);
                            }
                            if(week == 3){
                                var ThirdWeek = document.getElementById("ThirdWeek");
                                ThirdWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + Activity + '\',' + parseInt(ele) +')">' + Activity + '_' + Name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                thirdweekArry.push(ele);
                            }
                            if(week == 4){
                                var FourthWeek = document.getElementById("FourthWeek");
                                FourthWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + Activity + '\',' + parseInt(ele) +')">' + Activity + '_' + Name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                fourweekArry.push(ele);
                            }
                        }
                        else if(returndata.data.workingOrder[0].INSERT == "exist" ){
                            
                            exsistCount++;
                            m++;
                            
                        }
                        i++;
                        if(selection.length  == i){
                            if(exsistCount > 0){
                                alert(exsistCount +  ' of Selected element aready exists in this week !');
                                
                            }
                            
                        }
                        
                        
                    });

                }, function(){console.log("nooo")} );
            
            
            
        
        });
    }
    else{
        alert('Please Select One Element at Least')
    }
}

var firstweekArry =[];
var secweekArry =[];
var thirdweekArry =[];
var fourweekArry =[];
function updateWorkorder(){
    var doc_urn = viewer.model.getData().urn;
            retrieveWorkorderdb(doc_urn).then(function(returndata){
        //console.log(returndata);
        if(returndata.data.workingOrder[0].forge_id !== null){
            
            returndata.data.workingOrder.forEach(ele => {
                
                var week = ele.week;
                            if(week == 1){
                                var FirstWeek = document.getElementById("FirstWeek");
                                FirstWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + ele.Activity_id + '\',' + parseInt(ele.forge_id) +')">' + ele.Activity_id + '_' + ele.name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele.forge_id + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                firstweekArry.push(parseInt(ele.forge_id));
                            }
                            if(week == 2){
                                var SecondWeek = document.getElementById("SecondWeek");
                                SecondWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + ele.Activity_id + '\',' + parseInt(ele.forge_id) +')">' + ele.Activity_id + '_' + ele.name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele.forge_id + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                secweekArry.push(parseInt(ele.forge_id));
                            }
                            if(week == 3){
                                var ThirdWeek = document.getElementById("ThirdWeek");
                                ThirdWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + ele.Activity_id + '\',' + parseInt(ele.forge_id) +')">' + ele.Activity_id + '_' + ele.name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele.forge_id + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                            
                                thirdweekArry.push(parseInt(ele.forge_id));
                            }
                            if(week == 4){
                                var FourthWeek = document.getElementById("FourthWeek");
                                FourthWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + ele.Activity_id + '\',' + parseInt(ele.forge_id) +')">' + ele.Activity_id + '_' + ele.name + 
                                '<i class="fa fa-trash-o fa-lg float-right deletebt" onclick = "delWorkorder(' + ele.forge_id + ',' + week + ',' + 'this' + ')" aria-hidden="true"></i></li>';
                                fourweekArry.push(parseInt(ele.forge_id));
                            }
               
               
               

            });
            
        }
        
});
}
var islogin = true;
function login(){
    var overlay = document.querySelector('.overlay');
    var sidenav = document.querySelector('.sidenav');
    var viewer = document.getElementById('MyViewerDiv');
    var token = document.getElementById('token');
    var doc_urn = urnId;
    
    if(islogin){
    overlay.classList.remove('hidden');
    sidenav.classList.add('freeze');
    viewer.classList.add('freeze');
    islogin = false;
    }
    else{
        if(token.value == "QWhtYWRVZHdhbktpbmc"){
        overlay.classList.add('hidden');
        
    sidenav.classList.remove('freeze');
    viewer.classList.remove('freeze');
    islogin = true;
    localStorage.setItem("first_time","1");
    //window.open('/viewer.php?doc=dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZXRqbGprN2huM2dpdmNpemR6d2NiaGhzbHk4NHB4MTZfdHV0b3JpYWxfYnVja2V0L09NQS0wMDQtMDAxLUFFQy1BLUJJTS0wMC0wMDA2Lm53Yw&access_code=QWhtYWRVZHdhbktpbmc',"_self")
        window.open('/viewer.php?doc=' + doc_urn + '&access_code=QWhtYWRVZHdhbktpbmc' ,"_self");
    }
    }
}

function overlay_close(){
    var overlay = document.querySelector('.overlay');
    var sidenav = document.querySelector('.sidenav');
    var viewer = document.getElementById('MyViewerDiv');
    overlay.classList.add('hidden');
    sidenav.classList.remove('freeze');
    viewer.classList.remove('freeze');
    islogin = true;
}

function selectall(id){

    var selectionarr = [];
    
    if(id == "FirstWeek"){
        selectionarr = firstweekArry;
        
        
    }
    else if(id == "SecondWeek"){
        selectionarr = secweekArry;
    }
    else if(id == "ThirdWeek"){
        selectionarr = thirdweekArry;
    }
    else if(id == "FourthWeek"){
        selectionarr = fourweekArry;
    }
    
    
    
    
    
    let weeklist = document.getElementById(id).querySelectorAll('li');
    weeklist.forEach((item, index) => {
        if(index > 1)
            item.classList.add("active");
    });
    
    setTimeout(() => {
        viewer.select(selectionarr);
        viewer.fitToView(selectionarr);
        },200);
    
}

function unselectall(id){
    viewer.select();
    viewer.isolate();
    viewer.fitToView();
    
    let weeklist = document.getElementById(id).querySelectorAll('li');
    weeklist.forEach((item, index) => {
        if(index > 1)
            item.classList.remove("active");
    });
    
}

function downloadCSV(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV file
    csvFile = new Blob([csv], {type: "text/csv"});

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename;

    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Hide download link
    downloadLink.style.display = "none";

    // Add the link to DOM
    document.body.appendChild(downloadLink);

    // Click download link
    downloadLink.click();
}


function delWorkorder(id,week,list){

    
    var doc_urn = viewer.model.getData().urn;
    removeAnimation(list);
     delWorkorderdb(id,week,doc_urn).then(function(returndata){
         
         if(returndata.data.workingOrder[0].Delete == "OK"){
             
         }
         
});


}

function removeAnimation(list){
    
    $(list).closest("li").css("background-color", "red");
        $(list).closest("li").fadeOut( "slow", function() {
        $(list).closest("li").remove();
        
    });
}


window.onload = (event) => {
  progressbar(true);
};

function RefreshTable(){
    
    GenerateMainTable();
}
function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");
    
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        
        for (var j = 0; j < cols.length; j++) 
            row.push('"' + cols[j].innerText + '"');
        
        csv.push(row.join(","));        
    }

    // Download CSV file
    downloadCSV(csv.join("\n"), filename);
}

var x =0;
function GenerateMainTable(){


    var BOQtable = document.getElementById('BOQtable');
    BOQtable.innerHTML = "";
    var doc_urn='P2.J';

        retrievetabledb(doc_urn).then(function(returndata){
        //console.log(returndata.data.BOQs[0].BOQ);
        
        if(returndata.data.BOQs[0].BOQ !== null){
            var sumQuntities =0;
            var sumCumulative =0;
            var sumCurrent =0;
            returndata.data.BOQs.forEach(ele => {
               var row = "";
               row = row + '<tr onclick="applyBOQfilter(\'' + ele.Level +'\',\'' + ele.BOQ + '\')">';
               row = row + '<th class="boq_level" scope="row">' + ele.Level + '</th>';
               row = row + '<td class="boq_code">' + ele.BOQ + '</td>';
               row = row + '<td class="" title="' + ele.Descreption + '">' + ele.Descreption + '</td>';
               row = row + '<td>' + ele.Unit + '</td>';
               row = row + '<td>' + ele.Quantity + '</td>';
               //row = row + '<td class="commCertified">' + ele["Total Certified"] + '</td>';
               row = row + '<td class="currCertified">' + ele["Certified Qty"]  + '</td></tr>';
               //row = row + '<td style="width:150px;"><div style="width:100px;"><input class="input_Certif"  type="number" style="width:70px;"><button class="addbtn" type="button">+</button></div></td></tr>';
               sumQuntities = sumQuntities + parseFloat(ele.Quantity);
               sumCumulative = sumCumulative + parseFloat(ele["Total Certified"]);
               sumCurrent = sumCurrent + parseFloat(ele["Certified Qty"]);
               
               sumQuntities = Math.round(sumQuntities * 100) /100;
               sumCumulative = Math.round(sumCumulative * 100) /100;
               sumCurrent = Math.round(sumCurrent * 100) /100;
               
               BOQtable.innerHTML = BOQtable.innerHTML + row;
            });
            if(x == 0){
                $('table').DataTable({"lengthMenu": [25]});
                x++;
            }
            
        }
        
});
}


function markupSaveAs(){
  var cube = viewer.getExtension('Autodesk.ViewCubeUi');
  cube.setViewCube('top'); 
  viewer.fitToView();
  setTimeout(()=>{
  viewer.fitToView();
  setTimeout(() =>{
  viewer.loadExtension('Autodesk.Viewing.Wireframes').then(() =>{
  viewer.loadExtension('Autodesk.Viewing.MarkupsCore').then(function (markupCore) {
      viewer.getExtension('Autodesk.Viewing.Wireframes').activate();
      markupcore = markupCore;
      markupCore.enterEditMode();
      markupcore.leaveEditMode();
    var screenshot = new Image();
  screenshot.onload = function () {

          // load the markups
          //markupcore.show();
          //markupcore.loadMarkups(markupSVG, "Mrcode_layer");

          // ideally should also restore the state of Viewer for this markup

          // prepare to render the markups
          var canvas = document.getElementById('snapshot');
          canvas.width = viewer.container.clientWidth;
          canvas.height = viewer.container.clientHeight;
          var ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(screenshot, 0, 0, canvas.width, canvas.height);

          markupcore.renderToCanvas(ctx, function() {
            // hide the markups
            //markupCore.hide();

            var canvas = document.getElementById('snapshot');

            const a = document.createElement('a');
            //a.style = 'display: none';
            document.body.appendChild(a);

            a.href = canvas.toDataURL();
            a.download = 'Conpass_ScreenShot.png';
            a.click();

            document.body.removeChild(a);
          }, true);

          // hide the markups
          markupcore.hide();
      viewer.getExtension('Autodesk.Viewing.Wireframes').deactivate();
};

// Get the full image
viewer.getScreenShot(viewer.container.clientWidth, viewer.container.clientHeight, function (blobURL) {
    screenshot.src = blobURL;
});
                   
                });
  });
  },500);
  },500);
    
}


var myarray = [];
function extractAttributes(){
    
    
    // use Prop db quary 
    var thePromise = viewer.model.getPropertyDb().executeUserFunction(userFunction);
    thePromise.then(function(attrarray){
        let unique = [...new Set(attrarray.map(item => item))];
         myarray = unique;
         getAttributes();
         getoperators();
         //return myarray;
        
    });
    
    //var attri = ['Trade'];
    //return  attri ;
}

function getAttributes(){
    
    var attrlist = document.getElementById('attr_List');
    attrlist.innerHTML ="";
  myarray.forEach(ele => {
      
      attrlist.innerHTML = attrlist.innerHTML + '<option value="' + ele + '">' + ele + '</option>';
      
  }
      );
      

    
}

function getoperators(){
    var oprator = ["equal","does not Equal","Contains","Does not contain"];
    
    var attrlist = document.getElementById('oprator_List');
    attrlist.innerHTML ="";
  oprator.forEach(ele => {
      
      attrlist.innerHTML = attrlist.innerHTML + '<option value="' + ele + '">' + ele + '</option>';
      
  }
      );
}

//create use function 
function userFunction(pdb){
    var attributes = [];
    pdb.enumAttributes(function(i,attrD,attrR){
       if(attrD.category.includes("OBJ") || attrD.category.includes("Element") || attrD.category.includes("Sohar"))
        attributes.push(attrD.displayName); 
    });
    
    return attributes;
}

function conditions(){
    var conditions = [
    "elements[i].properties[0].displayValue.includes('Routing')"];
    
    return conditions;
}
var attributes
function filterByAttr() {
    
    extractAttributes();

}


/* add button function */

function addtomytable(){
    
    var filtertable = document.getElementById('filtertable');
    var attribute = document.getElementById('attr_List');
    var oprator = document.getElementById('oprator_List');
    var attr_value = document.getElementById('Attr_value');
    filtertable.innerHTML = filtertable.innerHTML + '<tr><td>' + attribute.value + '</td><td>' + oprator.value +'</td><td>' + attr_value.value + '</td>' + '<td><button onclick="removefromtable(' +  filtertable.rows.length + ')" type="button" class="btn btn-dark "><i class="fa fa-trash fa-lg"></i></button></td></tr>';
        
     
}


function removefromtable(index){
    $('table').on('click', 'button', function(e){
   $(this).closest('tr').remove();
});
}

function applyfilter(){
    var filtertable = document.getElementById('filtertable');
    var attrs =[];
    var condition =[];
    for(var i=1;i<filtertable.rows.length;i++){
        attrs.push(filtertable.rows[i].cells[0].innerText);
        //conditions
        
        //"elements[i].properties[" + (i-1).toString() + "].displayValue" 
        
        switch (filtertable.rows[i].cells[1].innerText) {
            case "equal":
                condition.push("elements[i].properties[" + "MRCODEINDEX" + "].displayValue"  + " == '" + filtertable.rows[i].cells[2].innerText + "'");
                break;
            case "does not Equal":
                condition.push("elements[i].properties[" + "MRCODEINDEX" + "].displayValue"  + " != '" + filtertable.rows[i].cells[2].innerText + "'");
                break;
            case "Contains":
                condition.push("elements[i].properties[" + "MRCODEINDEX" + "].displayValue"  + ".includes('" + filtertable.rows[i].cells[2].innerText +"')");
                break;
            case "Does not contain":
                condition.push("!elements[i].properties[" + "MRCODEINDEX" + "].displayValue"  + ".includes('" + filtertable.rows[i].cells[2].innerText+"')");
                break;
            
        }
        
        
    }
    
    
    var myids = [];
    var ids = [];
  
  
  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  let unique = [...new Set(attrs.map(item => item))];
  var attributes = unique;
  
  for(var value = 1; value < objcount;value++){
      myids.push(value);
  }
  //console.log(attributes + "\n" + condition[0]);
  
   viewer.model.getBulkProperties(myids,attributes ,function(elements){
       console.log(elements);
       
       
       for(var i=0; i<elements.length; i++){
           //mapping add attrib with elements attrib
       var attrseq =[];
       for(var x=0;x<attrs.length;x++){
           for(var y=0;y<elements[i].properties.length;y++){
               if(elements[i].properties[y].displayName == attrs[x]){
                attrseq.push(y);
                break;
               }
           }
       }
           var bools = true;
           var count=0;
           condition.forEach(function(cond){
               try{
               bools = bools && eval(cond.replace("MRCODEINDEX",attrseq[count].toString()));
               }catch(err){
                   // add timeout then try again
               }
               count++;
               //ids.push(elements[i].dbId);
           });
           
           if(bools)
            ids.push(elements[i].dbId);
          
          
           
     }
     

               viewer.isolate(ids);
               viewer.fitToView(ids);


}

, function(){//console.log("nooo");
});
}
