'use strict';

var ngApp = angular.module('myNgApp', ['ngSanitize']);

ngApp.controller('AppCtrl', ['$scope', '$http', '$timeout', '$sce', function($scope, $http, $timeout, $sce)
{
  $scope.showPageNoDiv = true;
  $scope.documents = [];
  $scope.document = {};
  $scope.pageQueue = [];
  $scope.noOfPageToLoad = 2;
  $scope.references = [];
  $scope.statusFilters = [{id: 0, name: 'All Status'}, {id: 1, name: 'Mandatory'}, {id: 2, name: 'Voluntary'}];
  $scope.tagStatusFilters = [{id: 0, name: 'All Tags'}, {id: 1, name: 'Used Tags'}, {id: 2, name: 'Unused Tags'}];
  $scope.filter = {};
  $scope.filter.status = 0;
  $scope.filter.tagStatus = 0;
  $scope.filter.exactMatch = false;
  $scope.filter.textBlock = false;
  $scope.filter.showSecondaryLabel = false;
  $scope.filter.highlightTextBlock = true;
  $scope.filterData = [];
  $scope.triggerFocused = false;
  $scope.triggerFocusedElement = "";

  $scope.viewerData = <!VIEWER DATA!>;
  $scope.factData = <!FACT DATA!>;
  $scope.presentationData = <!PRESENTATION DATA!>;
  $scope.calculationData = <!CALCULATION DATA!>;
  $scope.periodData = <!PERIOD DATA!>;
  $scope.periodValueData = <!PERIOD VALUE DATA!>;
  $scope.definitionData = <!DEFINITION DATA!>;
  // $scope.pageData = <!PAGE DATA!>;
  $scope.referenceData = <!REFERENCE DATA!>;
  $scope.mandatoryData = <!MANDATORY DATA!>;
  $scope.textblockMetricsData = <!TEXTBLOCKMETRICS DATA!>;
  $scope.continuationData = <!CONTINUATION DATA!>;

  $scope.initIframe = function()
  {
    $scope.initDocumentViewer();
    $scope.getAllPresentation();
    $scope.getAllCalculation();
    $scope.getAllDefinition();
    $scope.getAllMandatoryTag();
    $scope.getTextblockMetrics();
    $scope.getDocumentViewerDetail();
  };

  $scope.getDocumentViewerDetail = function()
  {
    $scope.documentDetail = $scope.viewerData[0];
    $scope.getAllFact(true);
  };

  $scope.getAllFact = function(isInitializeTable)
  {
    $scope.isGridLoading = true;
    $scope.factLists = [];
    $scope.isGridLoading = false;
    $scope.factLists = $scope.factData;
    if(isInitializeTable) {
      $timeout(function() {
        $scope.initTableWithSearch();
      }, 2000);
    }
  };

  $scope.initTableWithSearch = function()
  {
    var table = $('#viewerTable');

    var settings = {
        "sDom": "<t><'row'<p i>>",
        "destroy": true,
        "scrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "_MENU_ ",
            "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
        },
        "iDisplayLength": 1000,
        "scrollY": "18vh",
        "scrollX": true,
        "ordering": false,
        "paging": false,
        "info": false,
        fixedColumns: true
    };

    table.dataTable(settings);
    
    var iframe1 = $('.iframe').contents();
    $('#search-element').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(2, val);
    } );

    $('#search-value').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(3, val);
    } );

    $('#search-unit').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(5, val);
    } );

    $('#search-period').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(6, val);
    } );

    $('#search-scale').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(7, val);
    } );

    $('#search-decimal').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(8, val);
    } );

    $('#search-axis').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(9, val);
    } );

    $('#search-member').on( 'keyup', function () {
      $scope.filterData = [];
      var val = $(this).val();
      gridElmSearch(10, val);
    } );

    $('#filterExactMatch').on( 'change', function () {
      var colvalue1 = $("#search-element").val();
      if(colvalue1 != "") {
        gridElmSearch(2, colvalue1);
      }
      var colvalue2 = $("#search-value").val();
      if(colvalue2 != "") {
        gridElmSearch(3, colvalue2);
      }
      var colvalue3 = $("#search-unit").val();
      if(colvalue3 != "") {
        gridElmSearch(5, colvalue3);
      }
      var colvalue4 = $("#search-period").val();
      if(colvalue4 != "") {
        gridElmSearch(6, colvalue4);
      }
      var colvalue5 = $("#search-scale").val();
      if(colvalue5 != "") {
        gridElmSearch(6, colvalue5);
      }
      var colvalue6 = $("#search-decimal").val();
      if(colvalue6 != "") {
        gridElmSearch(8, colvalue6);
      }
      var colvalue7 = $("#search-axis").val();
      if(colvalue7 != "") {
        gridElmSearch(9, colvalue7);
      }
      var colvalue8 = $("#search-member").val();
      if(colvalue8 != "") {
        gridElmSearch(10, colvalue8);
      }
    });

    function gridElmSearch(col, val) {
      if(col == 3 || col == 7 || col == 8) {
        if($scope.filter.exactMatch) {
          //var regex = '\\b' + val + '\\b';
          var regex = '(?:^|[^-\\w])('+val+')(?:[^-\\w]|$)';
          $('#viewerTable').DataTable().column( col ).search(regex, true, false).draw();
        } else {
          $('#viewerTable').DataTable().column( col ).search(val).draw();
        }
      } else {
          if(val.length >= 3) {
            if($scope.filter.exactMatch) {
              //var regex = '\\b' + val + '\\b';
              var regex = '(?:^|[^-\\w])('+val+')(?:[^-\\w]|$)';
              $('#viewerTable').DataTable().column( col ).search(regex, true, false).draw();
            } else {
              $('#viewerTable').DataTable().column( col ).search(val).draw();
            }
          } else if(val == "") {
            $('#viewerTable').DataTable().column( col ).search("").draw();
          }
      }
 
      filterFocusedElem();
    };

    function filterFocusedElem() {
      $scope.triggerFocused = false;
      iframe1.find(".org-ixbrl-focused-element").each(function() {
        $scope.findAllTags($(this), "#FFFF00");
        iframe1.find(".continuation").each(function() {
          $scope.findAllTags($(this), "#FFFF00");
        });
        iframe1.find(".org-ixbrl-focused-element").removeClass("org-ixbrl-focused-element");
      });

      angular.forEach($scope.filterData, function(obj, key) {
        var selector = '[name="'+obj.fact_name+'"]';
          if(key == 0) {
            var keepGoing = true;
            angular.forEach($scope.factLists, function(factObj, factKey) {
              if(keepGoing) {
                if(factObj.TagName == obj.fact_name && factObj.ContextRef == obj.context_ref) {
                  $scope.handleGridClick(factObj.ElementIdentifier, factObj.TagName, factObj.ContextRef, factObj.PageIdentifier, factObj.IsHiddenElement);
                  keepGoing = false;
                  return false;
                }
              }  
            });
          } 
      });

    };

    $("#show-search-option").on("click", function() {
      $(".card-search").toggleClass("hide", 500);
      var name = $(this).children().attr("class");
      if(name === "fa fa-search") {
        $(this).children().removeClass("fa fa-search");
        $(this).children().addClass("fa fa-close");
      } else {
        $(".search-input").val('');
        $('#viewerTable').DataTable().search( '' ).columns().search( '' ).draw();
        $(this).children().removeClass("fa fa-close");
        $(this).children().addClass("fa fa-search");
        var iframe1 = $('#inlineviewer').contents();
        iframe1.find(".org-ixbrl-focused-element").each(function() {
          // iframe1.find(".org-ixbrl-focused-element").removeAttr("style");
          // iframe1.find(".org-ixbrl-focused-element").attr("style", "background-color:#FFFF00"); //Yellow Color
          $scope.findAllTags($(this), "#FFFF00");
          iframe1.find(".continuation").each(function() {
            $scope.findAllTags($(this), "#FFFF00");
          });
          iframe1.find(".org-ixbrl-focused-element").removeClass("org-ixbrl-focused-element");
        });
      }
    });
    
    $('#viewerTable').DataTable().on('search.dt', function() {
     $scope.filterData = [];
     if($('#search-element').val() !== "" || $('#search-value').val() !== "" || $('#search-unit').val() !== "" || $('#search-period').val() !== "" 
      || $('#search-scale').val() !== "" || $('#search-decimal').val() !== "" || $('#search-axis').val() !== "" || $('#search-member').val() !== "") {
      var dataArray = $('#viewerTable').DataTable().column( 1, { filter : 'applied'} ).data();
       angular.forEach(dataArray, function(obj, key) {
         var data = $.parseHTML(obj);
         console.log(data);
         $scope.filterData.push({'fact_name': data[6].innerText, 'context_ref': data[8].innerText});
       });
     }
    });
    
    if($scope.factLists.length > 0) {
      $scope.getFactDetail($scope.factLists[0].ElementIdentifier, $scope.factLists[0].TagName, $scope.factLists[0].ContextRef);
    }

  };

  $scope.getFactDetail = function(uniqueIdentifier, factName, contextRef)
  {
    angular.forEach($scope.factLists, function(obj, key) {
      if(obj.ElementIdentifier == uniqueIdentifier) {
        // $scope.$apply(function () {
        //   $scope.factDetail = obj;
        // });
        $timeout(function() {
          $scope.factDetail = obj;
          $scope.selectedName = obj.TagName;
          $scope.selectedContextRef = obj.ContextRef;
          $scope.selectedUniqueIdentifier = obj.ElementIdentifier;
          $scope.getContinuationTags($scope.factDetail);
          $scope.viewCalculationAndDefinitionDataInFactProperties();
          $(".loading-overlay").removeClass("is-active");
        }, 1000);
      }
    });
  };

  $scope.viewCalculationAndDefinitionDataInFactProperties = function() {
    $scope.factDetail.calculations = [];
    $scope.factDetail.definitions = [];
    $scope.factDetail.calcualtionName = "";
    $scope.factDetail.definitionParentName = "";
    $scope.factDetail.definitionSubParentName = "";
    var calcualtionParentId = "";
      angular.forEach($scope.calculationData, function(obj, key) {
          if($scope.factDetail.TagName == obj.Name) {
            $scope.factDetail.calcualtionName = $scope.factDetail.TagName;
            calcualtionParentId = obj.Id;
            return false;
          }
      });
    if(calcualtionParentId != "") {
      angular.forEach($scope.calculationData, function(obj, key) {
          if(calcualtionParentId == obj.ParentId) {
            $scope.factDetail.calculations.push(obj.Name);
          }
      });
    }
    
    if($scope.factDetail.IsExtendedElement) {
      var anchoringParentId = "";
      var anchoringSubParentId = "";
      angular.forEach($scope.definitionData, function(obj, key) {
          if($scope.factDetail.TagName == obj.Name) {
            $scope.factDetail.definitionSubParentName = obj.Name;
            anchoringSubParentId = obj.Id;
            anchoringParentId = obj.ParentId;
            return false;
          }
      });
      if($scope.factDetail.definitionSubParentName != "" && anchoringParentId != "") {
        angular.forEach($scope.definitionData, function(obj, key) {
            if(anchoringParentId == obj.Id) {
              $scope.factDetail.definitionParentName = obj.Name;
              return false;
            }
        });
      }
      if(anchoringSubParentId != "") {
        angular.forEach($scope.definitionData, function(obj, key) {
            if(anchoringSubParentId == obj.ParentId) {
              $scope.factDetail.definitions.push(obj);
            }
        });
      }
    }
  };

  $scope.getAllPresentation = function()
  {
      $scope.presentations = $scope.presentationData;
      $timeout(function() {
        $scope.initPresentationTable();
      }, 1000);
  };

  $scope.getAllCalculation = function()
  {
      $scope.calculations = $scope.calculationData;
      $scope.periods = $scope.periodData;
      $scope.period_values = $scope.periodValueData;
      $timeout(function() {
        $scope.initCalculationTable();
      }, 1000);
  };

  $scope.getAllDefinition = function()
  {
      $scope.definitions = $scope.definitionData;
      $timeout(function() {
        $scope.initDefinitionTable();
      }, 1000);
  };

  $scope.getAllMandatoryTag = function()
  {
    $scope.mandatoryTags = $scope.mandatoryData;
      $timeout(function() {
        $scope.initMandatoryTable(); 
      }, 1000);
  };

  $scope.initPresentationTable = function()
  {
    var table = $('#presentationTable');

    var settings = {
        "sDom": "<t><'row'<p i>>",
        "destroy": true,
        "scrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "_MENU_ ",
            "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
        },
        "iDisplayLength": 1000,
        "scrollY": "25vh",
        "ordering": false
    };

    $("#presentationTable").agikiTreeTable({persist: true, persistStoreName: "files"});
  };

  $scope.initCalculationTable = function()
  {
    var table = $('#calculationTable');

    var settings = {
        "sDom": "<t><'row'<p i>>",
        "destroy": true,
        "scrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "_MENU_ ",
            "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
        },
        "iDisplayLength": 1000,
        "scrollY": "25vh",
        "ordering": false
    };

    $("#calculationTable").agikiTreeTable({persist: true, persistStoreName: "files"});
  };

  $scope.initDefinitionTable = function()
  {
    var table = $('#definitionTable');

    var settings = {
        "sDom": "<t><'row'<p i>>",
        "destroy": true,
        "scrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "_MENU_ ",
            "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
        },
        "iDisplayLength": 1000,
        "scrollY": "25vh",
        "ordering": false
    };

    $("#definitionTable").agikiTreeTable({persist: true, persistStoreName: "files"});
  };

  $scope.initMandatoryTable = function()
  {
    var table = $('#mandatoryTable');

    var settings = {
        "sDom": "<t><'row'<p i>>",
        "destroy": true,
        "scrollCollapse": true,
        "oLanguage": {
            "sLengthMenu": "_MENU_ ",
            "sInfo": "Showing <b>_START_ to _END_</b> of _TOTAL_ entries"
        },
        "iDisplayLength": 1000,
        "scrollY": "25vh",
        "ordering": false
    };

    //table.dataTable(settings);
    $("#mandatoryTable").agikiTreeTable({persist: true, persistStoreName: "files"});
  };

  $scope.handleGridClick = function(_uniqueIdentifier, _name, _contextRef, _pageIdentifier, _isHidden)
  {
    if(_isHidden == "1") {
      $('#factPropertyHeadline').pgNotification({
        message: 'Hidden element can\'t be located in the document',
        position: 'left',
        timeout: 3000,
        type: 'info'
      }).show();
    }

    
    var isScrollToView = true;
    $scope.selectedName = _name;
    $scope.selectedContextRef = _contextRef;
    $scope.selectedUniqueIdentifier = _uniqueIdentifier;
    if(_isHidden != "1")
    {
      $scope.scrollToView();
    }
    
    $scope.getFactDetail(_uniqueIdentifier, _name, _contextRef);
  };

  $scope.getNextOrPreviousFactDetail = function(isNext)
  {
    var sequence = $scope.factDetail.Sequence;
    if(isNext) {
      sequence = sequence + 1;
    } else {
      sequence = sequence - 1;
    }

    angular.forEach($scope.factLists, function(obj, key) {
      if(obj.Sequence == sequence) {
        $scope.factDetail = obj;
        $scope.getContinuationTags($scope.factDetail);
        $scope.viewCalculationAndDefinitionDataInFactProperties();
        $scope.selectedName = $scope.factDetail.TagName;
        $scope.selectedContextRef = $scope.factDetail.ContextRef;
        $scope.selectedUniqueIdentifier = $scope.factDetail.ElementIdentifier;
        var _pageIdentifier = $scope.factDetail.PageIdentifier;
        if(!$scope.factDetail.IsHiddenElement)
        {
          $scope.scrollToView();

          $scope.highlightTextBlockingElement(iframe);
        }
      }
    });
  };

  $scope.applyHighlight = function(child, color) {
    child.css({'background-color': color})
  };

  $scope.findAllTags = function(children, color) {
    if (typeof children == "undefined" || children.length === 0) {
      return;
    }
    children.each(function(){
      var child = $(this);
      if (child.children().length > 0) {
        $scope.findAllTags(child.children(), color);
      }
      $scope.applyHighlight(child, color);
    });
  };

  $scope.highlightExcludeTags = function(children) {
    if (typeof children == "undefined" || children.length === 0) {
      return;
    }
    children.each(function() {
      var child = $(this);
      if (child.children().length > 0) {
        $scope.highlightExcludeTags(child.children());
      }
      child.css({'border': '2px dotted red', 'z-index': '9999'});
    });
  };
  
  var continuationTags = [];
  var continuationIdentifiers = [];
  $scope.initDocumentViewer = function()
  {
    var docLoadingNotification = $('#factPropertyHeadline').pgNotification({
      style: 'circle',
      title: 'Document is loading...',
      message: 'Viewer is preparing the document',
      position: 'right',
      timeout: 0,
      type: 'success'
    });
    docLoadingNotification.show();

    var iframe1 = $('#inlineviewer').contents();
    $('#page-container').on('click', '.org-ixbrl-element', function(e) {

        $scope.hideContinuationTagModal();

        if($(this).children()[0].tagName.toLowerCase() === "ix:continuation") {
          $scope.highlightContinuationTags($(this), iframe1);
          return false;
        }

        var name = $(this).children().attr("name");
        var contextRef = $(this).children().attr("contextref");
        var uniqueIdentifier = $(this).attr("id");
        if($(this).attr('class') == "org-ixbrl-element org-ixbrl-selected-element") {
          $(this).css({'background-color': '#FFFF00','cursor': 'pointer'});
          $scope.findAllTags($(this), "#FFFF00");
          iframe1.find(".continuation").each(function() {
            $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
            $scope.findAllTags($(this), "#FFFF00");
          });
          $(this).removeClass("org-ixbrl-selected-element");
        } else {
          iframe1.find(".org-ixbrl-selected-element").each(function() {
            $scope.findAllTags($(this), "#FFFF00");
          });
          iframe1.find(".continuation").each(function() {
            $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
            $scope.findAllTags($(this), "#FFFF00");
          });
          iframe1.find(".org-ixbrl-selected-element").removeClass("org-ixbrl-selected-element");
          iframe1.find(".org-ixbrl-focused-element").css({'background-color': 'orange','cursor': 'pointer'});

          //highlight TextBlock OFF Condition
          if(!$scope.filter.highlightTextBlock) {
            $scope.textBlockOff(iframe1);
          } 

          $(this).addClass("org-ixbrl-selected-element");
          iframe1.find(".org-ixbrl-selected-element").each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });
          $scope.highlightAppendTag(iframe1, uniqueIdentifier);
        }

        var openContinuationTagModal = true;
        $scope.getFactDetail(uniqueIdentifier, name, contextRef, openContinuationTagModal);
        e.stopPropagation();

      });

      $("#page-container").attr("style", "overflow: revert;margin-top: -15px");
      iframe1.find(".org-ixbrl-element").each(function() {
        $scope.findAllTags($(this), "#FFFF00");
      });

      iframe1.find(".exclude").each(function() {
        $(this).css({'border': '2px dotted red', 'z-index': '9999'});
        $scope.highlightExcludeTags($(this));
      });

      //Get continuation tag ids
      $scope.getAllContinuationTags();
      $scope.getAllContinuationIdentifiers();
  };

  $scope.getAllContinuationTags = function() {
      var iframe1 = $('#inlineviewer').contents();
      iframe1.find(".org-ixbrl-element").each(function() {
        if($(this).children().hasClass("non-numberic")) {
          var listOfAppendTags = [];
          var isAppendTag = false;
          var isLowerCaseAttr = false;
          if($(this).children().attr("continuedat")) {
            isLowerCaseAttr = true;
            isAppendTag = true;
          } else if($(this).children().attr("continuedAt")) {
            isLowerCaseAttr = false;
            isAppendTag = true;
          }

          if(isAppendTag)
          {
            var attrName = isLowerCaseAttr ? "continuedat" : "continuedAt";
            var name = $(this).children().attr("name");
            var contextRef = $(this).children().attr("contextref");
            var uniqueIdentifier = $(this).attr("id");
            listOfAppendTags.push($(this).children().attr(attrName));
            var continuedAt = $(this).children().attr(attrName);
            var isTextBlock = $(this).children().attr("escape");
            while(true)
            {
              var elem = iframe1.find("#" + continuedAt);
              if(!elem.attr(attrName)) {
              break;
              }

              continuedAt = elem.attr(attrName);
              listOfAppendTags.push(continuedAt);
            }

            if(name != "" && contextRef != "" && uniqueIdentifier != "") {
                continuationTags.push(
                  {
                   'tag_detail': {'name': name, 'context_ref': contextRef, 'unique_identifier' : uniqueIdentifier, 'is_text_block' : isTextBlock},
                   'continuation_ids': listOfAppendTags
                  });
            }
          }
        }
      });
  };

  $scope.getAllContinuationIdentifiers = function() {
    continuationIdentifiers = $scope.continuationData;
  };

  $scope.scrollToView = function()
  {
    $('.fp-element-class').css({ '-webkit-box-orient' : 'vertical'});
    var iframe1 = $('#inlineviewer').contents();
    iframe1.find(".org-ixbrl-selected-element").css({'background-color': '#FFFF00','cursor': 'pointer'});
    iframe1.find(".org-ixbrl-selected-element").removeClass("org-ixbrl-selected-element");

    iframe1.find(".org-ixbrl-element").each(function() {
      $scope.findAllTags($(this), "#FFFF00");
    });

    iframe1.find(".exclude").each(function() {
      $(this).css({'border': '2px dotted red', 'z-index': '9999'});
      $scope.highlightExcludeTags($(this));
    });
    
    $scope.highlightSearchText(iframe1);

    var isNonFractionElemFound = false;
    iframe1.find(".org-ixbrl-element").each(function(index) {
      if($(this).children()[0].tagName.toLowerCase() !== "ix:continuation") {
        var name = $(this).children().attr("name");
        var contextRef = $(this).children().attr("contextref");
        var uniqueIdentifier = $(this).attr("id");
        if($scope.selectedName == name && $scope.selectedContextRef == contextRef && $scope.selectedUniqueIdentifier == uniqueIdentifier) {
          console.log("Match Found");
          if(!$(this).children().hasClass("non-numberic")) {
            isNonFractionElemFound = true;
          }
          $(this).css({'background-color': 'greenyellow','cursor': 'pointer'});
          $(this).children().css({'background-color': 'greenyellow','cursor': 'pointer'});
          $(this).addClass("org-ixbrl-selected-element");
          $(this).children().each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });

          // $(this)[0].scrollIntoView({block: "center"});
          if($(this).children().children().length > 0) {
            // $(this).children().children().first()[0].scrollIntoView({block: "center"});
            var _obj = $(this).children().children().first();
            while(true) {
              if(_obj.length > 0) {
                if(_obj[0].className == "org-ixbrl-element" || _obj[0].nodeName == "IX:NONFRACTION" || _obj[0].nodeName == "IX:NONNUMERIC" || _obj[0].nodeName == "IX:CONTINUATION") {
                  _obj = _obj.children().first();
                } else {
                  _obj[0].scrollIntoView({block: "center"});
                  break;
                }
              } else {
                break;
              }
            }
          } else {
            $(this)[0].scrollIntoView({block: "center"});
          }

          return false;
        } 
      }
  
    });

    if(isNonFractionElemFound) {
      return false;
    }

    iframe1.find(".continuation").each(function() {
      $(this).css({'background-color': '#FFFF00','cursor': 'pointer'});
      $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
    });

    //highlight TextBlock OFF Condition
    if(!$scope.filter.highlightTextBlock) {
      $scope.textBlockOff(iframe1);
    } 

    var isNonNumbericElemFound = false;
    iframe1.find(".non-numberic").each(function() {
      // $(this).attr("style", "background-color:#FFFF00;display:inherit;cursor: pointer");
      // $(this).children().attr("style", "background-color:#FFFF00;display:inherit;cursor: pointer");
      var name = $(this).attr("name");
      var contextRef = $(this).attr("contextref");
      var uniqueIdentifier = $(this).parent().attr("id");
      if($scope.selectedName.trim() == name.trim() && $scope.selectedContextRef.trim() == contextRef.trim() && $scope.selectedUniqueIdentifier.trim() == uniqueIdentifier.trim()) {
        isNonNumbericElemFound = true;
        $(this).css({'background-color': 'greenyellow','cursor': 'pointer'});
        $(this).children().css({'background-color': 'greenyellow','cursor': 'pointer'});
        $(this).children().each(function() {
          $scope.findAllTags($(this), "greenyellow");
        });

        // $(this)[0].scrollIntoView({block: "center"});
        if($(this).children().children().length > 0) {
          // $(this).children().children().first()[0].scrollIntoView({block: "center"});
          var _obj = $(this).children().children().first();
          while(true) {
            if(_obj.length > 0) {
              if(_obj[0].className == "org-ixbrl-element" || _obj[0].nodeName == "IX:NONFRACTION" || _obj[0].nodeName == "IX:NONNUMERIC" || _obj[0].nodeName == "IX:CONTINUATION") {
                _obj = _obj.children().first();
              } else {
                _obj[0].scrollIntoView({block: "center"});
                break;
              }
            } else {
              break;
            }
          }
        } else {
          $(this)[0].scrollIntoView({block: "center"});
        }

        return false;
      } 
    });

    if(isNonNumbericElemFound) {
      iframe1.find("#"+$scope.selectedUniqueIdentifier).find(".non-numberic, .org-ixbrl-element, .continuation").css({'background-color': 'greenyellow','cursor': 'pointer'});
      iframe1.find("#"+$scope.selectedUniqueIdentifier).find(".non-numberic, .org-ixbrl-element, .continuation").children().css({'background-color': 'greenyellow','cursor': 'pointer'});
    }

    $scope.highlightAppendTag(iframe1, $scope.selectedUniqueIdentifier);
    
    $scope.triggerFocused = false;
    $scope.triggerFocusedElement = "";
    
  };

  $scope.highlightSearchText = function(iframe1) {
    if($scope.triggerFocused) {
      var selector = '[name="'+$scope.triggerFocusedElement+'"]';
      iframe1.find(selector).each(function() {
        // $(this).parent().attr("style", "background-color:orange;cursor: pointer");
        $scope.findAllTags($(this), "orange");
        $(this).parent().addClass("org-ixbrl-focused-element"); 
      });
    } else {
      angular.forEach($scope.filterData, function(obj, key) {
        var selector = '[name="'+obj.fact_name+'"]';
         iframe1.find(selector).each(function() {
          var contextRef = $(this).attr("contextref");
          if(contextRef == obj.context_ref) {
            // $(this).parent().attr("style", "background-color:orange;cursor: pointer");
            $scope.findAllTags($(this), "orange");
            $(this).parent().addClass("org-ixbrl-focused-element"); 
          }
        });
      }); 
    }
  };

  // $scope.toggleCollapse = function()
  // {
  //   if($(".card-advance").hasClass("card-collapsed")) {
  //     $(".card-advance").removeClass("card-collapsed");
  //     $(".card-collapse").find('i').addClass("pg-arrow_maximize");
  //     $(".card-collapse").find('i').removeClass("pg-arrow_minimize");
  //     $(".card-advance").find(".card-body").removeAttr("style", "display:none");
  //     $("#iframeId").attr("style", "height:70vh;width:100% !important;margin-left: -7px;");
  //     $(".card-fact-properities").attr("style", "height:64vh;overflow-y: scroll;width: 105%");
  //     $(".card-maximize-tab").attr("style", "height:20vh;position: relative;bottom: 0px;");
  //     $(".card-maximize-tab").removeClass("card-maximized");

  //   } else {
  //     $(".card-advance").addClass("card-collapsed");
  //     $(".card-collapse").find('i').removeClass("pg-arrow_maximize");
  //     $(".card-collapse").find('i').addClass("pg-arrow_minimize");
  //     $(".card-advance").find(".card-body").attr("style", "display:none");
  //     $("#iframeId").attr("style", "height:50vh;width:100% !important;margin-left: -7px;");
  //     $(".card-fact-properities").attr("style", "height:44vh;overflow-y: scroll;width: 105%");
  //     $(".card-maximize-tab").attr("style", "height:40vh;position: relative;bottom: 0px;");
  //     $(".card-maximize-tab").removeClass("card-maximized");
  //   }
  // };

  $scope.toggleMaximize = function()
  {
    if($(".card-maximize-tab").hasClass("card-maximized")) {
      $(".card-maximize-tab").removeClass("card-maximized");
      $(".card-maximize-tab").removeAttr("style");
      $(".card-icon-maximize").removeClass("pg-fullscreen_restore");
      $(".card-icon-maximize").addClass("pg-fullscreen");
      $(".card-maximize-tab").attr("style", "height:30vh");
      $(".dataTables_scrollBody").attr("style", "position: relative;overflow: auto;max-height: 18vh;width: 100%;");
      $(".presentation_scrollBody").attr("style", "position: relative;bottom: 18px;height: 25vh");
      $(".calculation_scrollBody").attr("style", "position: relative;bottom: 18px;height: 25vh");
      $(".definition_scrollBody").attr("style", "position: relative;bottom: 18px;height: 25vh");
      $(".mandatory_scrollBody").attr("style", "position: relative;bottom: 18px;height: 25vh");
    } else {
      $(".card-maximize-tab").addClass("card-maximized");
      $(".card-maximize-tab").attr("style", "left: 0px; top: 95px; overflow: scroll");
      $(".card-icon-maximize").addClass("pg-fullscreen_restore");
      $(".card-icon-maximize").removeClass("pg-fullscreen");
      $(".dataTables_scrollBody").attr("style", "position: relative;overflow: auto;max-height: 55vh;width: 100%;");
      $(".presentation_scrollBody").attr("style", "position: relative;bottom: 18px;height: 55vh");
      $(".calculation_scrollBody").attr("style", "position: relative;bottom: 18px;height: 55vh");
      $(".definition_scrollBody").attr("style", "position: relative;bottom: 18px;height: 55vh");
      $(".mandatory_scrollBody").attr("style", "position: relative;bottom: 18px;height: 55vh");
    }
  };


  $scope.iframeSize = 1.0;
  $scope.iframeZoom = function(isZoom) {
    if(isZoom) {
      $scope.iframeSize = $scope.iframeSize + 0.1;
    } else {
      $scope.iframeSize = $scope.iframeSize - 0.1;
    }
    // $("#page-container").attr("style", "zoom: "+$scope.iframeSize);
    $("#page-container").attr("style", "zoom: "+$scope.iframeSize+";overflow:revert;margin-top: -15px;");
    return false;
  };


  // $scope.triggerAFV = function(gridObj)
  // {
  //   if(gridObj.parent_id == "")
  //     return true;
    
  //   var factName = gridObj.Name;
  //   $scope.filter.exactMatch = true;
  //   var regex = '\\b' + factName + '\\b';
  //   $('#viewerTable').DataTable().column( 1 ).search(
  //   regex, true, false
  //   ).draw();

  //   var keepGoing = true;
  //   angular.forEach($scope.factLists, function(obj, key) {
  //     if(keepGoing) {
  //       if(obj.TagName == factName) {
  //         $scope.triggerFocused = true;
  //         $scope.triggerFocusedElement = factName;
  //         $scope.handleGridClick(obj.ElementIdentifier, obj.TagName, obj.ContextRef, obj.PageIdentifier, obj.IsHiddenElement);
  //         keepGoing = false; 
  //       }
  //     }  
  //   });

  //   this.$apply($scope.triggerAFVTabClick(factName));

  // };

  $scope.triggerAFV = function(gridObj, type)
  {
    if(gridObj.ParentId == "")
      return true;
    
    $scope.filterData = [];
    var factName = gridObj.Name;
    $scope.filter.exactMatch = true;
    var parentId = gridObj.Id;
    var regex = '\\b';
    var index = 0;
    if(parentId != "") {
      var elemObj = [];
      if(type == 1) {
        elemObj = $scope.presentationData;
      } else if(type == 2) {
        elemObj = $scope.calculationData;
      } else if(type == 3) {
        elemObj = $scope.definitionData;
      }
      angular.forEach(elemObj, function(obj, key) {
          if(parentId == obj.ParentId) {
            if(index > 0) {
              regex += "|" + obj.Name ;
            } else {
              regex +=  obj.Name ;
            }
            index++;
          }
      });
    }

    if(index > 0) {
      regex += "|" + factName + '\\b';
    } else {
      regex += factName + '\\b';
    }
    console.log(regex);
    $('#viewerTable').DataTable().column( 2 ).search(
    regex, true, false
    ).draw();

    var keepGoing = true;
    angular.forEach($scope.factLists, function(obj, key) {
      if(keepGoing) {
        if(obj.TagName == factName) {
          $scope.triggerFocused = true;
          $scope.triggerFocusedElement = factName;
          $scope.handleGridClick(obj.ElementIdentifier, obj.TagName, obj.ContextRef, obj.PageIdentifier, obj.IsHiddenElement);
          keepGoing = false;
        }
      }  
    });

    this.$apply($scope.triggerAFVTabClick(factName));

  };

  $scope.tagNavigationFromMandatoryTab = function(tagObj)
  {
    var factName = tagObj.Prefix.trim() + tagObj.ElementName.trim();
   
    var keepGoing = true;
    angular.forEach($scope.factLists, function(obj, key) {
      if(keepGoing) {
        if(obj.TagName == factName) {
          $scope.handleGridClick(obj.ElementIdentifier, obj.TagName, obj.ContextRef, obj.PageIdentifier, obj.IsHiddenElement);
          keepGoing = false;
        }
      }  
    });

  };

  $scope.triggerAFVTabClick = function(factName) {
    $('#show-search-option').children().removeClass("fa fa-search");
    $('#show-search-option').children().addClass("fa fa-close");
    $("#search-element").val(factName);
    $(".card-search").removeClass("hide");
    $(".grid-filter").show();
    $('[data-target="#fact-viewer"]').trigger('click');
  };

  $scope.openReadMeModel = function()
  {
    $("#popupModal").modal('show');
  };

  $scope.highlightTextBlockingElement = function(iframe)
  {
    //to highlight the address group div's
    iframe.find(".non-numberic").each(function() {
      $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
    });

    iframe.find(".continuation").each(function() {
      $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
    });

    iframe.find(".exclude").each(function() {
      $(this).css({'border': '2px dotted red', 'z-index': '9999'});
      $scope.highlightExcludeTags($(this));
    });

  };

  $scope.iframeMaximize = function() {
    $('#iframe-panel').addClass("col-md-12");
    $('#fact-properities-panel').attr("style", "display: none");
    $('.iframe-maximize').addClass('hide');
    $('.iframe-minimize').removeClass('hide');
  };

  $scope.iframeMinimize = function() {
    $('#iframe-panel').removeClass("col-md-12");
    $('#fact-properities-panel').removeAttr("style");
    $('#fact-properities-panel').attr("style", "background-color: white;padding-left: 0px;");
    $('.iframe-minimize').addClass('hide');
    $('.iframe-maximize').removeClass('hide');
  };

  $scope.showAFV = function() {
    $("#inlineviewer").attr("style", "height:60vh;width:100% !important;overflow: scroll;");
    $('.card-maximize-tab').attr("style", "height:30vh;");
    $(".card-fact-properities").attr("style", "height:54vh;overflow-y: scroll;width: 105%");
    $('.show-afv').addClass('hide');
    $('.hide-afv').removeClass('hide');
  };

  $scope.hideAFV = function() {
    $("#inlineviewer").attr("style", "height:90vh;width:100% !important;overflow: scroll;");
    $('.card-maximize-tab').removeAttr("style");
    $('.card-maximize-tab').attr("style", "display: none");
    $(".card-fact-properities").attr("style", "height:80vh;overflow-y: scroll;width: 105%");
    $('.hide-afv').addClass('hide');
    $('.show-afv').removeClass('hide');
  };

  $scope.showReferenceModal = function(referenceName) {
    $("#referenceModal").modal('show');
    $scope.isRefPageLoading = true;
    $scope.references = [];
    var factName = referenceName.substring(referenceName.indexOf(":")+1);
    var data = [];
    angular.forEach($scope.referenceData, function(obj, key) {
      if(obj.ElementName == factName) {
        data.push(obj);
      }
    });
    $timeout(function() {
        $scope.references = data;
        $scope.isRefPageLoading = false;
    }, 1000);
  };

  $scope.expandValueText = function() {
    if( $('.fp-element-class').css('-webkit-box-orient') == 'vertical' ) {
       $('.fp-element-class').css({ '-webkit-box-orient' : 'unset'});
    } else {
       $('.fp-element-class').css({ '-webkit-box-orient' : 'vertical'});
    }
  };

  $scope.finderActivate = function() {
    finderActivate();
  };

  $scope.showCalculationModal = function(id, elementName, parentIndex) {
    $scope.calculationSummary = {};
    $scope.calculationSummary.elementName = elementName;
    $scope.calculationSummary.parentIndex = parentIndex;
    $scope.calculationSummary.periods = $scope.periods;
    $scope.calculationSummary.periodValueName = [];
    $scope.calculationSummary.periodValues = [];
    console.log($scope.periods);

    var columnIndex = 0;
    var totalPeriod = $scope.calculationSummary.periods.length;
    var name = ['Calculated', 'Mapped', 'Difference'];
    for(var i=0; i<totalPeriod; i++)
    {
      console.log("TotalPeriod=" + totalPeriod);
      var isValueExists = false;
      for(var j=0; j<3; j++)
      {
        if($scope.period_values[parentIndex][columnIndex] !== "-") {
          isValueExists = true;
        }
        columnIndex++;
  
      }

      if(!isValueExists) {
        console.log("i=" + i);
        //$scope.calculationSummary.periods.splice(i, 1);
        console.log($scope.calculationSummary.periods);

        $scope.calculationSummary.periods = jQuery.grep($scope.calculationSummary.periods, function(value) {
          return value != $scope.periods[i];
        });
      }
    }

    angular.forEach($scope.calculationSummary.periods, function(obj, key) {
      console.log(obj);
      console.log($scope.period_values[parentIndex]);
      angular.forEach($scope.periods, function(obj1, key1) {
        if(obj == obj1) {
          var columnIndex = key1 * 3;
          for(var j=0; j<3; j++)
          {
            var indexValue = $scope.period_values[parentIndex][columnIndex];
            $scope.calculationSummary.periodValues.push(indexValue);
            columnIndex++;
          }
        } 
      });
    });

    for(var i=0; i<$scope.calculationSummary.periods.length; i++) {
      $scope.calculationSummary.periodValueName = $scope.calculationSummary.periodValueName.concat(name);
    };

    //get child element calculation
    $scope.calculationSummary.directChilds = [];
    var totalCalculation = $scope.calculations.length;
    var indexValue = parentIndex + 1;
    for(var index = indexValue; index < totalCalculation; index++) {
       if($scope.calculations[index].ParentId == id) {
        var childElement = $scope.calculations[index].Name;
        var childIndex = index;
        var periods = $scope.periods;
        var childColumnIndex = 0;
          for(var i=0; i<totalPeriod; i++)
          {
            var isValueExists = false;
            for(var j=0; j<3; j++)
            {
              if($scope.period_values[index][childColumnIndex] !== "-") {
                isValueExists = true;
              }
              childColumnIndex++;
            }

            if(!isValueExists) {
              periods = jQuery.grep($scope.calculationSummary.periods, function(value) {
                return value != $scope.periods[i];
              });
            }
          }
          
          var periodValues = [];
          angular.forEach(periods, function(obj, key) {
            angular.forEach($scope.periods, function(obj1, key1) {
              if(obj == obj1) {
                var columnIndex = key1 * 3;
                for(var j=0; j<3; j++)
                {
                  var indexValue = $scope.period_values[childIndex][columnIndex];
                  periodValues.push(indexValue);
                  columnIndex++;
                }
              } 
            });
          });

          $scope.calculationSummary.directChilds.push({'childElementName': childElement, 'childIndex': childIndex, 'childPeriods': periods, 'periodValues': periodValues});
       }
    };

    // $scope.calculationSummary.elementName = elementName;
    // $scope.calculationSummary.parentIndex = parentIndex;
    // $scope.calculationSummary.periods = $scope.periods;


    console.log($scope.calculationSummary.periods);
    // console.log($scope.calculationSummary);
    $("#calculationModal").modal('show');
  };

  $scope.showParentViewElement = function() {
    var obj = document.getElementsByClassName("calculation-view");
    $.each(obj[0].children, function(index, value) {
      if(value.children.length > 0) {
        if(value.children[0].children.length > 0) {
          if(value.children[0].children[0].children.length > 0) {
            $("#calculationView"+index).removeClass("hide");
            $("#calculationView"+index).addClass("show");
          }
        }
      }

      // if(value.children[0].children[0].children.length) {
      //   $("#calculationView"+index).removeClass("hide");
      //   $("#calculationView"+index).addClass("show");
      // }
    });
  };

  $scope.highlightAppendTag = function(iframe1, selectedUniqueIdentifier) {
    //Hightlight appendtags
    var listOfAppendTags = [];
    var isAppendTag = false;
    var isLowerCaseAttr = false;
    if(iframe1.find("#" + selectedUniqueIdentifier).children().attr("continuedat")) {
      isLowerCaseAttr = true;
      isAppendTag = true;
    } else if(iframe1.find("#" + selectedUniqueIdentifier).children().attr("continuedAt")) {
      isLowerCaseAttr = false;
      isAppendTag = true;
    }
    
    if(isAppendTag)
    {
      var attrName = isLowerCaseAttr ? "continuedat" : "continuedAt";
      listOfAppendTags.push(iframe1.find("#" + selectedUniqueIdentifier).children().attr(attrName));
      var continuedAt = iframe1.find("#" + selectedUniqueIdentifier).children().attr(attrName);
      while(true)
      {
        var elem = iframe1.find("#" + continuedAt);
        if(!elem.attr(attrName)) {
          break;
        }

        continuedAt = elem.attr(attrName);
        listOfAppendTags.push(continuedAt);
      }
      
      if(listOfAppendTags.length > 0) {
        for(var i=0; i<listOfAppendTags.length; i++) {
          iframe1.find("#" + listOfAppendTags[i]).each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });
        }
      }
    }
  };

  $scope.highlightContinuationTags = function(selectedNode, iframe1) {
      var continuationId = selectedNode.children().attr("id");
      var isTagFound = false;
      angular.forEach(continuationTags, function(tagObj) {
        if(isTagFound) {
          return false;
        }
        angular.forEach(tagObj.continuation_ids, function(id) {
            if(id == continuationId) {
                var tagDetail = tagObj.tag_detail;
                var openContinuationTagModal = true;
                $scope.getFactDetail(tagDetail.unique_identifier, tagDetail.name, tagDetail.context_ref, openContinuationTagModal);
                
                iframe1.find(".org-ixbrl-element").each(function() {
                  $scope.findAllTags($(this), "#FFFF00");
                });

                iframe1.find(".org-ixbrl-element").removeClass("org-ixbrl-selected-element");

                iframe1.find("#"+tagDetail.unique_identifier).addClass("org-ixbrl-selected-element");

                //highlight TextBlock OFF Condition
                if(!$scope.filter.highlightTextBlock) {
                  $scope.textBlockOff(iframe1);
                } 

                $scope.findAllTags(iframe1.find("#"+tagDetail.unique_identifier), "greenyellow");
                
                angular.forEach(tagObj.continuation_ids, function(indexId) {
                    iframe1.find("#"+indexId).addClass("org-ixbrl-selected-element");
                    $scope.findAllTags(iframe1.find("#"+indexId), "greenyellow");
                });

                // if(iframe1.find("#"+tagDetail.unique_identifier).children().children().length > 0) {
                //   iframe1.find("#"+tagDetail.unique_identifier).children().children().first()[0].scrollIntoView({block: "center"});
                // } else {
                //   iframe1.find("#"+tagDetail.unique_identifier)[0].scrollIntoView({block: "center"});
                // }
                
                isTagFound = true;
                return false;
             }
        });
      });
    };


    $scope.highlightTextBlockOnOff = function() {
      var iframe1 = $('#inlineviewer').contents();
      if($scope.filter.highlightTextBlock) {
        $scope.textBlockOn(iframe1);
      } else {
        $scope.textBlockOff(iframe1);
      }
    };

    $scope.textBlockOn = function(iframe1)
    {
      iframe1.find(".org-ixbrl-selected-element").css({'background-color': '#FFFF00','cursor': 'pointer'});
      iframe1.find(".org-ixbrl-selected-element").removeClass("org-ixbrl-selected-element");

      iframe1.find(".org-ixbrl-element").each(function() {
        $scope.findAllTags($(this), "#FFFF00");
      });
      
      $scope.highlightSearchText(iframe1);

      var isNonFractionElemFound = false;
      iframe1.find(".org-ixbrl-element").each(function(index) { 
        if($(this).children()[0].tagName.toLowerCase() !== "ix:continuation") {
          var name = $(this).children().attr("name");
          var contextRef = $(this).children().attr("contextref");
          var uniqueIdentifier = $(this).attr("id");
      
          if($scope.selectedName == name && $scope.selectedContextRef == contextRef && $scope.selectedUniqueIdentifier == uniqueIdentifier) {
            if(!$(this).children().hasClass("non-numberic")) {
              isNonFractionElemFound = true;
            }
            $(this).css({'background-color': 'greenyellow','cursor': 'pointer'});
            $(this).children().css({'background-color': 'greenyellow','cursor': 'pointer'});
            $(this).addClass("org-ixbrl-selected-element");
            $(this).children().each(function() {
              $scope.findAllTags($(this), "greenyellow");
            });
          
            return false;
          } 
        } 

      });
     
      if(isNonFractionElemFound) {
        return false;
      }

      iframe1.find(".continuation").each(function() {
        $(this).css({'background-color': '#FFFF00','cursor': 'pointer'});
        $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
      });
    
      var isNonNumbericElemFound = false;
      iframe1.find(".non-numberic").each(function() {
        // $(this).css({'background-color': '#FFFF00','cursor': 'pointer'});
        // $(this).children().css({'background-color': '#FFFF00','cursor': 'pointer'});
        var name = $(this).attr("name");
        var contextRef = $(this).attr("contextref");
        var uniqueIdentifier = $(this).parent().attr("id");
        if($scope.selectedName.trim() == name.trim() && $scope.selectedContextRef.trim() == contextRef.trim() && $scope.selectedUniqueIdentifier.trim() == uniqueIdentifier.trim()) {
          isNonNumbericElemFound = true;
          $(this).css({'background-color': 'greenyellow','cursor': 'pointer'});
          $(this).children().css({'background-color': 'greenyellow','cursor': 'pointer'});
          $(this).children().each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });
        } 
      });

      if(isNonNumbericElemFound) {
        iframe1.find("#"+$scope.selectedUniqueIdentifier).find(".non-numberic, .org-ixbrl-element, .continuation").css({'background-color': 'greenyellow','cursor': 'pointer'});
        iframe1.find("#"+$scope.selectedUniqueIdentifier).find(".non-numberic, .org-ixbrl-element, .continuation").children().css({'background-color': 'greenyellow','cursor': 'pointer'});
      }

      $scope.highlightAppendTag(iframe1, $scope.selectedUniqueIdentifier);
  };

  $scope.textBlockOff = function(iframe1) {
    iframe1.find(".non-numberic").each(function() {
      var isTextBlock = $(this).attr("escape");
        if(isTextBlock) {
          $(this).parent().css({'background-color': 'transparent','cursor': 'pointer'});
            $scope.findAllTags($(this), "transparent");
        } else {
          $(this).parent().css({'background-color': '#FFFF00','cursor': 'pointer'});
            $scope.findAllTags($(this), "#FFFF00");
        }
    });

    angular.forEach(continuationTags, function(tagObj) {
      var tagDetail = tagObj.tag_detail;
      if(tagDetail.is_text_block) {
        angular.forEach(tagObj.continuation_ids, function(indexId) {
            iframe1.find("#"+indexId).parent().css({'background-color': 'transparent','cursor': 'pointer'});
            $scope.findAllTags(iframe1.find("#"+indexId), "transparent");
        }); 
      } else {
        angular.forEach(tagObj.continuation_ids, function(indexId) {
            $scope.findAllTags(iframe1.find("#"+indexId), "#FFFF00");
        });
      }  
    });

  };

  $scope.getTextblockMetrics = function()
  {
    $scope.texblockMetrics = $scope.textblockMetricsData;
  };

  $scope.showTextblockReportModal = function() {
    $("#textblockReportModal").modal('show');
  };

  $scope.showGridFilters = function(event) {
      var elm = $(event.currentTarget).children().attr("data-target");
      if(elm == "#fact-viewer") {
        $(".grid-filter").show();
        $(".grid-tag-filter").hide();
      } else if(elm == "#fact-comment") {
        $(".grid-comment-filter").show();
        $(".grid-tag-filter").hide();
      } else if(elm == "#mandatory") {
        $(".grid-tag-filter").show();
        $(".grid-filter").hide();
        $(".grid-comment-filter").hide();
      } else {
        $(".grid-filter").hide();
        $(".grid-comment-filter").hide();
        $(".grid-tag-filter").hide();
      }
  };

  $scope.hideContinuationTagModal = function() {
    $("#continuationTagModal").removeClass("show");
    $("#continuationTagModal").addClass("hide");
    $("#continuationTagBuilder").removeClass("show");
    $("#continuationTagBuilder").addClass("hide");
  };
  
  $scope.getContinuationTags = function(factObj) {
    $scope.continuedAtTag = {};
    if(factObj.ElementType == 1) {
      $scope.hideContinuationTagModal();
      return false;
    }
    
    var uniquePageIdentifier = [];
    var elementIdentifier = "";
    if(typeof factObj.ElementIdentifier === "undefined" || factObj.ElementIdentifier == null) {
      elementIdentifier = factObj.UniqueIdentifier;
    } else {
      elementIdentifier = factObj.ElementIdentifier;
    }

    angular.forEach(continuationTags, function(tagObj) {
      if(tagObj.tag_detail.unique_identifier == elementIdentifier) {
        $scope.continuedAtTag.tag_name = tagObj.tag_detail.name;
        $scope.continuedAtTag.unique_identifier = tagObj.tag_detail.unique_identifier;
        $scope.continuedAtTag.page_identifier = factObj.PageIdentifier;
        uniquePageIdentifier.push($scope.continuedAtTag.page_identifier);
        $scope.continuedAtTag.continuedAt = [];
        angular.forEach(tagObj.continuation_ids, function(id) {
            // $scope.continuedAtTag.continuedAt.push(id);
            angular.forEach(continuationIdentifiers, function(identifierObj) {
                if(identifierObj.ContinuationId == id) {
                  if(uniquePageIdentifier.indexOf(identifierObj.PageIdentifier) == -1) {
                    uniquePageIdentifier.push(identifierObj.PageIdentifier);
                    $scope.continuedAtTag.continuedAt.push({'sequence': identifierObj.Sequence, 'continuation_id': identifierObj.ContinuationId});
                    return false;
                  }
                }
            });
        });
      }
    });
    
    console.log($scope.continuedAtTag.continuedAt);
    if(typeof $scope.continuedAtTag.continuedAt !== "undefined") {
      if($scope.continuedAtTag.continuedAt.length > 0) {
        $("#continuationTagModal").removeClass("hide");
        $("#continuationTagModal").addClass("show");
        $("#continuationTagBuilder").removeClass("show");
        $("#continuationTagBuilder").addClass("hide");
      } else {
        $scope.hideContinuationTagModal();
      }
    } else {
      $scope.hideContinuationTagModal();
    }

  };

  $scope.continuationTagNavigation = function(continuedAt) {
    var continuedAtObj = $("#"+continuedAt);
    continuedAtObj[0].scrollIntoView({block: "center"});
  };

  $scope.nonNumericTagNavigation = function(uniqueIdentifier) {
    var continuedAtObj = $("#"+uniqueIdentifier);
    continuedAtObj[0].scrollIntoView({block: "center"});
  };

  $scope.maximizeContinuationTagModal = function() {
    $("#continuationTagBuilder").removeClass("show");
    $("#continuationTagBuilder").addClass("hide");
    $("#continuationTagModal").removeClass("hide");
    $("#continuationTagModal").addClass("show");
  };

  $scope.minimizeContinuationTagModal = function() {
    $("#continuationTagModal").removeClass("show");
    $("#continuationTagModal").addClass("hide");
    $("#continuationTagBuilder").removeClass("hide");
    $("#continuationTagBuilder").addClass("show");
  };
 
}]);



