//filter for boq

function copyStringToClipboard (str) {
   // Create new element
   var el = document.createElement('textarea');
   // Set value (string to be copied)
   el.value = str;
   // Set non-editable to avoid focus and move outside of view
   el.setAttribute('readonly', '');
   el.style = {position: 'absolute', left: '-9999px'};
   document.body.appendChild(el);
   // Select text inside element
   el.select();
   // Copy text to clipboard
   document.execCommand('copy');
   // Remove temporary element
   document.body.removeChild(el);
}

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','L3'];
  
  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 == '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 ;
    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){

       //console.log(elements);
       for(var i=0; i<elements.length; i++){
           if(elements[i].properties.length == 2){
               var mm ,activity ;
               
               if(elements[i].properties[0].displayName == 'MemberMark'){
               mm = elements[i].properties[0].displayValue;
               activity = elements[i].properties[1].displayValue;
           }else{
               mm = elements[i].properties[1].displayValue;
               activity = elements[i].properties[0].displayValue;
           }
           
           if(mm.includes(Name) && 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);
           
           }
       }
       if(i == elements.length - 1 ){
           var avg = Math.round(sum/count);
           if(avg == 100){
               listitem.innerHTML =
               '<div class="pull-right progresscircle"><span class="badge badge-pill badge-success pull-right" style = "font-size:60%"> Completed </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,['Room Number','MemberMark'] ,success , null)
        
       



}


function Guardfilter(Room){
    
    var Name = "GD";
    
    var myids = [];
    var ids = [];
    //viewer.clearThemingColors( viewer.model );


  
  // object count 
  var objcount = viewer.model.getData().instanceTree.objectCount;
  var attributes = ['Room Number','MemberMark'];
  
  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 == 'Room Number'){
               try{
                  if(elements[i].properties[1].displayValue.includes(Name)){
                      if(elements[i].properties[0].displayValue == Room){
                          ids.push(elements[i].dbId);
                      }
                  }
               }catch(err){console.log(elements[i].dbId)}
                
               }else{
                   if(elements[i].properties[0].displayValue.includes(Name) ){
                       if(elements[i].properties[1].displayValue ==  Room){
                           ids.push(elements[i].dbId);
                           
                       }
                   }
                  
               }
           }
       
            
          
          
           
     }
     if(ids.length > 0){
               viewer.isolate(ids);
               viewer.fitToView(ids);
               viewer.select(ids);
                       
               
     }else{
         viewer.hide(1);
     }


}

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

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'] ,function(elements){
       console.log(elements);
       
       for(var i=0; i<elements.length; i++){
           for(var j =0 ;j < elements[i].properties.length ;j++){
               
               try{
                   if(elements[i].properties[j].displayCategory == 'Element'){
                   if(elements[i].properties[j].displayName  == 'Area'){
                      
                          area = area + elements[i].properties[j].displayValue * 0.09290304;
                  }
                  
                  if(elements[i].properties[j].displayName  == 'Volume'){
                      
                          volume = volume + elements[i].properties[j].displayValue * 0.0283168466;
                  }
                  
                  if(elements[i].properties[j].displayName  == 'Length'){
                      
                          length = length + elements[i].properties[j].displayValue * 0.3048;
                  }
                   }
               }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 = ['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  == 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 + '<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 GenerateMainTable(){


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

        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;
            });
            $('table').DataTable();

        }
        
});
}


  function updateActivitiesList(){

    var ActivitiesList = document.getElementById('ActivitiesList');
    ActivitiesList.innerHTML = "";
    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;
               //getActivitesProgress(ele.Activity_ID);
               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="Guardfilter(\'' + 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("http://mallofomaninteractiveviewer.audwan.info/includes/boqtable.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
            function retrievetabledb(urn){
                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/wallguards/includes/tablegenerator.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            

            
function retrieveactivitesdb(urn){
                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/includes/getActivites.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function retrieveWorkorderdb(urn){
                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/includes/getWorkOrder.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            } 
            
function updateBOQdb(Level,BOQ,sumCurrent,sumCumulative,urn){
                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/includes/updateboqtable.php?Level=" + Level +"&BOQ=" + BOQ + "&sumCurrent=" + sumCurrent + "&sumCumulative=" + sumCumulative + "&urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function retrieveProgress(urn){
                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/includes/getProgressElements.php?urn=" + urn).then(function(data){
                    return {
                        data
                        
                    }
                    
                });
                
            }
            
function updateElementProgress(progress,area,id,forgeid,urn){

                return $.getJSON("http://mallofomaninteractiveviewer.audwan.info/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("http://mallofomaninteractiveviewer.audwan.info/includes/setWorkorder.php?forgeid=" + forgeid +"&name=" + name + "&activity=" + activity + "&week=" + week + "&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 = ['Length','BOQ_CODE','L3','Value'];
    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;
           forgeid = elements[i].dbId;
           
           for(var j =0; j < elements[i].properties.length ;j++){
               if(elements[i].properties[j].displayCategory.includes("Element")){
                   
               if(elements[i].properties[j].displayName == "Length"){
                   
                   area = elements[i].properties[j].displayValue * 0.3048 * (progress/100);
                   area1 = elements[i].properties[j].displayValue * 0.3048;
               }else if(elements[i].properties[j].displayName == "BOQ_CODE"){
                   boq = elements[i].properties[j].displayValue;
                   
               }else if(elements[i].properties[j].displayName == 'L3'){
                   level = elements[i].properties[j].displayValue;
                   
               }
               else if(elements[i].properties[j].displayName == 'Value'){
                   id = elements[i].properties[j].displayValue;
                   console.log(id);
                   
               }
               }
               
               
           }
           setTimeout(() => {
               
               if(boq == 'P2.K.002.A-2'){
                   area = 1;
                   area1  =1;
                   progress = 100;
               }
           
              //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);
                                   
                               });
                           } 
                           
                       });
                       
                       
                       
        
});
},50);
           
           // 
  }, 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) =>{
                   
                   tree.enumNodeChildren(ele, function (children) {
                       viewer.setThemingColor(children,color,viewer.model);
                       
                       tree.enumNodeChildren(children, function (children1) {
                           
                       viewer.setThemingColor(children1,color,viewer.model);
                           
                       }, false);
                
            }, 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,1);
            }
            else if(progVal >= 25  &&  progVal <= 49){
                
                return color = new THREE.Vector4(1,0.647,0,1);
            }
            else if(progVal >= 50  &&  progVal <= 69){
                //254,238,0
                return color = new THREE.Vector4(0.996,0.9334,0,1);
            }
            else if(progVal >= 70  &&  progVal <= 89){
                //173,255,47
                return color = new THREE.Vector4(0.6784,1,0.184,1);
                
            }
            else if(progVal >= 90  &&  progVal <= 99){
                //124,252,0
                return color = new THREE.Vector4(0.486,0.9882,0,1);
            }
            else if(progVal == 100){
                return color = new THREE.Vector4(0,1,0,1);
            }
            
            
}

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>m²</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.isolate(id);
    viewer.fitToView([id]);
      },200);
}


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


  // 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  == 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 firstweekArry =[];
var secweekArry =[];

function setSquenceOfWork(week){
    
    var selection = viewer.getSelection();
    var doc_urn = viewer.model.getData().urn;
    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"] == "Room Number"){
                            //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 + '\',' + ele +')">' + Activity + '_' + Name + '</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(\'' + Activity + '\',' + ele +')">' + Activity + '_' + Name + '</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(\'' + Activity + '\',' + ele +')">' + Activity + '_' + Name + '</li>';
                            }
                            if(week == 4){
                                var FourthWeek = document.getElementById("FourthWeek");
                                FourthWeek.innerHTML += '<li class="list-group-item list-group-item-action Activity-item" onclick="itemSelection(\'' + Activity + '\',' + ele +')">' + Activity + '_' + Name + '</li>';
                            }
                        }
                        
                    });

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

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 + '</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 + '</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 + '</li>';
                            }
                            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 + '</li>';
                            }
               
               
               

            });
            
        }
        
});
}
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 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 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 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);
}
