///define(['app'], function (app) {
(function () {
  var app = angular.module('myApp');
  var cId = 'SOB1';
  var cVer = 0;
  ///app.register.controller(cId, [
  app.controller(cId, [
    '$scope', '$rootScope', '$http', '$window', '$location', 'VS4Library', 'myFactory', 'SOFactory',
    function ($scope, $rootScope, $http, $window, $location, VS4Library, myFactory, SOFactory) {
      var self = this;
      $rootScope.controllerMsg = cId + ' : ' + myFactory.AppVersion() + '.' + cVer;

      //00 Start Inject Initialize Library

      var target = document.getElementById('progress');
      var spinner = new Spinner($rootScope.progressOpts).spin(target);
      var newRowID = 1000;
      var onRecalculating = false;

      var click = ej.Autocomplete.prototype._OnDropdownClick;
      ej.Autocomplete.prototype._OnDropdownClick = function (e) {
        click.call(this, e);
        this._trigger("select", {
          value: this.element.val()
        })
      }

      $scope.showDataList = function (returnObjNameList, fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName, dataChangeEvent) {
        // if ($scope.runMode == "VIEW" && !$rootScope.loadingDialog) {
        if (!$rootScope.loadingDialog) {
          $rootScope.loadingDialog = true;
          myFactory.selectDataList(fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName).then(function (data) {
            if (data.value.action) {
              if (data.value.value.length > 0) {
                // Multiple fields return support
                var fL = $rootScope.selectDataList.fieldList.split("##");
                var fRL = fL[0].split(",");
                var oL = returnObjNameList.split(",");
                var l1 = fRL.length;
                var l2 = oL.length;
                if (l1 > l2) {
                  l1 = l2
                };
                var v = data.value.value[0].split("#$#");
                for (var i = 0; i < l1; i++) {
                  var n = oL[i].split(".");
                  switch (n.length) {
                    case 2:
                      $scope.formData[n[0]][n[1]] = v[i];
                      break;
                    case 3:
                      $scope.formData[n[0]][n[1]][n[2]] = v[i];
                      break;
                    case 4:
                      $scope.formData[n[0]][n[1]][n[2]][n[3]] = v[i];
                      break;
                    default:
                      $scope.formData[n[0]] = v[i];
                  }
                }

                if (dataChangeEvent !== undefined) {
                  $scope.formData.which = 13;
                  dataChangeEvent($scope.formData);
                }
              }
            }
            $rootScope.loadingDialog = false;
          });
        }
      };

      //00 End Inject Initialize Library


      $scope.onEdit = false;
      $rootScope.loadingDialog = false;
      $scope.controllerName = "SOB1";

      //0 Private Data      
      function InitialData() {
        $scope.formData = {
          reportFullName: '',
          reportQuery: '',
          baseQuery: '',
          baseOrderBy: '',
          where: '',
          parameters: '',
          reportConditions: '',
          toolbarSettings: '',
          autoPrint: false,

          list: {
            status: 4,
            fromDate: VS4Library.GetDateText(),
            toDate: "",
            saleCode: ""
          },

          PK_DOC_NO: '',
          DOC_NO: '',
          DOC_DATE: VS4Library.GetDate(),
          DISCOUNT_LIST: '0.00',
          TOTAL: '0.00',
          VAT_RATE: '0.00',
          VAT_TOTAL: '0.00',
          GRAND_TOTAL: '0.00',
          TARDName: '',
          TARNDiscount: '',

          TPdtCode: '',
          TPdtBarCode: '',
          TPdtName: '',
          TPOSUnitCalc: '',
          TPOSPrice: '',
          TQuBTUntCode: '',
          TPdtTUntCode: '',          

          SEARCH: '',

          TQuoNo: '',
          PK_TQuoNo: '',

          //modal
          VS4TQuotation: {
            TQuoNo: 'XXXXXXXXXX',
            TQuoRevision: 0,
            TQuoDate: VS4Library.GetDate(),
            TQuoType: 0,
            TQuoTPrjCode: '',
            TQuoTBraCode: '',
            TQuoTQBkCode: '',
            TQuoTARNCode: '',
            TQuoTRCACode: '',
            TQuoTDStCode: '',
            TQuoCustomerName: '',
            TQuoTARDCode: '',
            TARDName: '',
            TQuoTEmpCode: $window.sessionStorage.EmpCode,
            TEmpName: $window.sessionStorage.EmpName,
            TQuoRefNo: '',
            TQuoRefNo2: '',
            TQuoPriceChannel: '0',
            TQuoDeliveryDate: VS4Library.GetDate(),
            TQuoDueDate: VS4Library.GetDate(),
            TQuoDescription: '',
            TQuoSubTotal: 0,
            TQuoDiscountList: 0,
            TQuoDiscountText: '',
            TQuoDiscountTotal: 0,
            TQuoNetTotal: 0,
            TQuoDepositText: '',
            TQuoDeposit: 0,
            TQuoTotal: 0,
            TQuoTotalFOB: 0,
            TQuoVATType: 0,
            TQuoVATRate: 7.0,
            TQuoTaxBase: 0,
            TQuoVATTotal: 0,
            TQuoGrandTotal: 0,
            TQuoCondition1: 0,
            TQuoConditionDay1: 0,
            TQuoConditionDay: 0,
            TQuoCancelStatus: 0,
            TQuoCheckStatus: 0,
            TQuoApproveStatus: 0
          },

          VS4TQuotationMB: [{
            TQuBLn: 0,
            TQuBTPOSCode: '',
            TQuBPOSName: '',
            TQuBCustom1: '',
            TQuBUnitCalc: 0,
            TQuBQuantity: 0,
            TQuBTUntCode: '',
            TQuBUnitFactor: 0,
            TQuBQuantityBase: 0,
            TPdtTUntCode: '',
            TQuBQuantityCalc: 0,
            TQuBIsPremium: 0,
            TQuBFreeCode: '',
            TQuBPrice: 0,
            TQuBPerQuantity: 0,
            TQuBDiscountText: '',
            TQuBNetAmount: 0,
            TQuBUseDate: VS4Library.GetDate()
          }],

          // var q = "SELECT TQuBTQuoNo,TQuBLn,TQuBTPOSCode,TQuBPOSName,TQuBCustom1,TQuBUnitCalc,TQuBQuantity,TQuBTUntCode,TQuBUnitFactor,TQuBQuantityBase,TPdtTUntCode,TQuBQuantityCalc";
          // // q += ",TQuBQuantity2,TPdtTUntCode2,TQuBQuantity3,TPdtTUntCode3";
          // q += ",TQuBIsPremium,TQuBFreeCode,TQuBPrice,TQuBPerQuantity,TQuBDiscountText,TQuBNetAmount,TQuBUseDate";
          // // q += ",TQuBAmount,TQuBDiscountTotal,TQuBTaxBase,TQuBAmountVAT"
          // // q += ",TQuBTARWCode,TQuBWelfareRate,TQuBTRCACode,TQuBStockFlag,TQuBFlag1";
          // // q += ",TQuBType,TQuBStatus,TQuBTaxType,TQuBFlag3,TQuBTotalDelivery";
        }

        //Load Option Configure
        // myFactory.getSystemOption("",
        // '',
        // '');    

        // myFactory.getBranchOption("",
        // '',
        // '');                 

        myFactory.getUserOption($window.sessionStorage.userID,
          'DefaultUserProject,DefaultSOVATType,DefaultSOVATRate,DEFAULTQuBOOK,DEFAULTSOCAMPAIGN,SALEAutoListProduct,SOSkipSaleCode,SOEnableFillSaleFromCustomer',
          'VS4TQuotation.TQuoTPrjCode,VS4TQuotation.TQuoVATType,VS4TQuotation.TQuoVATRate,VS4TQuotation.TQuoTQBkCode,VS4TQuotation.TQuoTRCACode,VS4TQuotation.TQuoTDStCode,SALEAutoListProduct,SOSkipSaleCode,SOEnableFillSaleFromCustomer',
          $scope.formData);

        $scope.errorMessage = "";
        $scope.formReady = false;
        $scope.rendering = false;
        $scope.showStandardUI = false;
        $scope.formData.baseQuery = "";
      }

      InitialData();
      //6 Try to make move control by return key
      // setTabindex();


      //1 Private Function
      $scope.priceChannel = myFactory.getPriceChannel();
      $scope.vatType = myFactory.getVATType();
      $scope.statusDocument = myFactory.getStatusDocument();

      $scope.saleCode = function () {
        var fl = "TEmpCode,TEmpFullName,TEmpFullName2";
        var fieldList = "TEmpCode##" + fl + "##รหัสพนักงาน,ชื่อพนักงาน,ชื่อพนักงาน2##150,400,400";
        var q = "SELECT " + fl + " FROM VS4TEmployee WHERE TEmpFlag1=1";
        $scope.showDataList("list.saleCode", fieldList, q, false, "", "", "POST");
      }

      $scope.TPrjCode = function () {
        if ($scope.runMode !== "VIEW") {
          var fl = "TPrjCode,TPrjName,TPrjName2";
          var fieldList = "TPrjCode##" + fl + "##รหัสโครงการ,ชื่อโครงการ,ชื่อโครงการ2##150,400,400";
          var q = "SELECT " + fl + " FROM VS4TProject WHERE TPrjFlag1=1";
          $scope.showDataList("VS4TQuotation.TQuoTPrjCode", fieldList, q, false, "", "", "POST", "", getCode);
        }
      }

      $scope.TQBkCode = function () {
        if ($scope.runMode !== "VIEW") {
          var fl = "TQBkCode,TQBkName,TQBkName2";
          var fieldList = "TQBkCode##" + fl + "##รหัสสมุด,ชื่อสมุด,ชื่อสมุด2##150,400,400";
          var q = "SELECT " + fl + " FROM VS4TQuotationBook WHERE TQBkFlag1=1";
          $scope.showDataList("VS4TQuotation.TQuoTQBkCode", fieldList, q, false, "", "", "POST", "", getCode);
        }
      }

      $scope.TARNCode = function () {
        if ($scope.runMode !== "VIEW") {
          var fl = "TARNCode,TARNName,TARNName2";
          var fieldList = "TARNCode##" + fl + "##รหัสลูกค้า,ชื่อลูกค้า,ชื่อลูกค้า2##150,400,400";
          var q = "SELECT " + fl + " FROM VS4TAR WHERE TARNFlag1=1";
          $scope.showDataList("VS4TQuotation.TQuoTARNCode", fieldList, q, false, "", "", "POST", "", $scope.e_TARNCode);
        }
      }
      $scope.e_TARNCode = function ($event) {
        if ($event.which === 13) {
          var q = "SELECT TARNName,TARNDiscount,TARNPriceChannel FROM VS4TAR WHERE TARNCode='" + $scope.formData.VS4TQuotation.TQuoTARNCode + "'";
          myFactory.selectDataObj("", q, false, "", "", "POST")
            .done(function (e) {
              if (e.result.length > 0) {
                $scope.formData.VS4TQuotation.TQuoCustomerName = e.result[0].TARNName;
                $scope.formData.TARNDiscount = e.result[0].TARNDiscount;
                $scope.formData.VS4TQuotation.TQuoPriceChannel = e.result[0].TARNPriceChannel;
                if (!$scope.$$phase) {
                  $scope.$apply();
                }
                getCode();


                //6 Move to next ejControl
                // var outerWrapper = $("#" + $event.target.id).parents(".e-widget")[0];
                // $(outerWrapper.nextElementSibling).children().children("input").focus();
                // $(outerWrapper.nextElementSibling).children().children("input").select();
                // $event.preventDefault();

                // document.getElementById("#" + $event.target.id).nextElementSibling.focus();
                // document.getElementById("#" + $event.target.id).nextElementSibling.select();


                //6 Try to make move control by return key

                // $event.keyCode = 9;
                // return $event.keyCode;

                //$("#" + $event.target.id).sendKeys(Keys.CONTROL + "\t");
                // $("#" + $event.target.id).trigger ( { type: 'keydown', keyCode: 9, which: 9, charCode: 9 } );
                // $("#TARNCode").trigger ( { type: 'keypress', keyCode: 9, which: 9, charCode: 9 } );


                //var element = document.getElementById("TARNCode"); 

                // var element = $("#TARNCode");
                // triggerKeyDown(element, 9);

                // var e = $.Event('keydown');
                // e.which = 9;              
                // if (options.shiftKey) {
                //   e.shiftKey = true;
                // }
                // $("#TARNCode").trigger(e);

                //var ti = $(this).attr('tabindex') + 1;
                // var ti = $($event.target).attr('tabindex') + 1;
                // $('input[tabindex='+ti+']').focus(); 

                // $event.target.id.next().focus();                           
                // $("#" + $event.target.id).next('.e-input').focus();

                // var nextItem = $("#" + $event.target.id).next('.e-input');
                // if (nextItem.size() === 0) {
                //   nextItem = $('.e-input').eq(0);
                // }              
                // nextItem.focus();

                // $("#DOC_DATE").val($("#DOC_DATE").val());
                // $("#DOC_DATE").focus(function() { $("#DOC_DATE").select(); } );
                // $("#DOC_DATE").focus();


                // $('[tabIndex=' + (+this.tabIndex + 1) + ']')[0].focus();

                // var $canfocus = $(':focusable');
                // var index = $canfocus.index(document.activeElement) + 1;
                // if (index >= $canfocus.length) index = 0;
                // $canfocus.eq(index).focus();

                // $event.keycode = 9;
                // return $event.keycode;

                // var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
                // if (nextInput) {
                //   nextInput.focus();
                // }
              }
            });
          var q = "SELECT TARDCode,TARDName FROM VS4TARBranch WHERE TARDType=2 AND TARDTARNCode='" + $scope.formData.VS4TQuotation.TQuoTARNCode + "'";
          myFactory.selectDataObj("TARDCode,TARDName", q, false, "", "", "POST")
            .done(function (e) {
              if (e.result.length > 0) {
                $scope.formData.VS4TQuotation.TQuoTARDCode = e.result[0].TARDCode;
                $scope.formData.VS4TQuotation.TARDName = e.result[0].TARDName;
                if (!$scope.$$phase) {
                  $scope.$apply();
                }
              }
            });
        }
      }

      $scope.TARDCode = function () {
        if ($scope.runMode !== "VIEW") {
          var fl = "TARDCode,TARDName,TARDName2";
          var fieldList = "TARDCode##" + fl + "##รหัสสาขา,ชื่อสาขา,ชื่อสาขา2##150,400,400";
          var q = "SELECT " + fl + " FROM VS4TARBranch WHERE TARDTARNCode='" + $scope.formData.VS4TQuotation.TQuoTARNCode + "' ORDER BY TARDCode"
          $scope.showDataList("VS4TQuotation.TQuoTARDCode", fieldList, q, false, "", "", "POST", "", $scope.e_TARDCode);
        }
      }
      $scope.e_TARDCode = function ($event) {
        if ($event.which === 13) {
          var q = "SELECT TARDName FROM VS4TARBranch WHERE TARDTARNCode='" + $scope.formData.VS4TQuotation.TQuoTARNCode + "' AND TARDCode='" + $scope.formData.VS4TQuotation.TQuoTARDCode + "'";
          myFactory.selectDataObj("TARDName", q, false, "", "", "POST")
            .done(function (e) {
              if (e.result.length > 0) {
                $scope.formData.VS4TQuotation.TARDName = e.result[0].TARDName;
                if (!$scope.$$phase) {
                  $scope.$apply();
                }
              }
            });
        }
      }

      $scope.TEmpCode = function () {
        if ($scope.runMode !== "VIEW") {
          var fl = "TEmpCode,TEmpFullName,TEmpFullName2";
          var fieldList = "TEmpCode##" + fl + "##รหัสพนักงาน,ชื่อพนักงาน,ชื่อพนักงาน2##150,400,400";
          var q = "SELECT " + fl + " FROM VS4TEmployee WHERE TEmpCode<>''";
          $scope.showDataList("VS4TQuotation.TQuoTEmpCode", fieldList, q, false, "", "", "POST");
        }
      }

      $scope.TPOSCode = function () {
        var fl = "TPdtCode,TPdtBarCode,TPdtName,TPOSUnitCalc,TPOSPrice,TPdtTUntCode";
        var fieldList = fl + "##" + fl + "##รหัสสินค้า,ฺBarcode,ชื่อสินค้า,ฐานราคา,ราคา,หน่วย##150,150,400,100,100,60";
        var q = "SELECT " + fl + " FROM VS4VProduct WHERE TPOSCode<>''";
        //Need to make GetPrice function like Client
        // if ($scope.formData.VS4TQuotation.TQuoTARNCode != "") {
        //   q += " AND (TPLPTARNCode='" + $scope.formData.VS4TQuotation.TQuoTARNCode + "' OR TPLPTARNCode='' OR TPLPTARNCode IS NULL)";
        // } else {
        //   q += " AND (TPLPTARNCode='' OR TPLPTARNCode IS NULL)";
        // }
        if ($scope.formData.SEARCH != "") {
          var s = $scope.formData.SEARCH.replace("*", "%");
          q += " AND (TPdtCode Like '" + s + "%' ";
          q += " OR TPdtBarCode Like '" + s + "%' ";
          q += " OR TPdtName Like '" + s + "%' ";
          q += ")";
        }
        q += " ORDER BY TPdtCode";
        $scope.showDataList(fl, fieldList, q, false, "", "", "POST", "", $scope.e_TPOSCode);
      }
      $scope.e_TPOSCode = function ($event) {
        if ($event.which === 13) {
          var q = "SELECT TPdtCode,TPdtTUntCode FROM VS4TProduct WHERE TPdtCode='" + $scope.formData.TPdtCode + "'";
          myFactory.selectDataObj("", q, false, "", "", "POST")
            .done(function (e) {
              if (e.result.length > 0) {
                $scope.formData.TPdtCode = e.result[0].TPdtCode;
                $scope.formData.TPdtTUntCode = e.result[0].TPdtTUntCode;
                var gridObj = $("#Grid1").data("ejGrid");
                var i = gridObj.model.selectedRowIndex;
                gridObj.setCellValue(i, "TQuBTUntCode", $scope.formData.TPdtTUntCode);
                gridObj.setCellValue(i, "TPdtTUntCode", $scope.formData.TPdtTUntCode);
                gridObj.setCellValue(i, "TQuBUnitCalc", $scope.formData.TPOSUnitCalc);
                gridObj.setCellValue(i, "TQuBUnitFactor", 1);
                gridObj.setCellValue(i, "TQuBIsPremium", 0);
                gridObj.setCellValue(i, "TQuBPrice", $scope.formData.TPOSPrice);
                gridObj.setCellValue(i, "TQuBTPOSCode", $scope.formData.TPdtCode);
                gridObj.setCellValue(i, "TQuBPOSName", $scope.formData.TPdtName);                
                gridObj.batchSave();
                recalculate();
              }
            });
        }
      }

      $scope.search = function ($event) {
        if ($event.which === 13) {
          $scope.TPOSCode();
        }
      }

      $scope.TUntCode = function (args) {
        var fl = "TUntCode,TUntName,TUntFactor";
        var fieldList = "TUntCode##" + fl + "##หน่วยนับ,หมายเหตุ,Ratio##100,150,100";
        var q = "SELECT " + fl + " FROM VS4TUnit WHERE TUntFlag1=1";
        $scope.showDataList("TQuBTUntCode", fieldList, q, false, "", "", "POST", "", $scope.e_TUntCode);
      }
      $scope.e_TUntCode = function ($event) {
        if ($event.which === 13) {
          var gridObj = $("#Grid1").data("ejGrid");
          var i = gridObj.model.selectedRowIndex;
          gridObj.setCellValue(i, "TQuBTUntCode", $scope.formData.TQuBTUntCode);
          gridObj.batchSave();
          recalculate();

          var q = "SELECT TPdURatio FROM VS4TProductUnit WHERE TPdUTPdtCode='" + $scope.formData.TPdtCode + "' AND TPdUTUntCode='" + $scope.formData.TQuBTUntCode + "'";
          myFactory.selectDataObj("", q, false, "", "", "POST")
            .done(function (e) {
              if (e.result.length > 0) {
                var gridObj = $("#Grid1").data("ejGrid");
                var i = gridObj.model.selectedRowIndex;
                gridObj.setCellValue(i, "TQuBTUntCode", $scope.formData.TQuBTUntCode);
                gridObj.setCellValue(i, "TQuBUnitFactor", e.result[0].TPdURatio);
                gridObj.batchSave();
                recalculate();
              }
            });
        }
      }

      $scope.TRCACode = function () {
        var fl = "TRCACode,TRCAName,TRCAName2";
        var fieldList = "TRCACode##" + fl + "##รหัส Campaign,ชื่อ Campaign,ชื่อ Campaign2##150,400,400";
        var q = "SELECT " + fl + " FROM VS4TARCampaign WHERE TRCAFlag1=1";
        $scope.showDataList("VS4TQuotationMB.TQuBTRCACode", fieldList, q, false, "", "", "POST");
      }

      $scope.TARWCode = function () {
        var fl = "TARWCode,TARWName,TARWName2";
        var fieldList = "TARWCode##" + fl + "##รหัสสวัสดิการ,ชื่อสวัสดิการ,ชื่อสวัสดิการ2##150,400,400";
        var q = "SELECT " + fl + " FROM VS4TARWelfare WHERE TARWFlag1=1";
        $scope.showDataList("VS4TQuotationMB.TQuBTARWCode", fieldList, q, false, "", "", "POST");
      }



      //2 Set buttons
      $scope.runMode = "LIST";
      refreshControl();

      $scope.processStatus = function () {
        var target = document.getElementById('progress');
        var spinner = new Spinner($rootScope.progressOpts).spin(target);
        var data = {
          programId: cId,
          formData: $scope.formData
        };
        myFactory.process($scope.controllerName, "ProcessStatus", data)
          .then(function (response) {
            refreshControl()
            spinner.stop();
          }, function (error) {
            myFactory.errorBox(error);
            spinner.stop();
          });
      }
      $scope.cancelDoc = function () {
        $scope.formData.processAction = "cancelDoc";
        $scope.processStatus();
      }
      $scope.revise = function () {
        $scope.formData.processAction = "revise";
        $scope.processStatus();
      }
      $scope.check = function () {
        $scope.formData.processAction = "check";
        $scope.processStatus();
      }
      $scope.approve = function () {
        $scope.formData.processAction = "approve";
        $scope.processStatus();
      }
      // $scope.approve2 = function () {
      //   $scope.formData.processAction = "approve2";
      //   $scope.processStatus();
      // }
      // $scope.approve3 = function () {
      //   $scope.formData.processAction = "approve3";
      //   $scope.processStatus();
      // }

      $scope.close = function () {
        if ($scope.runMode === "LIST") {
          $window.history.back();
        } else {
          $scope.runMode = "LIST";
          InitialData();
          refreshControl();
        }
      };

      $scope.edit = function () {
        $scope.runMode = "EDIT";
        refreshControl();
      };

      $scope.add = function () {
        $scope.formData.TQuoNo = "";
        $scope.formData.PK_TQuoNo = "";
        $scope.runMode = "ADD";
        InitialData();
        getCode();
        refreshControl();
      };

      $scope.open = function () {
        if ($scope.formData.PK_TQuoNo !== "") {
          $scope.runMode = "VIEW";
          refreshControl();
        }
      };

      $scope.cancel = function () {
        var r = confirm("ต้องการยกเลิกการแก้ไข ใช่หรือไม่ ?");
        if (r === true) {
          if ($scope.runMode === "EDIT" && $scope.formData.PK_TQuoNo !== "") {
            $scope.runMode = "VIEW";
            refreshControl();
          } else { //ADD
            $scope.runMode = "LIST";
            InitialData();
            refreshControl();
          }
        }
      };


      function validateForm() {
        //$("#Grid1").ejGrid("editFormValidate");
        if ($scope.runMode === "ADD") $scope.formData.VS4TQuotation.TQuoTBraCode = $rootScope.ActiveBranch;
        if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoNo, "เลขที่เอกสาร")) { return false; }
        else if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoDate, "วันที่เอกสาร ให้ถูกต้อง")) { return false; }
        else if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoTPrjCode, "รหัสโครงการ")) { return false; }
        else if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoTQBkCode, "สมุดเสนอราคา")) { return false; }
        else if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoTARNCode, "รหัสลูกค้า")) { return false; }
        else if (!myFactory.isValidInput($scope.formData.VS4TQuotation.TQuoDeliveryDate, "วันที่กำหนดส่ง ให้ถูกต้อง")) { return false; }
        $scope.formData.VS4TQuotation.TQuoDueDate = VS4Library.cDate($scope.formData.VS4TQuotation.TQuoDeliveryDate) + VS4Library.cInt($scope.formData.VS4TQuotation.TQuoConditionDay);
        //$scope.formData.VS4TQuotation.TQuoDueDate = $scope.formData.VS4TQuotation.TQuoDeliveryDate + VS4Library.cInt($scope.formData.VS4TQuotation.TQuoConditionDay);
        return true;
      }

      $scope.submit = function () {
        if (validateForm()) {
          var target = document.getElementById('progress');
          var spinner = new Spinner($rootScope.progressOpts).spin(target);

          var data = {
            programId: cId,
            empName: $window.sessionStorage.EmpName,
            formData: $scope.formData
          };
          myFactory.batchUpdate($scope.controllerName, data)
            .then(function (response) {
              $scope.formData.PK_TQuoNo = response.data;
              $scope.runMode = "VIEW";
              refreshControl();
              spinner.stop();
            }, function (error) {
              myFactory.errorBox(error);
              spinner.stop();
            });
        }
      };

      $scope.process = function () {
        refreshControl();
      }

      // $scope.reset = function () {
      //   InitialData();
      //   refreshControl();
      // }


      //FILL DATA
      function refreshControl() {
        if ($scope.runMode !== "VIEW") $scope.onEdit = true; else $scope.onEdit = false;
        if ($scope.runMode === "LIST") {
          setButtons("LIST", $scope.runMode);
          refreshGDoc();
          refreshG();
        } else {
          setButtons("DOCUMENT", $scope.runMode);
          refreshDoc();
          refreshG();
        }

        $scope.formReady = true;

        $scope.showQuery = false;
        $scope.toggleQuery = function () {
          $scope.showQuery = !$scope.showQuery;
        };

      }

      function refreshGDoc() {
        var colDoc = [
          {
            field: "TQuoNo",
            headerText: "เลขที่ QT",
            isPrimaryKey: true,
            width: 150
          },
          {
            field: "TQuoDate",
            headerText: "วันที่",
            format: "{0:dd/MM/yyyy}",
            textAlign: ej.TextAlign.Center,
            width: 100
          },
          {
            field: "TQuoTQBkCode",
            headerText: "สมุด",
            width: 100
          },
          {
            field: "TQuoTARNCode",
            headerText: "รหัสลูกค้า",
            width: 100
          },
          {
            field: "TQuoCustomerName",
            headerText: "ชื่อลูกค้า",
            width: 100
          },
          {
            field: "TQuoGrandTotal",
            headerText: "จำนวนเงิน",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 120
          },
          {
            field: "TQuoCancelStatus",
            headerText: "C",
            editType: ej.Grid.EditingType.Dropdown,
            foreignKeyField: "value",
            foreignKeyValue: "text",
            dataSource: myFactory.getStatusNoYes(),
            textAlign: ej.TextAlign.Center,
            width: 50
          },
          {
            field: "TQuoConfirmStatus",
            headerText: "F",
            editType: ej.Grid.EditingType.Dropdown,
            foreignKeyField: "value",
            foreignKeyValue: "text",
            dataSource: myFactory.getStatusNoYes(),
            textAlign: ej.TextAlign.Center,
            width: 50
          },
          {
            field: "TQuoApproveStatus",
            headerText: "A",
            editType: ej.Grid.EditingType.Dropdown,
            foreignKeyField: "value",
            foreignKeyValue: "text",
            dataSource: myFactory.getStatusApprove(),
            textAlign: ej.TextAlign.Center,
            width: 50
          },
          {
            field: "TQuoDescription",
            headerText: "หมายเหตุ"
          }
        ];

        var q = "SELECT TQuoNo,TQuoDate,TQuoTQBkCode,TQuoTARNCode,TQuoCustomerName,TQuoGrandTotal,TQuoCancelStatus,TQuoConfirmStatus,TQuoApproveStatus,TQuoDescription";
        q += " FROM VS4VQuotationHead ";
        q += " WHERE TQuoNO <> ''";
        q += myFactory.getWHEREfromStatus($scope.formData.list.status, "TQuo", "");
        q += VS4Library.formatFilter($scope.formData, "D", false, "TQuoDate", ">=", $scope.formData.list.fromDate, "TQuoDate");
        q += VS4Library.formatFilter($scope.formData, "D", false, "TQuoDate", "<=", $scope.formData.list.toDate, "TQuoDate_T");
        q += VS4Library.formatFilter($scope.formData, "S", false, "TQuoTEmpCode", "=", $scope.formData.list.saleCode, "SALE_CODE");
        q += " ORDER BY TQuoNO";

        $scope.formData.reportQuery = q;

        myFactory.selectDataObj("", q, false, "", "", "POST")
          .done(function (e) {
            $scope.gridDataList = e.result;
            showGrid("#GridDocumentList", $scope.gridDataList, "", "", colDoc, $scope.runMode, 10);
          });
        showGrid("#GridDocumentList", [], "", "", colDoc, $scope.runMode, 10);
        $("#GridDocumentList").ejGrid({
          cellSelected: function (args) {
            $scope.select();
          },
          rowSelected: function (args) {
            $scope.select();
          }
        });
      }
      $scope.selectValue = [];
      $scope.select = function () {
        $scope.selectList = $("#GridDocumentList").ejGrid("model.selectedRecords");
        $scope.selectValue = [];
        var len = $scope.selectList.length;
        for (var i = 0; i < len; i++) {
          $scope.formData.PK_TQuoNo = $scope.selectList[i].TQuoNo;
          $scope.formData.TQuoNo = $scope.selectList[i].TQuoNo;
        }
      };

      $scope.recalculate = function ($event) {
        if ($event.which === 13) {
          recalculate();
        }
      }

      //recalculate
      function recalculate(args) {
        onRecalculating = true;
        if ($scope.runMode !== "LIST") {
          $scope.formData.VS4TQuotation.TQuoSubTotal = 0;
          $scope.formData.VS4TQuotation.TQuoDiscountList = 0;
          var u2x = 0; //myFactory.getSystemValue("USEUint2ATCUTMODE");

          var obj = $("#Grid1").ejGrid("instance");
          var gLength = obj.model.currentViewData.length;
          for (var i = 0; i < gLength; i++) {
            var data = obj.model.currentViewData[i];
            if (data !== "undefined" && data !== undefined) {
              if (data.TQuBLn == 0 || data.TQuBLn == null || data.TQuBLn == undefined) { data.TQuBLn = newRowID++; }
              if (data.TQuBUnitFactor === 0) { data.TQuBUnitFactor = 1; }
              if (data.TQuBPerQuantity === 0) { data.TQuBPerQuantity = 1; }
              data.TQuBQuantityBase = data.TQuBQuantity * data.TQuBUnitFactor;
              data.TQuBQuantityCalc = myFactory.calcQuantityCalc(data.TQuBUnitCalc, data.TQuBQuantity, data.TQuBQuantity2, data.TQuBQuantity3, data.TQuBQuantityBase, u2x);
              var NET_AMOUNT = 0;
              data.TQuBDiscountText = myFactory.validDiscountTextList(data.TQuBDiscountText, 2);
              data.TQuBDiscountTotal = 0;
              switch (Number(data.TQuBIsPremium)) {
                case 0:
                  var NET_AMOUNT = data.TQuBPrice / data.TQuBPerQuantity * data.TQuBQuantityCalc;
                  data.TQuBDiscountTotal = myFactory.getValueDiscountTextList((data.TQuBPrice / data.TQuBPerQuantity), data.TQuBDiscountText, data.TQuBQuantityCalc);
                  break;
              }
              data.TQuBNetAmount = NET_AMOUNT - data.TQuBDiscountTotal;
              obj.setCellValue(i, "TQuBNetAmount", data.TQuBNetAmount);
              obj.batchSave();

              //Sum to Head
              $scope.formData.VS4TQuotation.TQuoSubTotal += data.TQuBNetAmount;
              $scope.formData.VS4TQuotation.TQuoDiscountList += data.TQuBDiscountTotal;
            }
          }
          $scope.formData.VS4TQuotationMB = obj.model.currentViewData;

          //Calculate Head
          $scope.formData.VS4TQuotation.TQuoDiscountText = myFactory.validDiscountTextList($scope.formData.VS4TQuotation.TQuoDiscountText, 2);
          $scope.formData.VS4TQuotation.TQuoDiscountTotal = myFactory.getValueDiscountTextList($scope.formData.VS4TQuotation.TQuoSubTotal, $scope.formData.VS4TQuotation.TQuoDiscountText, 1);
          $scope.formData.VS4TQuotation.TQuoNetTotal = $scope.formData.VS4TQuotation.TQuoSubTotal - $scope.formData.VS4TQuotation.TQuoDiscountTotal;

          $scope.formData.VS4TQuotation.TQuoDepositText = myFactory.validDiscountTextList($scope.formData.VS4TQuotation.TQuoDepositText, 2);
          $scope.formData.VS4TQuotation.TQuoDeposit = myFactory.getValueDiscountTextList($scope.formData.VS4TQuotation.TQuoNetTotal, $scope.formData.VS4TQuotation.TQuoDepositText, 1);

          var EXIM = 0;
          if (EXIM === 1) {
            $scope.formData.VS4TQuotation.TQuoTotal = $scope.formData.VS4TQuotation.TQuoNetTotal - $scope.formData.VS4TQuotation.TQuoDeposit;
          } else {
            $scope.formData.VS4TQuotation.TQuoTotal = $scope.formData.VS4TQuotation.TQuoNetTotal;
          }

          if (VS4Library.cDbl($scope.formData.VS4TQuotation.TQuoExchangeRate) === 0) { $scope.formData.VS4TQuotation.TQuoExchangeRate = 1; }
          $scope.formData.VS4TQuotation.TQuoTotalInRate = $scope.formData.VS4TQuotation.TQuoTotal * $scope.formData.VS4TQuotation.TQuoExchangeRate;
          var t = $scope.formData.VS4TQuotation.TQuoTotalInRate;

          $scope.formData.VS4TQuotation.TQuoVATRate = VS4Library.cDbl($scope.formData.VS4TQuotation.TQuoVATRate);
          var v = $scope.formData.VS4TQuotation.TQuoVATRate;
          $scope.formData.VS4TQuotation.TQuoVATType = VS4Library.cInt($scope.formData.VS4TQuotation.TQuoVATType);
          switch (Number(VS4Library.cInt($scope.formData.VS4TQuotation.TQuoVATType))) {
            case 0:
              $scope.formData.VS4TQuotation.TQuoVATTotal = 0;
              $scope.formData.VS4TQuotation.TQuoTaxBase = t;
              $scope.formData.VS4TQuotation.TQuoGrandTotal = t;
              break;
            case 1:
              $scope.formData.VS4TQuotation.TQuoVATTotal = t * v / 100;
              $scope.formData.VS4TQuotation.TQuoTaxBase = t;
              $scope.formData.VS4TQuotation.TQuoGrandTotal = t + $scope.formData.VS4TQuotation.TQuoVATTotal;
              break;
            default:
              $scope.formData.VS4TQuotation.TQuoVATTotal = t * v / (100 + v);
              $scope.formData.VS4TQuotation.TQuoTaxBase = t - $scope.formData.VS4TQuotation.TQuoVATTotal;
              $scope.formData.VS4TQuotation.TQuoGrandTotal = t;
          }

          //Format Display
          $scope.formData.DISCOUNT_LIST = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoDiscountList, 2);
          $scope.formData.DISCOUNT_BILL = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoDiscountTotal, 2);
          $scope.formData.TOTAL = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoTaxBase, 2);
          $scope.formData.VAT_RATE = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoVATRate, 2);
          $scope.formData.VAT_TOTAL = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoVATTotal, 2);
          $scope.formData.GRAND_TOTAL = accounting.formatNumber($scope.formData.VS4TQuotation.TQuoGrandTotal, 2);
          if (!$scope.$$phase) {
            $scope.$apply();
          }
          onRecalculating = false;
        }
        onRecalculating = false;
      }

      function getCode() {
        $scope.manualDocNo = false;
        if ($scope.runMode == "ADD" && !$scope.manualDocNo) {
          var data = {
            programId: cId,
            runMode: $scope.runMode,
            manualDocNo: $scope.manualDocNo,
            formData: $scope.formData
          };
          myFactory.process($scope.controllerName, "GetCode", data)
            .then(function (response) {
              if (data !== "") {
                $scope.formData.VS4TQuotation.TQuoNo = response.data;
              }
            });
        }
      }


      function refreshDoc() {
        var q = "SELECT *";
        q += " FROM VS4VQuotationHead ";
        q += " WHERE TQuoNO = '" + $scope.formData.TQuoNo + "'";
        myFactory.selectDataObj("", q, false, "", "", "POST")
          .done(function (e) {
            if (e.result.length > 0) {
              $scope.formData.VS4TQuotation = e.result[0];
              if ($scope.runMode == "VIEW") {
                var sC = $scope.formData.VS4TQuotation.TQuoCancelStatus;
                var sF = $scope.formData.VS4TQuotation.TQuoConfirmStatus;
                var sA = $scope.formData.VS4TQuotation.TQuoApproveStatus;
                if (sC == 1) {
                  $("#btnEdit").hide();
                } else if (sF == 0) {
                  $("#btnCheck").show();
                  $("#btnCancelDoc").show();
                } else if (sA == 0) {
                  $("#btnApprove").show();
                  $("#btnRevise").show();
                  $("#btnEdit").hide();
                  $("#btnCancelDoc").show();
                } else {
                  $("#btnRevise").show();
                  $("#btnEdit").hide();
                  $("#btnCancelDoc").show();
                }
              }
              recalculate();
              if (!$scope.$$phase) {
                $scope.$apply();
              }
            }
          });
      }

      function refreshG() {
        var col = [
          {
            field: "TQuBLn",
            headerText: "Ln",
            type: "number",
            // allowEditing: true,
            isPrimaryKey: true,
            visible:false
          },
          {
            field: "TQuBTPOSCode",
            editTemplate: {
              create: function () {
                return "<input>";
              },
              read: function (args) {
                //args.ejAutocomplete('suggestionList').css('display', 'none');
                args.ejAutocomplete().css('display', 'none');
                return args.ejAutocomplete("getValue");
              },
              write: function (args) {
                args.element.ejAutocomplete({ width: "100%", dataSource: "", showPopupButton: true, showEmptyResultText: false, select: $scope.TPOSCode, enableDistinct: true, value: args.rowdata !== undefined ? args.rowdata["TQuBTPOSCode"] : "" });
              }
            },
            headerText: "รหัสสินค้า",
            type: "string",
            width: 80
          },
          {
            field: "TQuBPOSName",
            headerText: "ชื่อสินค้า",
            type: "string",
            width: 50
          },
          {
            field: "TQuBCustom1",
            headerText: "Commission",
            type: "string",
            width: 50
          },
          {
            field: "TQuBUnitCalc",
            headerText: "ฐานราคา",
            type: "number",
            editType: ej.Grid.EditingType.Dropdown,
            foreignKeyField: "value",
            foreignKeyValue: "text",
            dataSource: myFactory.getUnitCalc(),
            textAlign: ej.TextAlign.Center,
            width: 50
          },
          {
            field: "TQuBQuantity",
            headerText: "จำนวน",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 50
          },
          {
            field: "TQuBTUntCode",
            editTemplate: {
              create: function () {
                return "<input>";
              },
              read: function (args) {
                args.ejAutocomplete().css('display', 'none');
                return args.ejAutocomplete("getValue");
              },
              write: function (args) {
                args.element.ejAutocomplete({ width: "100%", dataSource: "", showPopupButton: true, showEmptyResultText: false, select: $scope.TUntCode, enableDistinct: true, value: args.rowdata !== undefined ? args.rowdata["TQuBTUntCode"] : "" });
              }
            },
            headerText: "หน่วย",
            type: "string",
            width: 30
          },
          {
            field: "TQuBUnitFactor",
            headerText: "Ratio",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 40
          },
          {
            field: "TQuBQuantityBase",
            headerText: "หน่วย",
            type: "number",
            allowEditing: false,
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 40
          },
          {
            field: "TPdtTUntCode",
            headerText: "หลัก",
            // allowEditing: false,
            type: "string",
            width: 30
          },
          {
            field: "TQuBQuantityCalc",
            headerText: "Qty",
            type: "number",
            allowEditing: false,
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            visible:false
          },
          {
            field: "TQuBQuantity2",
            headerText: "จำนวน",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            visible:false
          },
          {
            field: "TPdtTUntCode2",
            headerText: "หน่วย",
            allowEditing: false,
            type: "string",
            visible:false
          },
          {
            field: "TQuBQuantity3",
            headerText: "จำนวน",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            visible:false
          },
          {
            field: "TPdtTUntCode3",
            headerText: "หน่วย",
            allowEditing: false,
            type: "string",
            visible:false
          },
          {
            field: "TQuBIsPremium",
            headerText: "PayType",
            type: "number",
            editType: ej.Grid.EditingType.Dropdown,
            foreignKeyField: "value",
            foreignKeyValue: "text",
            dataSource: myFactory.getPayType(),
            textAlign: ej.TextAlign.Center,
            width: 40
          },
          {
            field: "TQuBFreeCode",
            headerText: "PCode",
            type: "string",
            visible:false
          },
          {
            field: "TQuBPrice",
            headerText: "Price",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 40
          },
          {
            field: "TQuBPerQuantity",
            headerText: "ต่อจำนวน",
            type: "number",
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            visible:false
          },
          {
            field: "TQuBDiscountText",
            headerText: "ส่วนลด",
            type: "string",
            width: 30
          },
          {
            field: "TQuBNetAmount",
            headerText: "Total",
            type: "number",
            allowEditing: false,
            textAlign: ej.TextAlign.Right,
            format: "{0:N}",
            width: 50
          },
          {
            field: "TQuBUseDate",
            headerText: "กำหนดส่ง",
            type: "date",
            format: "{0:dd/MM/yyyy}",
            textAlign: ej.TextAlign.Center,
            width: 50
          }
          // {
          //   field: "TQuBTARWCode",
          //   editTemplate: {
          //     create: function () {
          //       return "<input>";
          //     },
          //     read: function (args) {
          //       args.ejAutocomplete().css('display', 'none');
          //       return args.ejAutocomplete("getValue");
          //     },
          //     write: function (args) {
          //       args.element.ejAutocomplete({ width: "100%", dataSource: "", showPopupButton: true, showEmptyResultText: false, select: $scope.TARWCode, enableDistinct: true, value: args.rowdata !== undefined ? args.rowdata["TQuBTARWCode"] : "" });
          //     }
          //   },
          //   headerText: "สวัสดิการ",
          //   type: "string",
          //   width: 30
          // },
          // {
          //   field: "TQuBWelfareRate",
          //   headerText: "ส. Rate",
          //   type: "string",
          //   width: 30
          // },
          // {
          //   field: "TQuBTRCACode",
          //   editTemplate: {
          //     create: function () {
          //       return "<input>";
          //     },
          //     read: function (args) {
          //       args.ejAutocomplete().css('display', 'none');
          //       return args.ejAutocomplete("getValue");
          //     },
          //     write: function (args) {
          //       args.element.ejAutocomplete({ width: "100%", dataSource: "", showPopupButton: true, showEmptyResultText: false, select: $scope.TRCACode, enableDistinct: true, value: args.rowdata !== undefined ? args.rowdata["TQuBTRCACode"] : "" });
          //     }
          //   },
          //   headerText: "Campaign",
          //   type: "string",
          //   width: 30
          // },
          // {
          //   field: "TQuBStockFlag",
          //   headerText: "Stock",
          //   // type: "number",            
          //   editType: ej.Grid.EditingType.Boolean,
          //   width: 20
          // },
          // {
          //   field: "TQuBFlag1",
          //   headerText: "Show",
          //   // type: "number",
          //   editType: ej.Grid.EditingType.Boolean,
          //   width: 20
          // }
        ];

        if ($scope.formData.TQuoNo === undefined) { $scope.formData.TQuoNo = ''; }

        var q = "SELECT TQuBTQuoNo,TQuBLn,TQuBTPOSCode,TQuBPOSName,TQuBCustom1,TQuBUnitCalc,TQuBQuantity,TQuBTUntCode,TQuBUnitFactor,TQuBQuantity*TQuBUnitFactor AS TQuBQuantityBase,TPdtTUntCode";
        q += ",TQuBQuantity2,TPdtTUntCode2,TQuBQuantity3,TPdtTUntCode3";
        q += ",TQuBIsPremium,TQuBFreeCode,TQuBPrice,TQuBPerQuantity,TQuBAmount,TQuBDiscountText,TQuBDiscountTotal";
        q += ",TQuBNetAmount,TQuBTaxBase,TQuBAmountVAT,TQuBUseDate,TQuBTARWCode,TQuBWelfareRate,TQuBTRCACode,TQuBStockFlag,TQuBFlag1";
        q += ",TQuBType,TQuBTaxType";
        q += " FROM VS4VQuotation ";
        q += " WHERE TQuBTQuoNO = '" + $scope.formData.TQuoNo + "'";
        q += " ORDER BY TQuBTQuoNO,TQuBLn";

        $scope.formData.reportQuery = q;

        myFactory.selectDataObj("", q, false, "", "", "POST")
          .done(function (e) {
            if (e.result.length > 0) {
              $scope.formData.VS4TQuotationMB = e.result;
              showGrid("#Grid1", $scope.formData.VS4TQuotationMB, "", "", col, $scope.runMode, 0, 0, 150);
              recalculate();
            }
          });
        showGrid("#Grid1", $scope.formData.VS4TQuotationMB, "", "", col, $scope.runMode, 0, 0, 150);

        var flag = 0;
        $("#Grid1").ejGrid({
          cellSave: function (args) {
            if (!onRecalculating) {
              if (args.value !== undefined || args.value.value !== undefined) {
                //if (args.value !== undefined) {
                var rowIndex = this.getIndexByRow(args.cell.parent());
                //this.setCellValue(rowIndex, args.columnName, args.isForeignKey ? args.value.value : args.value);
                if (flag == 0) {//flag variable is used to avoid recursive call
                  if ($("#Grid1EditForm").length) {
                    args.cancel = true;
                    flag = 1;
                    this.batchSave();
                    flag = 0;
                    recalculate(args);
                  }
                }

              }
            }
          },
          batchDelete: function (args) {
            if (!onRecalculating) { recalculate(args); }
          }
        });
        $("#VAT_TYPE").ejDropDownList({
          change: function (args) {
            $scope.formData.VS4TQuotation.TQuoVATType = args.value;
            if (!onRecalculating) { recalculate(args); }
          }
        });


      }

    }
  ]);
  ///});
})();



