'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.filter = {};
  $scope.filter.exactMatch = false;
  $scope.filter.showSecondaryLabel = false;
  $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.initIframe = function()
  {
    $scope.initDocumentViewer();
    $scope.getAllPresentation();
    $scope.getAllCalculation();
    $scope.getAllDefinition();
    $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);
    } else {
      if($scope.factLists.length > 0) {
        $scope.getFactDetail($scope.factDetail.unique_identifier, $scope.factDetail.fact_name, $scope.factDetail.context_ref);
      }
    }
  };

  $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(1, val);
    } );

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

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

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

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

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

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

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

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

    function gridElmSearch(col, val) {
      if(col == 2 || col == 6 || col == 7) {
        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 >= 2) {
            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( 0, { 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.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.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.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.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.attr("style", "background-color:"+color+";display:inherit;cursor: pointer");
    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.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) {
      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).removeAttr("style");
        $(this).attr("style", "background-color:#FFFF00;cursor: pointer");
        $scope.findAllTags($(this), "#FFFF00");
        $(this).removeClass("org-ixbrl-selected-element");
      } else {
        iframe1.find(".org-ixbrl-selected-element").removeAttr("style");
        // iframe1.find(".org-ixbrl-selected-element").attr("style", "background-color:#FFFF00;cursor: pointer");
        iframe1.find(".org-ixbrl-selected-element").each(function() {
          $scope.findAllTags($(this), "#FFFF00");
        });
        iframe1.find(".org-ixbrl-selected-element").removeClass("org-ixbrl-selected-element");

        iframe1.find(".org-ixbrl-focused-element").removeAttr("style");
        iframe1.find(".org-ixbrl-focused-element").attr("style", "background-color:orange;cursor: pointer");

        // $(this).attr("style", "background-color:greenyellow;cursor: pointer");
        $(this).addClass("org-ixbrl-selected-element");
        iframe1.find(".org-ixbrl-selected-element").each(function() {
          $scope.findAllTags($(this), "greenyellow");
        });
      }

      console.log("name=" + name);
      console.log("contextRef=" + contextRef);
      console.log("uniqueIdentifier=" + uniqueIdentifier);
      $scope.getFactDetail(uniqueIdentifier, name, contextRef);
      e.stopPropagation();
    });

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

  $scope.scrollToView = function()
  {
    $('.fp-element-class').css({ '-webkit-box-orient' : 'vertical'});
    var iframe1 = $('#inlineviewer').contents();
    iframe1.find(".org-ixbrl-selected-element").removeAttr("style");
    iframe1.find(".org-ixbrl-selected-element").attr("style", "background-color:#FFFF00;cursor: pointer"); //Yellow Color
    iframe1.find(".org-ixbrl-selected-element").removeClass("org-ixbrl-selected-element");
    iframe1.find(".org-ixbrl-element").each(function() {
      $(this).children().attr("style", "background-color:#FFFF00;display:inherit;cursor:pointer");
    });
    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) {
          console.log("Match Found");
          if(!$(this).children().hasClass("non-numberic")) {
            isNonFractionElemFound = true;
          }
          $(this).attr("style", "background-color:greenyellow;cursor: pointer");
          $(this).children().attr("style", "background-color:greenyellow;cursor: pointer");
          $(this).addClass("org-ixbrl-selected-element");
          $(this).children().each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });
          $(this)[0].scrollIntoView({block: "center"});
          return false;
        } 
      }
  
    });

    if(isNonFractionElemFound) {
      return false;
    }

    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;
        console.log("Non Numberic :: Match Found");
        $(this).removeAttr("style");
        $(this).attr("style", "background-color:greenyellow;display:inherit;cursor: pointer");
        $(this).children().removeAttr("style");
        $(this).children().attr("style", "background-color:greenyellow;display:inherit;cursor: pointer");
        $(this).children().each(function() {
          $scope.findAllTags($(this), "greenyellow");
        });
        $(this)[0].scrollIntoView({block: "center"});
        return false;
      } 
    });

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

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

    //Hightlight appendtags
    var listOfAppendTags = [];
    var isAppendTag = false;
    var isLowerCaseAttr = false;
    console.log($scope.selectedUniqueIdentifier);
    console.log(iframe1.find("#" + $scope.selectedUniqueIdentifier));
    console.log(iframe1.find("#" + $scope.selectedUniqueIdentifier).children());
    if(iframe1.find("#" + $scope.selectedUniqueIdentifier).children().attr("continuedat")) {
      isLowerCaseAttr = true;
      isAppendTag = true;
    } else if(iframe1.find("#" + $scope.selectedUniqueIdentifier).children().attr("continuedAt")) {
      isLowerCaseAttr = false;
      isAppendTag = true;
    }
    
    if(isAppendTag)
    {
      var attrName = isLowerCaseAttr ? "continuedat" : "continuedAt";
      listOfAppendTags.push(iframe1.find("#" + $scope.selectedUniqueIdentifier).children().attr(attrName));
      var continuedAt = iframe1.find("#" + $scope.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]).attr("style", "background-color:greenyellow;display:inherit;cursor: pointer");
          // iframe1.find("#" + listOfAppendTags[i]).children().attr("style", "background-color:greenyellow;display:inherit;cursor: pointer");
          iframe1.find("#" + listOfAppendTags[i]).each(function() {
            $scope.findAllTags($(this), "greenyellow");
          });
        }
      }
    }

    console.log(listOfAppendTags);

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


  $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( 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.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().attr("style", "background-color:#FFFF00;display:inherit;");
    });

    iframe.find(".continuation").each(function() {
      $(this).children().attr("style", "background-color:#FFFF00;display:inherit;");
    });
  };

  $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[0].children[0].children.length) {
        $("#calculationView"+index).removeClass("hide");
        $("#calculationView"+index).addClass("show");
      }
    });
  };
 
}]);



