angular.module('ANGApp').controller("SearchCtrl", 
  function($scope,$http,$location,ANGService,Auth,GlobalFuncService){

  var searchTypeItems = 
  {
    'cif': [{name:'#srcif'}],
    'acct': [{name:'#sracct'}],
    'time': [{name:'#srtime'},{name:'#srtimeprd',
    "columns": [
      { "width": "80px" },
      { "width": "120px" },
      { "width": "120px" },
      { "width": "120px" },
      { "width": "120px" }
      ]
    }] 
  };

  var g_fromview = GlobalFuncService.getCurrData().search.fromview;  

  $scope.state ={dispsearch:false};
  $scope.search ={};
  $scope.search.searchtype="acct";
  if (!g_fromview) {
    initSearch();
  }

  $scope.enableView=0; 

  $scope.$watch('search.searchtype', function() {
    $scope.searchClear();
  });

  // hotkeys for #search page
  if (GlobalFuncService.loadSearchKeys()) {
    $(document).keydown(function(e) {
      var page = $location.path();
      if (page == '/search') {
        
          if (e.keyCode == 13) {  // Enter
          document.getElementById("b_search").click();
          }
          /*
        if(e.altKey) {
          switch (e.keyCode) {
            case 76: // l
              Auth.logout();
              window.location.href = "#/login";
              return false;          
          }        
        }
        */
          return;
      }
    });     
  }

  function initSearch(){      
    // dynamically setup our select options list
    var acctprexlist = Auth.getAcctTypeList();
      var sel = $('#searchacctprefix');
      sel.empty();
    $.each(acctprexlist.split(','), function(){
          sel.append('<option value="'+this+'">'+this+'</option>');
      });  

    var selfirst = document.getElementById('searchacctprefix').options[0];
    selfirst.selected = true;  
    //selfirst[0].selectedIndex = 0;
    //selfirst.find('option:eq(0)').prop('selected', true);  
    //selfirst.val(selfirst.find('option').first().val());
    $scope.search.hasMore=false;
    $scope.search.needInput=false;
    $scope.search.docid="";    
    $scope.selected = { 1:{row:null,index:null,itempacked:null},
              2:{row:null,index:null,itempacked:null}};
    $scope.enableView=0;

    // don't clear if from view page, re-show the grid table
    if (g_fromview) {

      var search = GlobalFuncService.getCurrData().search;
      $scope.search.acctname= search.acctname;
      $scope.search.ignoreautoview = true;

      var btnType = 'b_' + search.searchtype;
      document.getElementById(btnType).click();    // call twice! don't know why, but it is needed    

      if (search.searchtype == 'acct') {
        var selidx = document.getElementById('searchacctprefix').options[search.acctprefixidx+1];
        selidx.selected = true;
      }
      document.getElementById("b_search").click();

      // clear from view flag so that user may change type
      GlobalFuncService.setCurrDataFromView(false);
      g_fromview = false;            
    } else {
      document.getElementById("b_clear").click();    // first call does nothing!        
    }
  }  

  //build the search criteria on the fly
  function searchCriteria(){
    return "randint=" + Math.random();
  }

  function pad(num, places) {
    var zero = places - num.toString().length + 1;
    return Array(+(zero > 0 && zero)).join("0") + num;
  }

  function searchSetUrl(type) {

    var param1 = "-1";
    if (!param1) param1 = "-1";

    var stype = $scope.search.searchtype;
    if (type == "#srtimeprd")
    {
      stype = "srtimeprd"; 

      // get current selected row
        var nRow =  $scope.selected[1].row.attr('ANG-tindex');  
        var searchtables= searchTypeItems[$scope.search.searchtype];
        var searchtype = searchtables[0].name;              

        // get current selected cif#, acct#, etc
      var mytable = $(searchtype).DataTable();
      param1 = mytable.data()[nRow].d1;
    }

    var search_url = GlobalFuncService.serviceUrl(false) + "/search/get/"
      + Auth.getSessionId() + "/" + stype + "/" + param1 + "/" + param2 + "/" + param3;        

    //console.log("Searching : " + search_url);
    return search_url;
  }

  function searchTarget(searchobj){
    var searchtype = searchobj.name;
    var columns = null;
    //alert('scrolly: ' +$(searchtype).data('scrolly'));
    if(searchobj.columns){
      columns = searchobj.columns;
    }
    $(searchtype).show();
    $(searchtype+'_wrapper').show();
    var step = $(searchtype).data('step');
    $scope.selected[step].row=null;
    $scope.selected[step].index=null;
    $scope.SetView(step);
    if ( $.fn.dataTable.isDataTable(searchtype) ) {
      table = $(searchtype).DataTable();
      table.ajax.url(searchSetUrl(searchtype)).load();
      //table.ajax.reload();
    }else{
      table = $(searchtype)
      .on('init.dt', function () {
        $(searchtype).on( 'click', 'tr', function () {
          $( searchtype+' tr.selected').removeClass('selected');
          if ( $scope.selected[step].index == $(this).attr('ANG-tindex')) {
            $scope.SetSelected(step,null);
          }else{
            $(this).addClass('selected');
            $scope.SetSelected(step,$(this));
          }
        });

        $(searchtype).on( 'dblclick', 'tr', function () {  
          var stype = $scope.search.searchtype;
          if (stype == "time") {
            $scope.SetSelected(step,$(this)); 
            $scope.selectTime();        
          } else {
            $scope.SetSelected(step,$(this));           
            $scope.viewSignature(false);
            $scope.SetSelected(step,$(this));          
          }      
        });        
      })
      .dataTable( {
        "scrollY": $(searchtype).data('scrolly'),
        "scrollX": columns==null?false:true,
        "columns":columns,
        "paging":   false,        
        "searching":   false,
        "processing": true,
        "serverSide": false,
        "ajax": {
          //"url":'data/demo' +searchtype.replace('#','')+'.txt',
          "url":searchSetUrl(searchtype),      
          "type": "GET",
          //"data":searchCriteria(),
          "beforeSend": function() {
            $scope.search.inputerror=false;            
            $scope.search.processing=true;
            if (!$scope.$$phase) $scope.$apply();
          },
          "complete": function(resp) {
            $scope.search.processing=false;        
            var obj = resp.responseJSON;
            $scope.search.hasMore = obj.hasMore;
            if (!$scope.$$phase) $scope.$apply();

            var stype = $scope.search.searchtype;
            if (stype == "time") {
              // if (obj.rows == 1 && $scope.search.ignoreautoview == false) {
              //   setTimeout(function() { 
                //     //$scope.selected[1].index=0;
              //     $scope.selectTime();
              //     document.getElementById("b_select").click();  
              //   }, 500);              
              // }
            }
            else {
              if (obj.rows == 1 && $scope.search.ignoreautoview == false) {
                setTimeout(function() {  
                    //$scope.selected[2].index=0;
                    $scope.viewSignature(true);                    
                  document.getElementById("b_search").click();              
                }, 500);              
              }
            }
          },
          "error": function(resp) {      
            $scope.search.processing=false;  
            $scope.search.inputerror=true;                  
            if (!$scope.$$phase) $scope.$apply();            
          },
        },
        "columns": [
          { "data": "d1" },
          { "data": "d2" }
        ],                
        "fnCreatedRow": function( nRow, aData, iDataIndex ) {
                // Bold the grade for all 'A' grade browsers
                $(nRow).attr('ANG-tindex',iDataIndex);
              }
          });
    }
  }

  // TODO... perhaps combine with searchTarget
  function searchTargetTime(searchobj){
    var searchtype = searchobj.name;
    var columns = null;
    //alert('scrolly: ' +$(searchtype).data('scrolly'));
    if(searchobj.columns){
      columns = searchobj.columns;
    }
    $(searchtype).show();
    $(searchtype+'_wrapper').show();
    var step = $(searchtype).data('step');
    $scope.selected[step].row=null;
    $scope.selected[step].index=null;
    $scope.SetView(step);
    if ( $.fn.dataTable.isDataTable(searchtype) ) {
      table = $(searchtype).DataTable();
      table.ajax.url(searchSetUrl(searchtype)).load();
      //table.ajax.reload();
    }else{
      table = $(searchtype)
      .on('init.dt', function () {
        $(searchtype).on( 'click', 'tr', function () {
          $( searchtype+' tr.selected').removeClass('selected');
          if ( $scope.selected[step].index == $(this).attr('ANG-tindex')) {
            $scope.SetSelected(step,null);
          }else{
            $(this).addClass('selected');
            $scope.SetSelected(step,$(this));
          }
        });

        $(searchtype).on( 'dblclick', 'tr', function () {          
          $scope.SetSelected(step,$(this)); 
          $scope.viewSignature(false);
          $scope.SetSelected(step,$(this));    
        });        
      })
      .dataTable( {
        "scrollY": $(searchtype).data('scrolly'),
        "scrollX": columns==null?false:true,
        "columns":columns,
        "paging":   false,        
        "searching":   false,
        "processing": true,
        "serverSide": false,
        "ajax": {
          //"url":'data/demo' +searchtype.replace('#','')+'.txt',
          "url":searchSetUrl(searchtype),      
          "type": "GET",
          //"data":searchCriteria(),
          "beforeSend": function() {
            $scope.search.inputerror=false;            
            $scope.search.processing=true;
            if (!$scope.$$phase) $scope.$apply();
          },
          "complete": function(resp) {
            $scope.search.processing=false;  
            var obj = resp.responseJSON;
            if (!$scope.$$phase) $scope.$apply();  

            if (obj.rows == 1 && $scope.search.ignoreautoview == false) {
              setTimeout(function() {  
                  $scope.viewSignature(true);                    
                document.getElementById("b_select").click();              
              }, 500);              
            }                    
          },
          "error": function(resp) {      
            $scope.search.processing=false;  
            $scope.search.inputerror=true;                  
            if (!$scope.$$phase) $scope.$apply();            
          },                        
        },
        "columns": [
          { "data": "d1" },
          { "data": "d2" }
        ],        
        "fnCreatedRow": function( nRow, aData, iDataIndex ) {
                // Bold the grade for all 'A' grade browsers
                $(nRow).attr('ANG-tindex',iDataIndex);
              }
          });
    }
  }  

  function hideTarget(searchtype){
    //console.log(searchtype);
    $(searchtype+'_wrapper').hide();
    $(searchtype).hide();
  }

  function padNumFormatter(inputnumber,padding) {
    var number = parseInt(inputnumber);
    var strnum = number.toString();

        if (strnum.length > padding) {
      inputnumber = strnum.substring(0, padding);
        }   
        /*
        else {
      inputnumber = pad(number, padding);  // pad 0's            
        }
        */  
    return inputnumber;
  }

  $scope.cifNumChange=function() {
    $scope.search.cifnumber = padNumFormatter($scope.search.cifnumber, 10);
    $scope.search.ignoreautoview=false;    
  }

  $scope.acctPrefixChange=function() {
    var idx = document.getElementById('searchacctprefix').selectedIndex;
    $scope.search.acctprefixidx = idx;
    $scope.search.ignoreautoview=false;    
  }

  $scope.acctNumChange=function(type) {
    switch(type) {
      case 'A': case 'B':
        $scope.search.acctnumlen = 12;
        break;

      case 'C': case 'D': default:
        $scope.search.acctnumlen = 12;
        break;
    }    
    $scope.search.acctnumber = padNumFormatter($scope.search.acctnumber, $scope.search.acctnumlen);
    $scope.search.ignoreautoview=false;    
  }
  
  $scope.setSearchType=function(type){  
    $scope.search.searchtype = type;
  }

  $scope.SetView= function(level){
    //console.log('SetView : ' +level)
    $scope.enableView= level;
  }
  
  $scope.SetSelected = function(level,row){
    //console.log('SetSelected : ' +level + ":" + row)
    $scope.$apply(function() {
        $scope.selected[level].row=row;   
        if(row!=null) {
          $scope.selected[level].index=row.attr('ANG-tindex');
        }
        else
          $scope.selected[level].index=null;            
    });
  }
  
  $scope.searchSignatures = function(){
    // check valid session
    ANGService.isSessionValid(Auth.getSessionId()).then(function(result){
      var res = result.data.IsSessionValidResult;
      if (res == "OK") {
        // search sig
        $scope.search.needInput=false;
        $scope.state.dispsearch=true;
        var searchtables= searchTypeItems[stype];
        searchTarget(searchtables[0]);
        if (searchtables.length>1){
          for (var i=1; i < searchtables.length; i++) {
            hideTarget(searchtables[i].name);
          }
          }
      }
      else {
        alert(GlobalFuncService.getPopMessage('TIMEOUT_SESSION'));
        $location.path("login");
        return;      
      }        
    });
  }

  /*
  $scope.searchSignatures = function(){
    $scope.state.dispsearch=true;
    var searchtables= searchTypeItems[$scope.search.searchtype];
    searchTarget(searchtables[0]);
    if (searchtables.length>1){
      for (var i=1; i < searchtables.length; i++) {
        hideTarget(searchtables[i].name);
      }
      }
  }  
  */
  
  $scope.searchClear = function(){
    initSearch();
  }
  
  $scope.selectTime = function(){
    //console.log('selectTime begin');
    searchTargetTime(searchTypeItems['time'][1]);
  }
  
  $scope.viewSignature = function(autozero){
    // get current selected row
    var level = $scope.enableView;
    var nRow = 0;

    if (autozero == false) {
       nRow = $scope.selected[level].row.attr('ANG-tindex');    
    }      
    var stype = $scope.search.searchtype;

    }
    GlobalFuncService.setCurrDataSearch($scope.search);    
    GlobalFuncService.setCurrData(stype, refnumb);
    $location.path("view");
  }  

  //check if user logged in, if not, redirect to login page
  var isLoggedIn = Auth.isLoggedIn();
  if (isLoggedIn == false) {
    $location.path("login");    
  }
});