//6 Try to make move control by return key 

// jQuery.extend(jQuery.expr[':'], {
//     focusable: function (el, index, selector) {
//         return $(el).is('a, button, :input, [tabindex]');
//     }
// });

// function setTabindex() {
  // var tabindexValue = 1;//cbChecked ? 0 : -1;
  // // var noTabindexElements = document.querySelectorAll('input[data-notabindex]');
  // var noTabindexElements = document.querySelectorAll('input[data-tabindex]');

  // for (var i = 0; i < noTabindexElements.length; i++) {
  //     noTabindexElements[i].tabIndex = tabindexValue;
  // }
// }


// utility functions
// var prepareInputEl = function (inputTpl) {
//   var el = $compile(angular.element(inputTpl))($scope);
//   $scope.$digest();
//   return el;
// };

// var findInput = function (element) {
//   return element.find('input');
// };

// var findDropDown = function (element) {
//   return element.find('ul.dropdown-menu');
// };

// var findMatches = function (element) {
//   return findDropDown(element).find('li');
// };

// var triggerKeyDown = function (element, keyCode, options) {
//   options = options || {};
//   //var inputEl = findInput(element);
//   var inputEl = element;
//   var e = $.Event('keydown');
//   e.which = keyCode;
//   if (options.shiftKey) {
//     e.shiftKey = true;
//   }
//   inputEl.trigger(e);
// };

// $(document).ready(function() {
//     $("input:text").focus(function() { $(this).select(); } );
// });


