angular.module('estimateCtrl', []).controller('estimateController', function($ionicActionSheet, $ionicHistory, $cordovaFile, $cordovaActionSheet, $cordovaCamera, //
  $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, //
  $location, $scope, $sce, $http, $window, $interval, $timeout, Login, Users, Products, Orderstatuses, $stateParams, Callaheads, Flexiblecustomers, Orders,
  Opportunities) {
  withoutPopup = $scope;
  $scope.currentIdLogin = currentIdLogin;
  // $scope.customer_id = getParameterByName('customer_id');
  // $scope.appointment_id = getParameterByName('appointment_id');
  // $scope.getestimate_id = getParameterByName('estimate_id');
  // var parameter = checkParameter('appointment_id', $location.absUrl());
  $scope.Service = '0';
  $scope.sendMailType = {};
  $scope.OptionService = '5';
  $scope.Declined = {};
  $scope.Declined.value = 0;
  $scope.Snail_Mail = {};
  $scope.Snail_Mail.value = "";
  $scope.Subtotal = 0;
  $scope.Discount = 0;
  $scope.MD_Estimate = 0;
  $scope.check_MD_Estimate = 0;
  $scope.check_Declined = 0;
  $scope.comment = {};
  $scope.comment.value = '';
  $scope.sendto = 'email';
  $scope.loadRespondsive = 0;
  $scope.check_create_task = 0;
  $scope.Installer_date = '';
  $scope.Installer = '';
  $scope.pricebookdata = [{
    name: '',
    Product_Class_name: '',
    id: '',
    warranty_name: '',
    quantity: '',
    price: '',
    warranty_id: '',
    Extended: '',
    Extended_Price: '',
    declined: '',
    Wholesale: '',
    Commercial: '',
    Contractor: '',
    Retail: '',
    Walk_In: '',
    Customer_Aquisition: ''
  }];
  $scope.notification = 'Your access to create the estimate is invalid, please try again.';
  $scope.roleName = role;
  $scope.isAdmin = isAdmin;
  $scope.isManager = isManager;
  $scope.isReporter = isReporter;
  $scope.isScheduler = isScheduler;
  $scope.isFieldinstaller = isFieldinstaller;
  $scope.isSalesman = isSalesman;
  $scope.isWarehouse = isWarehouse;
  $scope.departmentId = departmentId;
  $scope.onMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(andRoid)|(Linux)|(webOS)/i) != null;
  $scope.check_init_estimate = false;
  $scope.loadJobsite_id = 0;
  $scope.jobsitedata = {};
  $scope.MDValueAllItem = {};
  $scope.warrantyData = [];
  $scope.dataInch = {};
  $scope.cornerstylesdata={cornerstyles_id:'',cornerstyles_name:'',product_id:0,products:[],index:0,name:""};

  $scope.templateData = {
    dataInfoCustomer: { first_name: "No", last_name: "Name" },
    subtotal: 0,
    estimate_no: ""
  };
  //New Door
  $scope.DoorData = {
    "Construction": [
    [ "Heritage", "Lincoln", "Hillcrest", "Classica"],
    ["Designers_Choice", "Olympus"]
    ],
    "Height": {
        "ModelHeight": [
        [60, 63, 66, 69, 70, 76, 79, 80],
        [65, 69, 70, 74, 78, 80]
        ],
        "Panel_Height": [
        [18, 21],
        [28, 32]
        ]
    },
    "Color": {
        "Color1": {
            "Lincoln_1000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Lincoln_2000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Hillcrest_1000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Hillcrest_2000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Heritage_1000": ["True White", "Almond", "Sandtone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black", "Color Zone"],
            "Heritage_2000": ["True White", "Almond", "Sandtone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black", "Color Zone"],
            "Heritage_3000": ["True White", "Almond", "Sandtone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black", "Color Zone"],
            "Lincoln_3000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Hillcrest_3000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut",  "Color Zone"],
            "Classica_1000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black",  "True White Base", "Almond Base", "Wicker Tan Base", "Sandtone Base", "Terratone Base", "Dark Brown Base", "Color Zone"],
            "Classica_2000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black",  "True White Base", "Almond Base", "Wicker Tan Base", "Sandtone Base", "Terratone Base", "Dark Brown Base", "Color Zone"],
            "Classica_3000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Golden Oak", "Mahogany", "Walnut", "Black",  "True White Base", "Almond Base", "Wicker Tan Base", "Sandtone Base", "Terratone Base", "Dark Brown Base", "Color Zone"],
            "Designers_Choice_3200": ["True White", "Almond", "Wicker Tan", "Sandtone", "Dark Brown", "Mahogany", "Walnut", "Black", "Color Zone"],
            "Olympus_3200": ["True White", "Almond", "Wicker Tan", "Sandtone", "Dark Brown", "Mahogany", "Walnut", "Black", "Color Zone"]
        },
        "Color2": {
            "Classica_1000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Gray"],
            "Classica_2000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Gray"],
            "Classica_3000": ["True White", "Almond", "Wicker Tan", "Sandtone", "Terratone", "Dark Brown", "Gray"]
        }
    },
    "Stamp": {
        "Classica_1000_Almond": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Almond Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Black": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Color Zone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Dark Brown": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Dark Brown Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Golden Oak": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Mahogany": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Sandtone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Sandtone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Terratone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Terratone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_True White": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_True White Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Walnut": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Wicker Tan": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_1000_Wicker Tan Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Almond": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Almond Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Black": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Color Zone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Dark Brown": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Dark Brown Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Golden Oak": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Mahogany": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Sandtone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Sandtone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Terratone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Terratone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_True White": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_True White Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Walnut": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Wicker Tan": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_2000_Wicker Tan Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Almond": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Almond Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Black": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Color Zone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Dark Brown": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Dark Brown Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Golden Oak": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Mahogany": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Sandtone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Sandtone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Terratone": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Terratone Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_True White": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_True White Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Walnut": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Wicker Tan": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Classica_3000_Wicker Tan Base": ["Lucern", "Tuscany", "Santiago", "Valencia", "Northampton", "Bordeaux", "Cortona"],
        "Designers_Choice_3200_Almond": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Black": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Color Zone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Dark Brown": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Mahogany": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Sandtone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_True White": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Walnut": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Designers_Choice_3200_Wicker Tan": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Heritage_1000_Almond": ["Short Panel", "Long Panel"],
        "Heritage_1000_Black": ["Short Panel", "Long Panel"],
        "Heritage_1000_Color Zone": ["Short Panel", "Long Panel"],
        "Heritage_1000_Dark Brown": ["Short Panel", "Long Panel"],
        "Heritage_1000_Golden Oak": ["Short Panel", "Long Panel"],
        "Heritage_1000_Mahogany": ["Short Panel", "Long Panel"],
        "Heritage_1000_Sandtone": ["Short Panel", "Long Panel"],
        "Heritage_1000_True White": ["Short Panel", "Long Panel"],
        "Heritage_1000_Walnut": ["Short Panel", "Long Panel"],
        "Heritage_2000_Almond": ["Short Panel", "Long Panel"],
        "Heritage_2000_Black": ["Short Panel", "Long Panel"],
        "Heritage_2000_Color Zone": ["Short Panel", "Long Panel"],
        "Heritage_2000_Dark Brown": ["Short Panel", "Long Panel"],
        "Heritage_2000_Golden Oak": ["Short Panel", "Long Panel"],
        "Heritage_2000_Mahogany": ["Short Panel", "Long Panel"],
        "Heritage_2000_Sandtone": ["Short Panel", "Long Panel"],
        "Heritage_2000_True White": ["Short Panel", "Long Panel"],
        "Heritage_2000_Walnut": ["Short Panel", "Long Panel"],
        "Heritage_3000_Almond": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Black": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Color Zone": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Dark Brown": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Golden Oak": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Mahogany": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Sandtone": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_True White": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Heritage_3000_Walnut": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Hillcrest_1000_Almond": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Color Zone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Dark Brown": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Golden Oak": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Mahogany": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Sandtone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Terratone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_True White": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Walnut": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_1000_Wicker Tan": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Almond": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Color Zone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Dark Brown": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Golden Oak": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Mahogany": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Sandtone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Terratone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_True White": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Walnut": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_2000_Wicker Tan": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Almond": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Color Zone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Dark Brown": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Golden Oak": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Mahogany": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Sandtone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Terratone": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_True White": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Walnut": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Hillcrest_3000_Wicker Tan": ["Bead Board", "Long Bead Board", "Raised", "Recessed"],
        "Lincoln_1000_Almond": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Color Zone": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Dark Brown": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Golden Oak": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Mahogany": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Sandtone": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Terratone": ["Short Panel", "Long Panel"],
        "Lincoln_1000_True White": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Walnut": ["Short Panel", "Long Panel"],
        "Lincoln_1000_Wicker Tan": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Almond": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Color Zone": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Dark Brown": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Golden Oak": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Mahogany": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Sandtone": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Terratone": ["Short Panel", "Long Panel"],
        "Lincoln_2000_True White": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Walnut": ["Short Panel", "Long Panel"],
        "Lincoln_2000_Wicker Tan": ["Short Panel", "Long Panel"],
        "Lincoln_3000_Almond": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Color Zone": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Dark Brown": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Golden Oak": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Mahogany": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Sandtone": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Terratone": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_True White": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Walnut": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Lincoln_3000_Wicker Tan": ["Short Panel", "Long Panel", "Ribbed", "Flush"],
        "Olympus_3200_Almond": ["Short Panel", "Long Panel"],
        "Olympus_3200_Black": ["Short Panel", "Long Panel"],
        "Olympus_3200_Color Zone": ["Short Panel", "Long Panel"],
        "Olympus_3200_Dark Brown": ["Short Panel", "Long Panel"],
        "Olympus_3200_Mahogany": ["Short Panel", "Long Panel"],
        "Olympus_3200_Sandtone": ["Short Panel", "Long Panel"],
        "Olympus_3200_True White": ["Short Panel", "Long Panel", "Flush"],
        "Olympus_3200_Walnut": ["Short Panel", "Long Panel"],
        "Olympus_3200_Wicker Tan": ["Short Panel", "Long Panel"],
    },
    "Top_Section": {
        "Top_Section": {
            "Heritage_1000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Heritage_2000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Heritage_3000": ["Closed Square", "Glazed", "Obscure", "Insulated", "Frosted", "Dark Tint"],
            "Lincoln_1000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Lincoln_2000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Lincoln_3000": ["Closed Square", "Glazed", "Obscure", "Insulated", "Frosted", "Dark Tint"],
            "Hillcrest_1000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Hillcrest_2000": ["Closed Square", "Glazed", "Obscure", "Frosted", "Dark Tint"],
            "Hillcrest_3000": ["Closed Square", "Glazed", "Obscure", "Insulated", "Frosted", "Dark Tint"],
            "Classica_1000": ["Closed Square", "Closed Arch", "Tempered", "Obscure", "Frosted", "Dark Tint"],
            "Classica_2000": ["Closed Square", "Closed Arch", "Tempered", "Obscure", "Frosted", "Dark Tint"],
            "Classica_3000": ["Closed Square", "Closed Arch", "Tempered", "Obscure", "Insulated", "Frosted", "Dark Tint"],
            "Designers_Choice_3200": ["Closed Square", "Glazed", "Obscure", "Insulated", "Frosted", "Dark Tint"],
            "Olympus_3200": ["Closed Square", "Glazed", "Obscure", "Insulated", "Frosted", "Dark Tint"]
        },
        "Section": {
            "Heritage_1000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Heritage_2000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Heritage_3000": ["Bottom", "Intermediate", "Glazed", "Obscure", "Insulated"],
            "Lincoln_1000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Lincoln_2000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Lincoln_3000": ["Bottom", "Intermediate", "Glazed", "Obscure", "Insulated"],
            "Hillcrest_1000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Hillcrest_2000": ["Bottom", "Intermediate", "Glazed", "Obscure"],
            "Hillcrest_3000": ["Bottom", "Intermediate", "Glazed", "Obscure", "Insulated"],
            "Classica_1000": ["Bottom", "Intermediate", "Tempered", "Obscure"],
            "Classica_2000": ["Bottom", "Intermediate", "Tempered", "Obscure"],
            "Classica_3000": ["Bottom", "Intermediate", "Tempered", "Obscure", "Insulated"],
            "Designers_Choice_3200": ["Bottom", "Intermediate", "Glazed", "Obscure", "Insulated"],
            "Olympus_3200": ["Bottom", "Intermediate", "Glazed", "Obscure", "Insulated"]
        }
    },
    "Radius": {
        "Construction": {
            "Stratford": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "Heritage": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "Lincoln": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "Hillcrest": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "Classica": ["15 SA66", "15 LA66", "LHRO66", "LHRI66", "15 SA70", "15 LA70", "LHRO70", "LHRI70", "15 LA80", "LHRO80", "LHRI80"],
            "Designers_Choice": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "Olympus": ["12 SA66", "15 SA66", "12 LA66", "15 LA66", "LHRO66", "LHRI66", "12 SA70", "15 SA70", "12 LA70", "15 LA70", "LHRO70", "LHRI70", "12 LA80", "15 LA80", "LHRO80", "LHRI80"]
        },
        "Width_Height": {
            "6X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "6X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "6X65": ["15 SA66", "LHRO66", "LHRI66"],
            "6X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "6X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "6X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "6X74": ["15 LA80", "LHRO80", "LHRI80"],
            "6X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "6X78": ["15 LA80", "LHRO80", "LHRI80"],
            "6X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "6X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "7X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "7X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "7X65": ["15 SA66", "LHRO66", "LHRI66"],
            "7X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "7X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "7X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "7X74": ["15 LA80", "LHRO80", "LHRI80"],
            "7X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "7X78": ["15 LA80", "LHRO80", "LHRI80"],
            "7X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "7X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "8X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "8X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "8X65": ["15 SA66", "LHRO66", "LHRI66"],
            "8X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "8X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "8X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "8X74": ["15 LA80", "LHRO80", "LHRI80"],
            "8X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "8X78": ["15 LA80", "LHRO80", "LHRI80"],
            "8X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "8X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "9X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "9X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "9X65": ["15 SA66", "LHRO66", "LHRI66"],
            "9X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "9X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "9X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "9X74": ["15 LA80", "LHRO80", "LHRI80"],
            "9X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "9X78": ["15 LA80", "LHRO80", "LHRI80"],
            "9X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "9X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "10X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "10X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "10X65": ["15 SA66", "LHRO66", "LHRI66"],
            "10X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "10X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "10X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "10X74": ["15 LA80", "LHRO80", "LHRI80"],
            "10X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "10X78": ["15 LA80", "LHRO80", "LHRI80"],
            "10X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "10X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "11X60": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "11X63": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "11X65": ["15 SA66", "LHRO66", "LHRI66"],
            "11X66": ["12 SA66", "15 SA66", "LHRO66", "LHRI66"],
            "11X69": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "11X70": ["12 SA70", "15 SA70", "LHRO70", "LHRI70"],
            "11X74": ["15 LA80", "LHRO80", "LHRI80"],
            "11X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "11X78": ["15 LA80", "LHRO80", "LHRI80"],
            "11X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "11X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "12X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "12X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "12X65": ["15 LA66", "LHRO66", "LHRI66"],
            "12X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "12X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "12X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "12X74": ["15 LA80", "LHRO80", "LHRI80"],
            "12X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "12X78": ["15 LA80", "LHRO80", "LHRI80"],
            "12X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "12X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "13X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "13X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "13X65": ["15 LA66", "LHRO66", "LHRI66"],
            "13X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "13X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "13X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "13X74": ["15 LA80", "LHRO80", "LHRI80"],
            "13X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "13X78": ["15 LA80", "LHRO80", "LHRI80"],
            "13X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "13X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "14X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "14X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "14X65": ["15 LA66", "LHRO66", "LHRI66"],
            "14X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "14X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "14X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "14X74": ["15 LA80", "LHRO80", "LHRI80"],
            "14X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "14X78": ["15 LA80", "LHRO80", "LHRI80"],
            "14X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "14X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "15X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "15X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "15X65": ["15 LA66", "LHRO66", "LHRI66"],
            "15X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "15X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "15X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "15X74": ["15 LA80", "LHRO80", "LHRI80"],
            "15X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "15X78": ["15 LA80", "LHRO80", "LHRI80"],
            "15X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "15X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "16X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "16X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "16X65": ["15 LA66", "LHRO66", "LHRI66"],
            "16X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "16X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "16X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "16X74": ["15 LA80", "LHRO80", "LHRI80"],
            "16X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "16X78": ["15 LA80", "LHRO80", "LHRI80"],
            "16X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "16X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "17X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "17X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "17X65": ["15 LA66", "LHRO66", "LHRI66"],
            "17X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "17X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "17X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "17X74": ["15 LA80", "LHRO80", "LHRI80"],
            "17X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "17X78": ["15 LA80", "LHRO80", "LHRI80"],
            "17X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "17X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "18X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "18X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "18X65": ["15 LA66", "LHRO66", "LHRI66"],
            "18X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "18X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "18X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "18X74": ["15 LA80", "LHRO80", "LHRI80"],
            "18X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "18X78": ["15 LA80", "LHRO80", "LHRI80"],
            "18X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "18X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "19X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "19X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "19X65": ["15 LA66", "LHRO66", "LHRI66"],
            "19X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "19X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "19X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "19X74": ["15 LA80", "LHRO80", "LHRI80"],
            "19X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "19X78": ["15 LA80", "LHRO80", "LHRI80"],
            "19X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "19X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "20X60": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "20X63": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "20X65": ["15 LA66", "LHRO66", "LHRI66"],
            "20X66": ["12 LA66", "15 LA66", "LHRO66", "LHRI66"],
            "20X69": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "20X70": ["12 LA70", "15 LA70", "LHRO70", "LHRI70"],
            "20X74": ["15 LA80", "LHRO80", "LHRI80"],
            "20X76": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "20X78": ["15 LA80", "LHRO80", "LHRI80"],
            "20X79": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"],
            "20X80": ["12 LA80", "15 LA80", "LHRO80", "LHRI80"]
        }
    }
};
  $scope.Constructiondata = [];
  $scope.Height = [];
  $scope.Color_1 = [];
  $scope.Color_2 = [];
  $scope.Section = [];
  $scope.Radius = [];
  $scope.DoorForm = {};
  $scope.DoorForm.Hardware = "Standard Hardware";
  $scope.DoorForm.Struts_Windload = "Standard Struts";
  $scope.buttonSubmit = "Check Item";
  $scope.searchtype = {};
  $scope.searchtype.value = 'Repair Parts';
  $scope.tier = tier;
  $scope.dataInsert = {};
  //end New Door
  var vars = [],
  hash;
  $scope.initialPricebookForSearch = [];
  $scope.appID = $stateParams.appID;
  $scope.orgPage = getParameterByName('org_page');
  $scope.arrMeasurements = [];
  $scope.show_estimate_Color2 = false;
  $scope.checkbox = {};
  $scope.checkbox.isDeclinedAll = 0;
  $scope.type_add_app_select = [{ "key": "1", "value": "Yes - We have a date/time" },
  { "key": "2", "value": "Yes - we DO NOT have a date/time" },
  { "key": "3", "value": "No - do not schedule install appointment" }
  ];
  $scope.type_add_app_value = 'No - do not schedule install appointment';
  $scope.type_add_app = '3';

  $scope.check_Appointment_customer = function() {
    Orderstatuses.check_Appointment_customer($scope.customer_id, $scope.appointment_id, $scope.getestimate_id).success(function(data) {
      if (data.status) {
        var alertPopup = $ionicPopup.alert({
          title: 'Alert',
          template: $scope.notification
        });
        alertPopup.then(function(res) {
          redirectTo($window.location.reload());
        });
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getEstimateData = function(getNewPrice) {
    $scope.closeTarget('#popupOrderInvoiceDetail');
    $ionicLoading.show({
      template: templateLoading
    });
    Orderstatuses.getPaging($scope.estimate_insertGetId, getNewPrice).success(function(data) {
      $scope.order_jobsite = data.order_jobsite;
      $scope.dataInsert.Jobsite_id = "";
      if (data.jobsite_id != "0")
        $scope.dataInsert.Jobsite_id = data.jobsite_id;
      $scope.setValueServiceLocation($scope.dataInsert.Jobsite_id, 'getData');
      $scope.couponprice = data.coupon_value ? data.coupon_value : 0;
      $scope.couponData = data.coupon_id;
      $scope.dataInsert.coupon_id = data.coupon_id;
      $scope.Input_value.couponData = $scope.setValueInput($scope.couponData, data.coupon);
      $scope.appointments = data.appointments;
      $scope.StoreLocation = data.store_location;
      $ionicLoading.hide();
      $scope.pricebookdata = data.data;
      for (var i = 0; i < $scope.pricebookdata.length; i++) {
        if ($scope.pricebookdata[i].Measurements != undefined) {
          $scope.pricebookdata[i].Measurements.can_op_go_up = $scope.pricebookdata[i].Measurements.can_op_go_up;
          $scope.pricebookdata[i].Measurements.floor_to_ceiling_at_center_plate = parseFloat($scope.pricebookdata[i].Measurements.floor_to_ceiling_at_center_plate).toFixed(2);
          $scope.pricebookdata[i].Measurements.floor_to_ceiling_at_drums = parseFloat($scope.pricebookdata[i].Measurements.floor_to_ceiling_at_drums).toFixed(2);
          $scope.pricebookdata[i].Measurements.floor_to_hor_at_backhanger = parseFloat($scope.pricebookdata[i].Measurements.floor_to_hor_at_backhanger).toFixed(2);
          $scope.pricebookdata[i].Measurements.floor_to_hor_at_radius = parseFloat($scope.pricebookdata[i].Measurements.floor_to_hor_at_radius).toFixed(2);
          $scope.pricebookdata[i].Measurements.floor_to_op_rail_18 = parseFloat($scope.pricebookdata[i].Measurements.floor_to_op_rail_18).toFixed(2);
          $scope.pricebookdata[i].Measurements.floor_to_op_rail_at_stop_bolt = parseFloat($scope.pricebookdata[i].Measurements.floor_to_op_rail_at_stop_bolt).toFixed(2);
          $scope.pricebookdata[i].Measurements.opening_height_left = parseFloat($scope.pricebookdata[i].Measurements.opening_height_left).toFixed(2);
          $scope.pricebookdata[i].Measurements.opening_height_middle = parseFloat($scope.pricebookdata[i].Measurements.opening_height_middle).toFixed(2);
          $scope.pricebookdata[i].Measurements.opening_height_right = parseFloat($scope.pricebookdata[i].Measurements.opening_height_right).toFixed(2);
          $scope.pricebookdata[i].Measurements.opening_width = parseFloat($scope.pricebookdata[i].Measurements.opening_width).toFixed(2);
        }
      }
      $scope.comment.value = data.comment;
      $scope.customer_id = data.customer_id;
      $scope.appointment_id = data.appointment_id;
      $scope.searchData.pricebookdt = data.list_product;
      $scope.customertype_id = data.customertype_id;
      if (!getNewPrice) {
        if (data.service == '5' || data.service == '7') {
          $scope.Service = data.service_option;
          $scope.OptionService = data.service;
          setTimeout(function() {
            $scope.$apply(function(val) {
              $scope.selectService($scope.Service, $scope.OptionService);
            });
          }, 50);
        } else {
          $scope.Service = data.service;
          $scope.selectService($scope.Service, '');
        }
      }else{
        if($scope.Service == '6'){
          $scope.StoreLocation = $scope.store_location ? $scope.store_location : 'Burnsville';
        }else{
          $scope.StoreLocation = null;
        }
      }
      $scope.Installer_date = data.installer_date;
      $scope.coupon = data.coupon;
      $scope.Installer = data.installer;
      $scope.estimate_no = data.invoice_no;
      $scope.getTypeOfService();
      // edit by haudao
      $scope.Input_value.service = $scope.setValueInput($scope.Service, $scope.typeOfService);
      $scope.Input_value.optionService = $scope.setValueInput($scope.OptionService, $scope.optionOfService);
      // end edit
      // $scope.replaceRes();
      // $('.tblloader').hide();
      setTimeout(function() {
        $scope.$emit('sendtotal', {
          total: $scope.total,
          appointment: $scope.appointments,
          order_no: $scope.estimate_no,
          pushchatroom: $scope.pushChatRoom,
          order_jobsite: $scope.order_jobsite,
          order_id: $scope.estimate_insertGetId,
          customertype_id: $scope.customertype_id
        });
      }, 200);

      $scope.changeInfoTemplate();

      $scope.dataInsertProducts = [];
      $scope.getListProducts({ search: '', from: 'app' });
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  };
  $scope.searchData = {};
  $scope.searchData.data = [];
  $scope.searchData.pricebookdt = [];
  $scope.refreshpricebook = function(search) {
    if (search.length > 2) {
      var params = {
        search: search
      };
      $('.tblloader').show();
      Products.getSelect2(params, $scope.searchtype.value).success(function(data) {
        var diff = differentArray(data, $scope.searchData.pricebookdt);
        $scope.searchResult = diff;
        // console.log($scope.searchResult);
        $('.tblloader').hide();
      })
    }
  };
  // $scope.AdvancedEmailrequiredemail = function(value, $index) {
  //         if (value) {
  //             $('.indexemailrequired').removeAttr('required');
  //             $('#indexemail-' + value).attr("required", "true");
  //         }
  //     }
  // $scope.pricebookdata = [];
  $scope.insertItemPricebook = function(data) {
    if (data.length == 0) return;
    $ionicLoading.show({
      template: templateLoading
    });
    for (var i = 0; i < data.length; i++) {
      $scope.itemPB = {};
      $scope.itemPB['id'] = data[i].id;
      $scope.itemPB['name'] = data[i].name;
      var list_product = arrayUnion($scope.searchData.pricebookdt, [$scope.itemPB], function(item1, item2) {
        return item1.id == item2.id;
      });
      $scope.searchData.pricebookdt = list_product;
    }

    Products.getDataProduct(data, 'estimate_multi').success(function(data) {
      $ionicLoading.hide();
      $scope.show_estimate_Color2 = false;
      $scope.searchResult = [];
      if(data){
        for (var i = 0; i < data.length; i++) {
          var index = _.findIndex($scope.pricebookdata, { id: data[i].id });
          $scope.MeasurementById = _.where($scope.arrMeasurements, { id: data[i].id });
          if ($scope.MeasurementById.length > 0) {
            data[i].Measurements = $scope.MeasurementById[0].data;
          }
          if (index < 0) {
            $scope.pricebookdata.push(data[i]);
          }else{
            if(data[i].Measurements){
              $scope.invoiceData[index].Measurements = data[i].Measurements ;
            }
          }
        }
        $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
        $scope.changeInfoTemplate();
      $(".box-expandable").addClass('expand');
      }    
      $scope.getListPairProduct(data);
       
    });
  };

  $scope.getListPairProduct = function(data){
    var pairproducts =  _.filter(data,function(item){
        return item.has_paired_product == true && item.is_full_door == true;
       });
       if(pairproducts.length>0){
        $scope.showSelectCornerstyle(pairproducts);
       }
}
  
  $scope.change_coupon = function(id) {
    $scope.dataInsert.coupon_id = id;
    $scope.Input_value.couponData = $scope.setValueInput(id, $scope.coupon);
    if (id == '' || id == null || id == '0') {
      $scope.couponprice = 0;
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    } else {
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
      var curr_coupon = _.find($scope.coupon, { "id": id });
      if (curr_coupon.id == id) {
        if (curr_coupon.type == "%") {
          $scope.couponprice = ($scope.Subtotal - $scope.Discount) * parseInt(curr_coupon.discount) / 100;
        } else {
          $scope.couponprice = curr_coupon.discount;
        }
      }
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    }
  }

  $scope.setPriceEstimate = function(data, action) {
    var price;
    $scope.Subtotal = 0;
    $scope.total = 0;
    $scope.Discount = 0;
    $treechecked = 0;

    $scope.MD_Estimate = $scope.requiredfloat($scope.MD_Estimate);
    for (var i = 0; i < data.length; i++) {
      switch (action) {
        case '1':
        price = data[i]['Wholesale'];
        break;
        case '2':
        price = data[i]['Commercial'];
        break;
        case '4':
        price = data[i]['Contractor'];
        break;
        case '6':
        price = data[i]['Walk_In'];
        break;
        case '0':
        if ($scope.OptionService == '5') {
          price = data[i]['Retail'];
        } else {
          price = data[i]['Customer_Aquisition'];
        }
        break;
        case '-1':
        if ($scope.OptionService == '5') {
          price = data[i]['Retail'];
        } else {
          price = data[i]['Customer_Aquisition'];
        }
        break;
      }
      //change MD all
      if ($scope.MD_Estimate != '' && $scope.check_MD_Estimate == 1) {
        data[i]['Extended'] = $scope.MD_Estimate;
      }
      //change declined all
      if ($scope.check_Declined == 1) {
        if ($scope.Declined.value == 1) {
          data[i]['declined'] = 1;
        }
        if ($scope.Declined.value == 0) {
          data[i]['declined'] = 0;
        }
      }
      data[i]['Extended'] = $scope.requiredfloat(data[i]['Extended']);
      data[i]['quantity'] = $scope.requirednumber(data[i]['quantity']);
      $('.quantity-' + data[i]['id']).val(data[i]['quantity']);
      $('.discount-' + data[i]['id']).val(data[i]['Extended']);
      $('.warranty-' + data[i]['id']).val(data[i]['warranty_id']);
      data[i]['price'] = price;
      data[i]['priceshow'] = price;
      data[i]['Extended_Price'] = parseFloat((data[i]['priceshow'] * data[i]['quantity']) - ((data[i]['priceshow'] * data[i]['Extended'] * data[i]['quantity']) / 100)).toFixed(2);
      $('.' + data[i]['id'] + data[i]['item_id']).html('$' + data[i]['Extended_Price']);
      if (data[i]['declined'] == 0) {
        $scope.Declined.value = 0;
        $scope.Subtotal += (data[i]['priceshow'] * data[i]['quantity']);
        $scope.Discount += ((data[i]['priceshow'] * data[i]['Extended'] * data[i]['quantity']) / 100);
      } else {
        $treechecked++;
      }
    }
    if ($scope.check_MD_Estimate == 1) {
      $scope.check_MD_Estimate = 0;
    }
    if ($scope.check_Declined == 1) {
      $scope.check_Declined = 0;
    }
    if ($treechecked == data.length) {
      $scope.Declined.value = 1;
    }
    $scope.Discount = parseFloat($scope.Discount).toFixed(2);
    $scope.Subtotal = parseFloat($scope.Subtotal).toFixed(2);
    $scope.pricebookdata = data;
    if ($scope.loadRespondsive == 0) {
      $scope.replaceRes();
    }

    //new cal value estimate
    if ($scope.dataInsert.coupon_id && parseInt($scope.dataInsert.coupon_id) > 0) {
      var curr_coupon = _.find($scope.coupon, { "id": $scope.dataInsert.coupon_id });
      if (curr_coupon.type == "%") {
        $scope.couponprice = ($scope.Subtotal - $scope.Discount) * parseInt(curr_coupon.discount) / 100;
      } else {
        $scope.couponprice = curr_coupon.discount;
      }
    } else {
      $scope.couponprice = 0;
    }

    $scope.total = parseFloat($scope.Subtotal - $scope.Discount - $scope.couponprice).toFixed(2);
    $scope.loadRespondsive = 0;
    setTimeout(function() {
      for (var i = 0; i < data.length; i++) {
        $('.warranty-' + data[i]['id']).val(data[i]['warranty_id']);
      }
      $('.editMeasurements').unbind("click");
      $('.editMeasurements').click(function() {
        $scope.buttonSubmitEditMeasurements = "Save";
        $scope.refreshform();
        var json_data = JSON.parse($(this).attr('Measurementsdata'));
        $scope.setDataForFormEditMeasurements(json_data);
        $scope.product_idEdit = $(this).attr('productId');
        var productName = $(this).attr('productName');
        var doortring = productName.split("x");
        var width = doortring[0].split(" ")[doortring[0].split(" ").length - 1];
        $scope.heightedit = doortring[1].substring(0, 2);
        var Const = doortring[1].split(" ")[1];
        var Construction = $scope.DoorData.Radius.Construction[Const];
        var Width_Height = $scope.DoorData.Radius.Width_Height[width + 'X' + $scope.heightedit];
        $scope.Radius = _.intersection(Construction, Width_Height);
        // if ($scope.Measurements.can_op_go_up != '' && $scope.Measurements.can_op_go_up != null) {
        //     $scope.Measurements.can_op_go_up_action = '1';
        // } else {
        //     $scope.Measurements.can_op_go_up_action = '0';
        // }
        //$scope.changecan_op_go_up();
        $scope.InchesTable($scope.heightedit, 'edit');
        $ionicLoading.show({
          template: templateLoading
        });
        $scope.styleOfMeasurement = "Edit";
        // $scope.openByGetTemplate('estimateMeasurementsPage');
        $scope.openByGetTemplate('popupOrderEstimateMeasurements');
        setTimeout(function() {
          $ionicLoading.hide();
          if (doortring[1].split(" ")[doortring[1].split(" ").length - 1].length < 6) {
            $scope.DoorForm.Radius = doortring[1].split(" ")[doortring[1].split(" ").length - 2] + ' ' + doortring[1].split(" ")[doortring[1].split(" ").length - 1];
          } else {
            $scope.DoorForm.Radius = doortring[1].split(" ")[doortring[1].split(" ").length - 1]
          }
          $scope.RadiusEdit = $scope.DoorForm.Radius;
          $scope.NameDoor = productName.split($scope.RadiusEdit);
        }, 500);
      });
    }, 100);
    $scope.changeInfoTemplate();

  }

  $scope.changeInfoTemplate = function() {
    $scope.templateData.dataInfoCustomer = $scope.dataInfoCustomer ? $scope.dataInfoCustomer : { first_name: "No", last_name: "Name" };
    $scope.templateData.subtotal = $scope.total ? $scope.total : 0;
    $scope.templateData.estimate_no = $scope.estimate_no;
  }

  $scope.change_MD_Estimate = function(MD_Estimate) {
    if ($scope.check_MD_Estimate == 0) {
      $scope.check_MD_Estimate = 1;
    }
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }

  $scope.email_sento = {};
  $scope.email_sento.value = '';
  $scope.save_estimate = function(actions) {
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.dataInsert.data = $scope.pricebookdata;
    $scope.dataInsert.Subtotal = $scope.Subtotal;
    $scope.dataInsert.Discount = $scope.Discount;
    $scope.dataInsert.user_id = $scope.currentIdLogin;
    $scope.dataInsert.action = actions;
    $scope.dataInsert.Estimate_id = $scope.estimate_insertGetId;
    $scope.dataInsert.comment = $scope.comment.value;
    $scope.dataInsert.customer_id = $scope.customer_id;
    $scope.dataInsert.appointment_id = $scope.appointment_id;
    $scope.dataInsert.email_sento = $scope.email_sento.value;
    $scope.dataInsert.invoice_id = $scope.invoice_check;
    $scope.dataInsert.estimate_no = $scope.estimate_no;
    $scope.dataInsert.AdvancedEmail = $scope.AdvancedEmail;
    $scope.dataInsert.coupon_value = $scope.couponprice;
    $scope.dataInsert.store_location = $scope.StoreLocation;
    if ($scope.Service > 0) {
      $scope.dataInsert.service_id = $scope.Service;
      $scope.dataInsert.service_option = null;
    } else {
      $scope.dataInsert.service_id = $scope.OptionService;
      $scope.dataInsert.service_option = $scope.Service;
    }
    if (actions == 'insertConvert_Est_to_Sale_Order' && parseInt($scope.inserted_to_schedule_id) > 0) {
      $scope.dataInsert.inserted_to_schedule_id = $scope.inserted_to_schedule_id;
    }
    Orderstatuses.save($scope.dataInsert).success(function(data) {
      $scope.getOrders();
      $scope.closeTarget('#popupOrderEstimateDetailOptions');
      $scope.closeTarget('#popupOrderEstimateDetailItemTransfer');
      $scope.closeTarget('#popupOrderEstimateSendToDetail');
      $ionicLoading.hide();
      if (actions == 'insertConvert_Est_to_Sale_Order' || actions == 'updateConvert_Est_to_Sale_Order') {
        $scope.dataResultConvertSaleOrder = data;
        if (data.redirect_to == 'invoice') {
          $scope.goToInvoiceDetails(data.order_id, 0);
        }
        if (data.redirect_to == 'saleorder') {
          $scope.goToSaleorderDetails(data.order_id, 0);
        }
      }
      if ($scope.check_create_task == 1) {
        $scope.create_task();
        $scope.check_create_task = 0;
      }
      if (data.status && data.action == 'openpage') {
        $scope.cordovaBrowser(data.link);
      }
      // if (data.Redirect) {
      //     $scope.goToInvoiceDetails(data.order_id, 0)
      // }
      if (data.status) {
        $scope.arrMeasurements = [];
        $scope.estimate_insertGetId = data.order_id;
        $scope.getEstimateData(false);
        if (data.msg) $cordovaToast.showLongTop(data.msg);
      } else {
        if (data.msg) $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.option_save_estimate = function(action, sendto, email, Snail_Mail, formValidate) {
    if (formValidate && formValidate.$invalid) {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    // console.log(action, sendto, email, Snail_Mail);
    // Send_To Snail_Mail none@none.com hauhuu.glinking@gmail.com

    if ($scope.estimate_insertGetId == '') {
      switch (action) {
        case 'saveEstimate':
        $scope.save_estimate('insertEstimate');
        break;
        case 'saveAndCreateEstimate':
        $scope.save_estimate('insertAndCreateEstimate');
        break;
        case 'saveComment':
          // if(sendto.length < 500){
          // $scope.comment.value = sendto;
          $scope.closeTarget('#popupOrderEstimateDetailAddComment');
          $cordovaToast.showLongTop('Comment will be saved at the same time you save the estimate.');
          // } else {
          //  toastr.error('nhiều  hơn 500 ký tự');
          // }
          break;
          case 'Convert_Est_to_Sale_Order':
          $scope.save_estimate('insertConvert_Est_to_Sale_Order');
          break;
          case 'Transfer_items':
          if ($scope.invoice_check) $scope.save_estimate('insert_Transfer_items');
          break;
          case 'Send_To':
          switch (sendto) {
            case 'AdvancedEmail':
            $scope.email_sento.value = email;
            $scope.save_estimate('insert_AdvancedEmail');
            break;
            case 'email':
            $scope.email_sento.value = email;
            $scope.save_estimate('insert_send_PDF');
            break;
            case 'Generate_printable_PDF':
            $scope.save_estimate('insert_printable_PDF');
            break;
            case 'Snail_Mail':
            $scope.Snail_Mail.value = Snail_Mail;
            $scope.check_create_task = 1;
            $scope.save_estimate('insertEstimate');
            break;
            case 'Generate_printable_PDF_DPI':
            $scope.save_estimate('update_printable_PDF_DPI');
            break;
          }
          break;
        }
      } else {
        switch (action) {
          case 'saveEstimate':
          $scope.save_estimate('updateEstimate');
          break;
          case 'saveAndCreateEstimate':
          $scope.save_estimate('updateAndCreateEstimate');
          break;
          case 'saveComment':
          // if(sendto.length < 500){
          // $scope.comment.value = sendto;
          $scope.updateComment();
          // } else {
          //  toastr.error('nhiều  hơn 500 ký tự');
          // }
          break;
          case 'Convert_Est_to_Sale_Order':
          $scope.save_estimate('updateConvert_Est_to_Sale_Order');
          break;
          case 'Transfer_items':
          if ($scope.invoice_check) $scope.save_estimate('update_Transfer_items');
          break;
          case 'Send_To':

          switch (sendto) {
            case 'AdvancedEmail':
            $scope.email_sento.value = email;
            $scope.save_estimate('update_AdvancedEmail');
            break;
            case 'email':
            $scope.email_sento.value = email;
            $scope.save_estimate('update_send_PDF');
            break;
            case 'Generate_printable_PDF':
            $scope.save_estimate('update_printable_PDF');
            break;
            case 'Snail_Mail':
            $scope.Snail_Mail.value = Snail_Mail;
            $scope.check_create_task = 1;
            $scope.save_estimate('updateEstimate');
            break;
            case 'Generate_printable_PDF_DPI':
            $scope.save_estimate('update_printable_PDF_DPI');
            break;
          }
          break;
        }
      }
    }
    $scope.checked_invoice = function(invoice_check) {
      $scope.invoice_check = invoice_check;
    }
    $scope.AdvancedEmail = {};
    $scope.getcustomermail = function() {
      $scope.AdvancedEmail = {};
      $scope.AdvancedEmail.emails = [];
      $ionicLoading.show({ template: templateLoading });
      Orderstatuses.getcustomermail($scope.customer_id).success(function(data) {
        $ionicLoading.hide();
        $scope.customermail = data.customerMail;
        _.each(data.customerMail, function(item) {
          $scope.AdvancedEmail.emails.push({ text: item.email });
        });
      // angular.copy($scope.AdvancedEmail.emails, $scope.tags);
      // $scope.initialEstimateSendFrom = _.findWhere($scope.allUser, { email: $scope.dataChangePassword.emailShow }).id;
      $scope.initialEstimateSendFrom = $scope.currentIdLogin;
      $scope.AdvancedEmail.Message = "";
      $scope.AdvancedEmail.Message = 'Hi ' + data.customerData.first_name + ' ' + data.customerData.last_name + ' \n' +
      $scope.AdvancedEmail.Message + "\r\n" +
      'Thank you for the opportunity to earn your business and I personally appreciate you as a customer.';
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.AdvancedEmailCustomer = function(type, sendtoType, email, snail_mail, formValidate) {
    if (sendtoType == 'Generate_printable_PDF') {
      $scope.option_save_estimate('Send_To', 'Generate_printable_PDF');
      return;
    }
    if (formValidate.$invalid) {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    if (sendtoType == 'advance') {
      $scope.AdvancedEmail.sendmail = $scope.AdvancedEmail.emails;
      $scope.option_save_estimate(type, 'AdvancedEmail', $scope.AdvancedEmail, '');
    } else {
      $scope.option_save_estimate(type, sendtoType, email, snail_mail)
    }
  }
  $scope.show_customer_address = function(sendto) {
    switch (sendto) {
      case 'email':
      $('#customer_email').hide();
      $('#sendmailpdf').show();
      $('#email_sento').attr("required", "true");
        //$('#Snail_Mail').removeAttr('required');
        break;
        case 'Generate_printable_PDF':
        $('#customer_email').hide();
        $('#sendmailpdf').hide();
        $('#email_sento').removeAttr('required');
        //$('#Snail_Mail').removeAttr('required');
        break;
        case 'Snail_Mail':
        $('#customer_email').show();
        $('#sendmailpdf').hide();
        //$('#Snail_Mail').attr("required", "true");
        $('#email_sento').removeAttr('required');
        break;
      }
    }
    $scope.requirednumber = function(value) {
      if (!value) return 0;
      if (value.length == 0) {
        value = 0;
      }
      value = parseInt(value.toString().replace(/[^0-9]/g, ''));
      if (isNaN(value) == true) {
        value = 0;
      }
      return value;
    };
    $scope.requiredfloat = function(value) {
      if (!value) return 0;
      if (value.length == 0) {
        value = 0;
      } else {
        var item_length = value.toString().split('.').length;
        value = value.toString().replace(/[^0-9-.]/g, '');
        if (item_length > 1 && value.toString().split('.')[1] != '' && value.toString().split('.')[1] != 0) {
          var part_2 = value.toString().split('.')[1];
          if (part_2.length > 2) {
            var new_part_2 = part_2.charAt(0) + part_2.charAt(part_2.length - 1);
            var new_part_2_to_number = parseFloat(new_part_2) / 100;
            var par_1 = parseFloat(value.toString().split('.')[0]);
            return par_1 + new_part_2_to_number;
          } else {
            value = parseFloat(value);
            return value;
          }
        }
        if (item_length == 1) {
          value = parseFloat(value);
        }
      }
      if (isNaN(value) == true) {
        value = 0;
      }
      return value;
    };
    $scope.create_task = function() {
    // var path = window.location.href;
    // var pathname = window.location.href.split('/');
    // var pa = path.lastIndexOf('/' + pathname[pathname.length - 1]);
    // var url_site=path.substring(0, pa);
    $ionicLoading.show({
      template: templateLoading
    });
    Orderstatuses.create_task($scope.Snail_Mail.value, $scope.currentIdLogin, $scope.appointment_id, 'estimate', $scope.customer_id, url_site, $scope.estimate_insertGetId).success(function(data) {
      $ionicLoading.hide();
      if (data.status) {
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongTop(data.msg);
      }

    });
  }
  $scope.updateMD = function(val) {
    // closeTarget('#popupOrderEstimateDetailEditMDAllItem');
    $scope.closeTarget('#popupOrderEstimateDetailDiscountCoupon');
    //closeTarget('#popupOrderEstimateDetailItemEdit');
    if (!val) return;
    angular.forEach($scope.pricebookdata, function(item) {
      item.Extended = parseFloat(val);
    })
    $cordovaToast.showLongTop('MD% is applied to all items. Please tap SAVE to save other changes to selected item.');
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.updateComment = function() {
    $ionicLoading.show({
      template: templateLoading
    });
    Orderstatuses.updateComment($scope.comment.value, $scope.estimate_insertGetId).success(function(data) {
      if (data.status) {
        $ionicLoading.hide();
        $scope.closeTarget('#popupOrderEstimateDetailComment');
        $cordovaToast.showLongTop(data.msg);
      } else {
        $cordovaToast.showLongCenter(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.change_price = function() {
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);

  }
  $scope.change_MD = function(MD_Estimate, product_id) {
    // $scope.MD_Estimate = MD_Estimate;
    // if($scope.check_MD_Estimate == 0){
    //  $scope.check_MD_Estimate = 1;
    // }
    for (var i = 0; i < $scope.pricebookdata.length; i++) {
      if ($scope.pricebookdata[i]['id'] == product_id) {
        $scope.pricebookdata[i]['Extended'] = MD_Estimate;
      }
    }
    $scope.loadRespondsive = 1;
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.change_warranty = function(warranty_id, product_id) {
    for (var i = 0; i < $scope.pricebookdata.length; i++) {
      if ($scope.pricebookdata[i]['id'] == product_id) {
        var warranty = _.where($scope.Warrantydata, { id: warranty_id })[0];
        $scope.pricebookdata[i]['warranty_id'] = warranty.id;
        $scope.pricebookdata[i]['warranty_name'] = warranty.name;
      }
    }
    $scope.loadRespondsive = 1;
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.change_Declined = function() {
    if ($scope.check_Declined == 0) {
      $scope.check_Declined = 1;
    }
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.selectService = function(sevice, Option , action) {
    if(action&&$scope.estimate_insertGetId){
      $scope.getEstimateData(true);
    }
    if (sevice < 1) {
      $scope.Service = sevice;
      if (Option != '') {
        $scope.OptionService = Option;
      }
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    } else {
      $scope.Service = sevice;
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    }
    $scope.Input_value.service = $scope.setValueInput($scope.Service, $scope.typeOfService);
    $scope.Input_value.optionService = $scope.setValueInput($scope.OptionService, $scope.optionOfService);
  }

  $scope.replaceRes = function() {
    // setTimeout(function() {
    //     $scope.$apply(function(val) {
    //         if (val) {
    //             $('#table_child').tableRespondsive({
    //                 paging: true,
    //                 pagingArg: {
    //                     totalRow: 105,
    //                     rowPerPage: 50,
    //                     currentPage: 2
    //                 }
    //             });
    //             $('#table_child .caption .col-md').click(function() {
    //                 $(this).find('.input-md').show();
    //             })
    //             if ($scope.pricebookdata.length > 0) {
    //                 if ($scope.pricebookdata[0].name == '' && $scope.pricebookdata[0].id == '') {
    //                     $scope.pricebookdata = [];
    //                 }
    //             }
    //             $('#content').show();
    //             $('.tblloaderroot').hide();
    //         }
    //     });
    // }, 50);
    if ($scope.pricebookdata.length > 0 && $scope.pricebookdata[0].name == '' && $scope.pricebookdata[0].id == '') {
      $scope.pricebookdata = [];
    }
  }
  // $scope.replaceRes();
  $scope.changequantity = function(quantity, product_id) {
    for (var i = 0; i < $scope.pricebookdata.length; i++) {
      if ($scope.pricebookdata[i]['id'] == product_id) {
        $scope.pricebookdata[i]['quantity'] = quantity;
      }
    }
    $scope.loadRespondsive = 1;
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.getTypeOfService = function() {
    Orderstatuses.getTypeOfService().success(function(data) {
      $scope.servicedata = data;
      $scope.getCornerstyles();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getRepresentative = function() {
    Orderstatuses.getRepresentative($scope.currentIdLogin, $scope.getestimate_id, $scope.customer_id).success(function(data) {
      $scope.representative = data.rep;
      $scope.invoice_data = data.invoice_data;
      $scope.dataInfoCustomer = data.dataCustomer;
      if ($scope.jobsitedata.length == 0) {
        $scope.Input_value.serviceLocation = $scope.dataInfoCustomer.street + ', ' + $scope.dataInfoCustomer.city + ', ' + $scope.dataInfoCustomer.state + ', ' + $scope.dataInfoCustomer.zipcode;
      }
      $scope.jobsitedata = data.jobsite;
      $scope.setValueServiceLocation($scope.dataInsert.Jobsite_id, '');
      $scope.date = data.date;
      $scope.email_sento.value = data.mail;
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
      $scope.replaceRes();
      !$scope.check_init_estimate ? $interval($scope.checkLogin, time_refresh) : '';
      request_notify_get_chat = true;
      $scope.check_init_estimate = true;
      $scope.data_to_schedule = _.where(data.data_appointment, {
        fieldworker: null
      });
      $scope.data_appointment = _.filter(data.data_appointment, function(val) {
        return parseInt(val.fieldworker) > 0;
      });
      $scope.changeInfoTemplate();
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.getCornerstyles = function() {
    Orderstatuses.getCornerstyles().success(function(data) {
      $scope.cornerstyles = data;
      $scope.getRepresentative();
    });
  }
  $scope.getEstimateNumber = function() {
    Orderstatuses.getEstimateNumber($scope.appointment_id).success(function(data) {
      $scope.estimate_no = data.data;
      $scope.total = 0;
      $ionicLoading.hide();
      $scope.dataInsertProducts = [];
      $scope.getListProducts({ search: '', from: 'app' });
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  //New Door
  $scope.DoorFormProduct = function(action) {
    switch (action) {
      case 'Question1':
      if ($scope.DoorForm.Question1 == "Door") {
        $scope.Input_value.estimateQuestion1 = 'Door';
        $scope.Input_value.Hardware="Blank";
        $scope.DoorForm.Hardware="Standard Hardware";
        $('#Hardware').show();
        $("#Struts").show();
        $("#Radius").show();
        $scope.labelbutton = 'Next';
          // $('.Hardware').attr("required", "required");
          // $('.Struts_Windload').attr("required", "required");
        } else {
          $scope.Input_value.Hardware="";
          $scope.DoorForm.Hardware="";
          if ($scope.DoorForm.Question1 == "Section Section") {
            $scope.Input_value.estimateQuestion1 = 'Section Set';
          } else {
            $scope.Input_value.estimateQuestion1 = 'Select';
          }
          $('#Hardware').hide();
          $("#Struts").hide();
          $("#Radius").hide();
          $scope.labelbutton = 'Search';
          // $('.Struts_Windload').removeAttr('required');
          // $('.Hardware').removeAttr('required');
        }
        // if($scope.DoorForm.Question1=="Panel" || $scope.DoorForm.Question1=="Section Section"){
        //     $('.notifNewDoor').show();
        //     $("#buttons1").hide();
        // } else {
        //     $("#buttons1").show();
        //     $('.notifNewDoor').hide();
        // }
        //getdata height
        $scope.getdataHeight();
        //getdata Section
        $scope.getdataSection();
        $scope.getdataRadius();
        break;
        case 'Model':
        //getdata construction
        if ($scope.DoorForm.Model != '' && $scope.DoorForm.Model != undefined) {
          $scope.DoorForm.Model == '3200' ? $scope.Constructiondata = $scope.DoorData.Construction[1] : $scope.Constructiondata = $scope.DoorData.Construction[0];
          //$('#Construction').show();
        } else {
          //$('#Construction').hide();
        }
        //getdata stamp color1
        $scope.getdataStampColor1();
        //getdata height
        $scope.getdataHeight();
        //getdata Section
        $scope.getdataSection();
        break;
        case 'Construction':
        //getdata height
        $scope.getdataHeight();
        //getdata stamp color1
        $scope.getdataStampColor1();
        //getdata Section
        $scope.getdataSection();
        //getdata Radius
        $scope.getdataRadius();
        break;
        case 'Width':
        //getdata Radius
        $scope.getdataRadius();
        break;
        case 'Height':
        //getdata Radius
        $scope.getdataRadius();
        break;
        case 'Color_1':
        //getdata color2
        $scope.getdataStampColor1();
        if ($scope.DoorForm.Color_1.substring($scope.DoorForm.Color_1.length - 4, $scope.DoorForm.Color_1.length) == "Base") {
          $scope.Color_2 = $scope.DoorData.Color.Color2[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model];
          $scope.show_estimate_Color2 = true;
          $scope.DoorForm.Color_2 = '';
        } else {
          $scope.Color_2 = [];
          $scope.show_estimate_Color2 = false;
          $scope.DoorForm.Color_2 = '';
        }
        break;
      }
    }

    $scope.getdataHeight = function() {
      if ($scope.DoorForm.Question1 != '' && $scope.DoorForm.Model != '' && $scope.DoorForm.Construction != '' && $scope.DoorForm.Question1 != undefined && $scope.DoorForm.Model != undefined && $scope.DoorForm.Construction != undefined) {
        if ($scope.DoorForm.Question1 == 'Door' || $scope.DoorForm.Question1 == 'Section Section') {
          if ($scope.DoorForm.Construction == 'Classica') {
            $scope.Height = $scope.DoorData.Height.ModelHeight[1];
          } else {
            $scope.Height = $scope.DoorData.Height.ModelHeight[0];
          }
        } else {
          if ($scope.DoorForm.Construction == 'Classica') {
            $scope.Height = $scope.DoorData.Height.ModelHeight[1];
          } else {
            $scope.Height = $scope.DoorData.Height.ModelHeight[0];
          }
        // if ($scope.DoorForm.Construction == 'Classica') {
        //     $scope.Height = $scope.DoorData.Height.Panel_Height[1];
        // } else {
        //     $scope.Height = $scope.DoorData.Height.Panel_Height[0];
        // }
      }
      // $('#Height').show();
      // $('#Width').show();
    } else {
      // $('#Height').hide();
      // $('#Width').hide();
    }
  }
  $scope.getdataSection = function() {
    if ($scope.DoorForm.Question1 != '' && $scope.DoorForm.Model != '' && $scope.DoorForm.Construction != '' && $scope.DoorForm.Question1 != undefined && $scope.DoorForm.Model != undefined && $scope.DoorForm.Construction != undefined) {
      if ($scope.DoorForm.Question1 == "Panel") {
        $scope.Section = $scope.DoorData.Top_Section.Section[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model];
      } else {
        $scope.Section = $scope.DoorData.Top_Section.Top_Section[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model];
      }
      //$('#TopSection').show();
    } else {
      //$('#TopSection').hide();
    }
  }
  $scope.getdataRadius = function() {
    if ($scope.DoorForm.Question1 == 'Door' && $scope.DoorForm.Width != '' && $scope.DoorForm.Height != '' && $scope.DoorForm.Construction != '' && $scope.DoorForm.Width != undefined && $scope.DoorForm.Height != undefined && $scope.DoorForm.Construction != undefined) {
      var Construction = $scope.DoorData.Radius.Construction[$scope.DoorForm.Construction];
      var Width_Height = $scope.DoorData.Radius.Width_Height[$scope.DoorForm.Width + 'X' + $scope.DoorForm.Height];
      $scope.Radius = _.intersection(Construction, Width_Height);
      //$('#Radius').show();
      $('.Radius').attr("required", "required");
    } else {
      //$('#Radius').hide();
      $('.Radius').removeAttr('required');
    }
  }
  $scope.getdataStampColor1 = function() {
    if ($scope.DoorForm.Model != '' && $scope.DoorForm.Construction != '' && $scope.DoorForm.Model != undefined && $scope.DoorForm.Construction != undefined) {
      //getdata color
      $scope.Color_1 = $scope.DoorData.Color.Color1[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model];
      //getdata stamp
      $scope.Stamp = $scope.DoorData.Stamp[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model + '_' + $scope.DoorForm.Color_1];
      // $('#Color1').show();
      // $('#Stamp').show();
    } else {
      // $('#Color1').hide();
      // $('#Stamp').hide();
    }
  }
  $scope.Measurements = {};
  $scope.actionDoor = 'measurements';
  $scope.labelbutton = 'Search';
  $scope.validateForm = function(formValidate, style, scrollId) {
    var exitLoop = false;
    if (formValidate.$invalid) {
      $ionicScrollDelegate.$getByHandle(scrollId).scrollTop();
      $cordovaToast.showLongTop('Please fill all the required information.!!!');

      // angular.forEach(formValidate.$error, function(item) {
      //     if (!exitLoop) {
      //         var id = item[0].$name;
      //         $("#" + id).val('');
      //         $location.hash(id); //set the location hash
      //         var handle = show_customer_address;
      //         handle.anchorScroll(true);
      //         exitLoop = true;
      //         $timeout(function() {
      //             var top = handle.getScrollPosition().top - 170;
      //             handle.scrollTo(0, top, true);
      //             $cordovaToast.showLongTop('Please fill all the required information.!!!');
      //         }, 500);
      //     }
      // })
      return;
    };
    if (style == 'door') {
      $scope.DoorFormAddProduct();
    } else if (style == 'measurementsAdd') {
      $scope.MeasurementsAddProduct();
    } else if (style == 'measurementsEdit') {
      $scope.MeasurementsEditDoor();
    }
  }
  $scope.DoorFormAddProduct = function() {
    if ($scope.buttonSubmit == "Check Item") {
      var name;
      var Sectionsearch;
      var color2;
      var color1;
      var Construction;
      var Hardware;
      var Struts_Windload;
      //$scope.DoorForm.Color_2 != '' && $scope.DoorForm.Color_2 != undefined ? color2 = ' '+$scope.DoorForm.Color_2+' ' : color2 = ' ';
      //$scope.DoorForm.Color_2 != '' && $scope.DoorForm.Color_2 != undefined ? color1 = $scope.DoorForm.Color_1+'/' : color1 = $scope.DoorForm.Color_1;
      $scope.DoorForm.Color_1.substring($scope.DoorForm.Color_1.length - 4, $scope.DoorForm.Color_1.length) == "Base" ? color2 = ' ' + $scope.DoorForm.Color_2 + ' ' : color2 = ' ';
      $scope.DoorForm.Color_1.substring($scope.DoorForm.Color_1.length - 4, $scope.DoorForm.Color_1.length) == "Base" ? color1 = $scope.DoorForm.Color_1 + '/' : color1 = $scope.DoorForm.Color_1;
      Construction = $scope.DoorForm.Construction.replace("_", " ");
      //$scope.DoorForm.Hardware == 'Blank' ? Hardware = '': Hardware = ' '+ $scope.DoorForm.' '+ $scope.DoorForm.Hardware +' ' +' ';
      Construction == "Designers Choice" ? Construction = "Designer's Choice" : '';
      $scope.DoorForm.Struts_Windload == "Standard Struts" ? Struts_Windload = "" : Struts_Windload = $scope.DoorForm.Struts_Windload + ' ';
      switch ($scope.DoorForm.Question1) {
        case 'Door':
        if ($scope.actionDoor == 'measurements') {
          $scope.styleOfMeasurement = "Add";
          $scope.openByGetTemplate('popupOrderEstimateMeasurements');
          $scope.changeCornerstyles();
          return;
        }
        switch ($scope.DoorForm.Section) {
          case 'Glazed':
          Sectionsearch = 'Glass';
          break;
          case 'Tempered':
          Sectionsearch = 'Glass';
          break;
          case 'Obscure':
          Sectionsearch = 'Obscure Glass';
          break;
          case 'Insulated':
          Sectionsearch = 'Insulated Glass';
          break;
          case 'Closed Square':
          Sectionsearch = 'Closed Square';
          break;
          case 'Frosted':
          Sectionsearch = 'Frosted Glass';
          break;
          case 'Dark Tint':
          Sectionsearch = 'Dark Tint Glass';
          break;
          default:
          Sectionsearch = $scope.DoorForm.Section;
        }
        name = "Full Door | " + $scope.DoorForm.Width + "x" + $scope.DoorForm.Height + ' ' + Construction + ' ' + $scope.DoorForm.Model + ' ' + color1 + color2 + $scope.DoorForm.Stamp + ' ' + Sectionsearch + ' ' + $scope.DoorForm.Hardware + ' ' + Struts_Windload + $scope.DoorForm.Radius;
        break;
        case 'Panel':
        switch ($scope.DoorForm.Section) {
          case 'Glazed':
          Sectionsearch = 'Standard Glass';
          break;
          case 'Tempered':
          Sectionsearch = 'Standard Glass';
          break;
          case 'Obscure':
          Sectionsearch = 'Obscure Glass';
          break;
          case 'Insulated':
          Sectionsearch = '';
          break;
          case 'Intermidiate':
          Sectionsearch = 'Insulated Glass';
          break;
          case 'Bottom':
          Sectionsearch = 'Bottom';
          break;
          default:
          Sectionsearch = $scope.DoorForm.Section;
        }
          //$scope.DoorForm.Color_2 != '' && $scope.DoorForm.Color_2 != undefined ? color2 = ' '+$scope.DoorForm.Color_2+' ' : color2 = ' ';
          // Construction = $scope.DoorForm.Construction.replace("_", " ");
          // Construction == "Designers Choice" ? Construction = "Designer's Choice" : '';
          name = Sectionsearch + " Section | " + $scope.DoorForm.Width + "x" + $scope.DoorForm.Height + ' ' + Construction + ' ' + $scope.DoorForm.Model + ' ' + color1 + color2 + $scope.DoorForm.Stamp;
          break;
          case 'Section Section':
          switch ($scope.DoorForm.Section) {
            case 'Glazed':
            Sectionsearch = 'Glass';
            break;
            case 'Tempered':
            Sectionsearch = 'Glass';
            break;
            case 'Obscure':
            Sectionsearch = 'Obscure Glass';
            break;
            case 'Insulated':
            Sectionsearch = 'Insulated Glass';
            break;
            case 'Closed Square':
            Sectionsearch = 'Closed Square';
            break;
            case 'Frosted':
            Sectionsearch = 'Frosted Glass';
            break;
            case 'Dark Tint':
            Sectionsearch = 'Dark Tint Glass';
            break;
            default:
            Sectionsearch = $scope.DoorForm.Section;
          }
          //$scope.DoorForm.Color_2 != '' && $scope.DoorForm.Color_2 != undefined ? color2 = ' '+$scope.DoorForm.Color_2+' ' : color2 = ' ';
          // Construction = $scope.DoorForm.Construction.replace("_", " ");
          // Construction == "Designers Choice" ? Construction = "Designer's Choice" : '';
          name = "Section Set | " + $scope.DoorForm.Width + "x" + $scope.DoorForm.Height + ' ' + Construction + " " + $scope.DoorForm.Model + ' ' + color1 + color2 + $scope.DoorForm.Stamp + ' ' + Sectionsearch;
          break;
        }
        $ionicLoading.show({
          template: templateLoading
        });
        Orderstatuses.getProducttoByname(name).success(function(data) {
          if (data.status == false) {
            $cordovaToast.showLongCenter(data.msg);
          } else {
            $ionicLoading.hide();
            if ($scope.actionDoor == 'search') {
              $scope.actionDoor = 'measurements';
            // openPopup('#popupNewDoor');
          }
          if (data.name != undefined) {
            $scope.buttonSubmit = "Back";
            var notify = 'Searched item: ' + data.name;
            $scope.product_idInsert = data.id;
            var myPopup = $ionicPopup.show({
              template: notify,
              title: 'Alert',
              buttons: [{
                text: '<b>Add Item</b>',
                onTap: function(e) {
                  $scope.DoorFormAddProduct();
                }
              }, {
                text: '<b>Back</b>',
                onTap: function(e) {
                  $scope.buttonSubmit = "Check Item";
                  myPopup.close();
                }
              }]
            });
          } else {
            var myPopup = $ionicPopup.show({
              template: 'There are no products match your selected options.',
              title: 'Alert',
              buttons: [{
                text: '<b>Back</b>',
                onTap: function(e) {
                  myPopup.close();
                }
              }, {
                text: '<b>Cancel</b>',
                onTap: function(e) {
                  myPopup.close();
                  $scope.closeTarget('#popupOrderEstimateMeasurements');
                  $scope.closeTarget('#popupOrderEstimateDoorFormProductTable');
                }
              }]
            });
          }
        }
      });
      } else {
        $ionicLoading.show({
          template: templateLoading
        });
        Products.getDataProduct($scope.product_idInsert, 'estimate').success(function(res) {
          $ionicLoading.hide();
          var data = res.pricebook;
          $scope.show_estimate_Color2 = false;
          if ($scope.DoorForm.Question1 == 'Door' || $scope.DoorForm.Radius != $scope.RadiusEdit) {
            if ($scope.Measurements.can_op_go_up_action == '0') {
              $scope.Measurements.can_op_go_up = '';
            }
            $scope.Measurements.opHangerInches = $scope.dataInch.opHangerInches;
            $scope.Measurements.headerBracketInches = $scope.dataInch.headerBracketInches;
            $scope.Measurements.Radius = $scope.DoorForm.Radius;
           $scope.Measurements.cornerstyle_id  = $scope.DoorForm.cornerstyle_id;
            _.each($scope.DoorForm, function(item, key) {
              return $scope.Measurements[key] = item;
            });
            let indexMea = _.findIndex($scope.arrMeasurements, function(pro){
              return pro.id == data[0].id;
            });
            if(indexMea==-1){
              $scope.arrMeasurements.push({ id: data[0].id, data: $scope.Measurements });
            }else{
              $scope.arrMeasurements[indexMea] = { id: data[0].id, data: $scope.Measurements };
            }
           
          // data[0].Measurements = $scope.Measurements;
        }
        $scope.searchResult = [];
        let index = _.findIndex($scope.listDataProducts, function(pro){
          return pro.id == data[0].id;
        });
        if (index==-1) {
            $scope.listDataProducts.push(data[0]);
        }else{
            $scope.listDataProducts[index] = data[0];
        }
        if ($scope.initialPricebookForSearch.indexOf(data[0].id) < 0) {
          $scope.initialPricebookForSearch = $scope.initialPricebookForSearch.concat([data[0].id]);
        }
        // $scope.openAutocomplete('ion-autocomplete-estimate');
        $scope.openAutocompleteEstimate();
        // $scope.dataInsertProducts.push(data[0]);
        // $scope.initialPricebookForSearch = $scope.dataInsertProducts;
        // var union = arrayUnion($scope.pricebookdata, data, function(item1, item2) {
        //     return item1.id == item2.id;
        // });
        //$scope.setPriceEstimate(union, $scope.Service);
        // $('#buttons1').show();
        // $('#buttons2').hide();
        // $('#buttons3').hide();
        // $('#DoorFormProduct').show();
        // $('#notifyDoorForm').hide();
        $scope.closeTarget('#popupOrderEstimateMeasurements');
        $scope.closeTarget('#popupOrderEstimateDoorFormProductTable');
        $scope.buttonSubmit = "Check Item";

        if (data[0]&&parseInt(data[0].message_status) > 0) {
              $scope.openProductMessage = true;
              $scope.productMessage =data[0].message;
            } else {
              $scope.openProductMessage = false;
              $scope.productMessage = '';
            }
            if ($scope.openProductMessage) {
              var myClass = $('#autocomplete-estimate').attr("class");
              autocompleteClass = (myClass.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
              $('.' + autocompleteClass).css('display', 'none');
              $scope.openByGetTemplate('orderPopupProductMessage');
            }
        
      });
      }
    }
    $scope.MeasurementsAddProduct = function() {
      if ($scope.dataInch.headerBracketInches && ($scope.dataInch.headerBracketInches % 0.25) != 0) {
        $cordovaToast.showLongTop('Please inter a valid bracket inches value!');
        return;
      }
      if ($scope.dataInch.opHangerInches && ($scope.dataInch.opHangerInches % 0.25) != 0) {
        $cordovaToast.showLongTop('Please inter a hanger inches valid value!');
        return;
      }
      $scope.actionDoor = 'search';
      $scope.DoorFormAddProduct();
    }
    $scope.MeasurementsEditDoor = function() {
      if (($scope.dataInch.headerBracketInches % 0.25) != 0) {
        $cordovaToast.showLongTop('Please inter a valid bracket inches value!');
        return;
      }
      if (($scope.dataInch.opHangerInches % 0.25) != 0) {
        $cordovaToast.showLongTop('Please inter a hanger inches valid value!');
        return;
      }
      $ionicLoading.show({
        template: templateLoading
      });
      if ($scope.DoorForm.Radius == $scope.RadiusEdit) {
        $scope.Measurements.headerBracketInches = parseFloat($scope.dataInch.headerBracketInches);
        $scope.Measurements.opHangerInches = parseFloat($scope.dataInch.opHangerInches);
        $scope.Measurements.Radius = $scope.DoorForm.Radius;
        _.each($scope.DoorForm, function(item, key) {
          return $scope.Measurements[key] = item;
        });
        Orderstatuses.saveMeasurements($scope.estimate_insertGetId, $scope.product_idEdit, $scope.Measurements).success(function(data) {
          $ionicLoading.hide();
          $scope.closeTarget('#popupOrderEstimateMeasurements');
          $scope.closeTarget('#popupOrderEstimateDoorFormProductTable');
          for (var i = 0; i < $scope.pricebookdata.length; i++) {
            if ($scope.pricebookdata[i].id == $scope.product_idEdit) {
              if ($scope.Measurements.can_op_go_up_action == '0') {
                $scope.Measurements.can_op_go_up = '';
              }
              $scope.pricebookdata[i].Measurements = $scope.Measurements;
            }
          }
          if (data.status) {
            $cordovaToast.showLongTop(data.msg);
          //$scope.getEstimateData();
        } else {
          $cordovaToast.showLongTop('Save Successful!');
        }
      });
      } else {
        Orderstatuses.getProducttoByname($scope.NameDoor[0] + $scope.DoorForm.Radius).success(function(data) {
          if (data.status == false) {
            $cordovaToast.showLongCenter(data.msg);
          } else {
            $ionicLoading.hide();
            if (data.name != undefined) {
              $scope.buttonSubmit = "Back";
              var notify = 'Searched item: ' + data.name;
              $scope.product_idInsert = data.id;
              var myPopup = $ionicPopup.show({
                template: notify,
                title: 'Alert',
                buttons: [{
                  text: '<b>Add Item</b>',
                  onTap: function(e) {
                    $scope.DoorFormAddProduct();
                  }
                }, {
                  text: '<b>Back</b>',
                  onTap: function(e) {
                    $scope.buttonSubmit = "Check Item";
                    myPopup.close();
                  }
                }]
              });
            } else {
              var myPopup = $ionicPopup.show({
                template: 'There are no products match your selected options.',
                title: 'Alert',
                buttons: [{
                  text: '<b>Back</b>',
                  onTap: function(e) {
                    myPopup.close();
                  }
                }, {
                  text: '<b>Cancel</b>',
                  onTap: function(e) {
                    myPopup.close();
                    $scope.closeTarget('#estimateMeasurementsPage');
                    $scope.closeTarget('#estimateDoorFormProductTables');
                  }
                }]
              });
            }
          }
        });
      }
    }
    $scope.buttonSubmitEditMeasurements = "Save";
    $scope.changeRadius = function() {
      if ($scope.DoorForm.Radius == $scope.RadiusEdit) {
        $scope.buttonSubmitEditMeasurements = "Save";
      } else {
        $scope.buttonSubmitEditMeasurements = "Search";
      }
    }
    $scope.changecan_op_go_up = function() {
      $timeout(function() {
        $scope.$apply(function() {
          if ($scope.Measurements.can_op_go_up_action == '1' || $scope.Measurements.can_op_go_up_action == 1) {
            $scope.Measurements.can_op_go_up_action = 1;
            $('.can_op_go_up').show();
            $('.can_op_go_up').find("input").prop('required', true);
          } else {
            $scope.Measurements.can_op_go_up_action = 0;
            $('.can_op_go_up').hide();
            $('.can_op_go_up').find("input").removeAttr('required');
          }
        })
      }, 100);
    }
    $scope.previousform = function() {
      console.log($scope.RadiusEdit);
      $('#DoorFormAddProduct > .isrequired').find("select").prop('required', true);
      if ($scope.RadiusEdit != '' && $scope.RadiusEdit != undefined) {
        openPopup('#popupMeasurementsedit');
      } else {
        if ($scope.DoorForm.Question1 == 'Door') {
          openPopup('#popupMeasurements');
        }
      }
      $('#DoorFormProduct').show();
      $('#notifyDoorForm').hide();
      $('#buttons1').show();
      $('#buttons2').hide();
      $('#buttons3').hide();
      $scope.buttonSubmit = "Check Item";
    }
    $scope.openpreviousform = function(action) {
      openPopup('#popupInchesTable');
      if (action == 'add') {
        $('#popupInchesTable').parent().parent().find('.close-title-button').unbind("click");
        $('#popupInchesTable').parent().parent().find('.close-title-button').click(function() {
          openPopup('#popupMeasurements');
        });
      } else {
        $('#popupInchesTable').parent().parent().find('.close-title-button').unbind("click");
        $('#popupInchesTable').parent().parent().find('.close-title-button').click(function() {
          openPopup('#popupMeasurementsedit');
        });
      }
    }
    $scope.refreshform = function() {
    //$scope.openByGetTemplate('popupOrderEstimateDoorFormProductTable');
    $scope.RecommendationRadius = '';
    $scope.Measurements = {};
    $scope.Measurements.can_op_go_up_action = 1;
    $scope.DoorForm = {};
    $scope.DoorForm.Hardware = "Standard Hardware";
    $scope.DoorForm.Struts_Windload = "Standard Struts";
    $scope.Constructiondata = {};
    $scope.Height = {};
    $scope.Color_1 = {};
    $scope.Color_2 = {};
    $scope.Stamp = {};
    $scope.Section = {};
    $scope.Radius = {};
  }
  $scope.InchesTable = function(display_height, action) {
    var height;
    switch (display_height) {
      case '80':
      height = 96;
      break;
      case '79':
      height = 93
      break;
      case '76':
      height = 90
      break;
      case '73':
      height = 87
      break;
      case '70':
      height = 84
      break;
      case '69':
      height = 81
      break;
      case '66':
      height = 78
      break;
      case '63':
      height = 75
      break;
      case '60':
      height = 72
      break;
    }
    if ($scope.Measurements.floor_to_ceiling_at_drums != undefined && $scope.Measurements.floor_to_op_rail_18 != undefined && $scope.Measurements.floor_to_op_rail_at_stop_bolt != undefined) {
      var A = $scope.Measurements.floor_to_ceiling_at_drums - height;
      var B = $scope.Measurements.floor_to_op_rail_18 - height;
      var C = $scope.Measurements.floor_to_op_rail_at_stop_bolt - height;
      var D = Math.abs($scope.Measurements.floor_to_ceiling_at_center_plate - height);
      if (A >= 14.5 && B >= 13 && C >= 11 && D >= 14) {
        $scope.RecommendationRadius = 15;
      } else {
        if (A >= 12.5 && B >= 10 && C >= 8 && D < 14 & D >= 12) {
          if ($scope.DoorForm.Construction != 'Classica') {
            $scope.RecommendationRadius = 12;
          } else {
            $scope.RecommendationRadius = 'LHRO';
          }
        } else {
          if (A >= 8.5 && B >= 6 && C >= 5 && D < 12 & D >= 8) {
            $scope.RecommendationRadius = 'LHRO';
          } else {
            $scope.RecommendationRadius = 'Contact Install department';
          }
        }
      }
    } else {
      $scope.RecommendationRadius = '';
    }
  }
  //end New Door
  $scope.deleteDataPricebook = {};
  $scope.deleteConfirmEstimate = function(item) {
    $scope.openByGetTemplate('popupOrderEstimateDetailItemDelete');
    $scope.deleteDataPricebook = item;
    // $scope.deleteOrderstatuses(item, pricebook);
  }
  $scope.setValueCornerstylesInput = function (id) {
    $scope.cornerstylesdata.cornerstyles_name = "";
    $scope.cornerstylesdata.cornerstyles_name = $scope.setValueForInput($scope.cornerstyles, id).name;
}
$scope.setValueForInput = function (arrData, id) {
  var result = '';
  var index = _.findLastIndex(arrData, {
      id: id
  });
  if (index >= 0)
      result = arrData[index];
  return result;
}
  $scope.showSelectCornerstyle =function(pairproducts){
    $scope.selectCornerstyles(pairproducts,0)
 }
  $scope.selectCornerstyles = function(products,index) {
   
    $scope.cornerstylesdata.product_id = products[index].id;
    $scope.cornerstylesdata.name = products[index].name;
    $scope.cornerstylesdata.index = index;
    $scope.cornerstylesdata.cornerstyles_id = '';
    $scope.cornerstylesdata.cornerstyles_name = '';
    $scope.cornerstylesdata.products = products;
    if(!products[index]['Measurements']){
      $scope.openByGetTemplate('popupCornerstyles');
    }else{
      $scope.cornerstylesdata.cornerstyles_id = products[index]['Measurements'].cornerstyle_id;
      if($scope.cornerstylesdata.cornerstyles_id!=''){
        $scope.getPairProduct();
      }else{
        $scope.selectCornerstyles(products,index+1);
      }
    }
  }

  $scope.getPairProduct =function(){
    if($scope.cornerstylesdata.cornerstyles_id!=''){
      $ionicLoading.show({ template: templateLoading });
    }else{
      $ionicLoading.hide();
    }
    Products.getPairProduct($scope.cornerstylesdata).success(function(data){
      $ionicLoading.hide();
         if(data.status == true){
           $scope.pricebookdata = $scope.pushPairProductToList($scope.pricebookdata,data.pricebook_pair)
             $scope.closeTarget('#popupCornerstyles');
             $scope.closePopupCornerstyles();
         }else{
            $scope.closePopupCornerstyles();
            $cordovaToast.showLongTop(data.msg);
         }
        
    });
  }

  $scope.closePopupCornerstyles = function(){
    $scope.closeTarget('#popupCornerstyles');
    if($scope.cornerstylesdata.index < $scope.cornerstylesdata.products.length-1){
      $scope.selectCornerstyles($scope.cornerstylesdata.products,$scope.cornerstylesdata.index + 1)
    } else{
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    }
  }

  $scope.pushPairProductToList = function(list_product,list_pair_product) {
    _.each(list_pair_product, function($item, $index) {
        var check_exist_product = _.where(list_product, {
            id: $item.id
        });
        if(check_exist_product.length > 0){
            var index = _.indexOf(list_product,check_exist_product[0]);
            if(index > -1){
                if($item.quantity > list_product[index].quantity){
                    list_product[index].quantity = $item.quantity;
                    
                }
                list_product[index].declined = $item.declined;
            }
        }else{
            list_product.push($item);
        }
    });
    return list_product;
}

  $scope.deleteOrderstatuses = function(item, pricebook) {
    var idx = _.findLastIndex($scope.pricebookdata, { id: item.id });
    $scope.pricebookdata.splice(idx, 1);
    // var data = [];
    // data[0] = $scope.pricebookdata[idx];
    // var diff = differentArray(pricebook, data);
    // $scope.itemPB = {};
    // $scope.itemPB['id'] = item.id;
    // $scope.itemPB['name'] = item.name;
    // $scope.searchData.pricebookdt = differentArray($scope.searchData.pricebookdt, [$scope.itemPB]);
    // $scope.pricebookdata = diff;
    // setTimeout(function() {
    //     $scope.$apply(function(val) {
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    //     });
    // }, 1);
    $scope.resizeScroll('scrollEstimateDetail');
    $scope.closeTarget('#popupOrderEstimateDetailItemDelete');
    // $cordovaToast.showLongTop('Delete Successful!');
  }
  $scope.dataChangePassword = {};
  $scope.loaddata = 0;
  $scope.getUserLogin = function() {
    return Login.getUserLogin().success(function(data) {
      //current_ext = data.extension_phone;
      //$scope.dataChangePassword.emailShow = data.email;
      $scope.ischange_password = data.ischange_password;
      $scope.pushChatRoom = data.pushchatroom;
      if (data == false) {
        localStorage.setItem("login_status", "0");
        redirectTo('index.html');
      } else {
        var index = _.findIndex(data.jsondata, { roletree_id: '96' });
        if (!data.jsondata[index].child[0].check) {
          $cordovaToast.showLongCenter('No permission !!!');
          localStorage.setItem("login_status", "0");
          redirectTo('index.html');
        }
        $scope.addItem = data.jsondata[index].child[0].child[0].check;
        $scope.removeItemNoInstalled = data.jsondata[index].child[0].child[1].check;
        $scope.showInstallDeclined = data.jsondata[index].child[0].child[2].check;
        $scope.addEditComment = data.jsondata[index].child[0].child[3].check;
        $scope.showNewDoorForm = data.jsondata[index].child[0].child[4].check;
        $scope.templateData.showNewDoorForm = $scope.showNewDoorForm;

        $scope.showSentTo = data.jsondata[index].child[0].child[5].check;
        if ($scope.showSentTo) {
          $scope.showGeneratePdf = data.jsondata[index].child[0].child[5].child[0].check;
          $scope.showLow_DPI_Pdf = data.jsondata[index].child[0].child[5].child[1].check;
          $scope.showSendEmail = data.jsondata[index].child[0].child[5].child[2].check;
        } else {
          $scope.showGeneratePdf = false;
          $scope.showLow_DPI_Pdf = false;
          $scope.showSendEmail = false;
        }
        $scope.changeCouponDropDown = data.jsondata[index].child[0].child[6].check;
        $scope.showConvertToInvoice = data.jsondata[index].child[0].child[7].check;
        $scope.showSaveAndCreateEstimate = data.jsondata[index].child[0].child[8].check;
        $scope.showTransferItems = data.jsondata[index].child[0].child[9].check;

        $scope.imagePath = pathToPublic + data.image_pic;
        var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
        if ($.trim(displayname) == "") {
          $scope.displayname = "Hello, " + data.email;
        } else {
          $scope.displayname = "Hello, " + displayname;
        }
        if ($scope.loaddata == 0) {
          if ($scope.getestimate_id.length > 0 && $scope.getestimate_id != '') {
            $scope.estimate_insertGetId = $scope.getestimate_id;
            $scope.check_Appointment_customer();
            setTimeout(function() {
              $scope.getEstimateData(false);
            }, 100);
          } else {
            $scope.estimate_insertGetId = '';
            setTimeout(function() {
              $scope.$apply(function(val) {
                $scope.getTypeOfService();
                // $scope.replaceRes();
              });
            }, 10);
            // if (parameter == false) {
            //     $scope.appointment_id = 0;
            // }
            $scope.check_Appointment_customer();
            $scope.getEstimateNumber();
          }
          // $('#documents').show();
        }
        //$scope.selectService($scope.Service, $scope.OptionService);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  // $scope.getUserLogin();
  $scope.logout = function() {
    return Login.logout().success(function(data) {
      $window.location.href = url_login;
    });
  }
  $scope.checkLogin = function() {
    return Login.checkLogin().success(function(data) {
      if (data.status == false) {
        $window.location.href = url_login;
      } else {
        //$scope.getUserLogin();
        if ($scope.getestimate_id.length > 0 && $scope.getestimate_id != '') {
          $scope.estimate_insertGetId = $scope.getestimate_id;
          $scope.check_Appointment_customer();
          setTimeout(function() {
            $scope.getEstimateData(false);
          }, 100);
        } else {
          $scope.estimate_insertGetId = '';
          setTimeout(function() {
            $scope.$apply(function(val) {
              $scope.getTypeOfService();
              $scope.replaceRes();
            });
          }, 10);
          // if (parameter == false) {
          //     $scope.appointment_id = 0;
          // }
          $scope.check_Appointment_customer();
          $scope.getEstimateNumber();
        }
        $scope.selectService($scope.Service, $scope.OptionService);
      }
    });
  }
  // edit by haudao
  $scope.setValueServiceLocation = function(id, type) {
    $scope.Input_value.serviceLocation = "Service Address";
    if ($scope.jobsitedata.length > 0) {
      var index = _.findLastIndex($scope.jobsitedata, {
        id: id
      });
      if (index >= 0) $scope.Input_value.serviceLocation = $scope.jobsitedata[index].service_location;
      if (type == 'changeInput') {
        $scope.changeServiceLocation(id);
        $scope.closeTarget('#popupOrderEstimateDetailServiceLocation');
      }
      $scope.disableApply = false;
    } else {
      // $scope.Input_value.serviceLocation = $scope.dataInfoCustomer.street + ', ' + $scope.dataInfoCustomer.city + ', ' + $scope.dataInfoCustomer.state + ', ' + $scope.dataInfoCustomer.zipcode;
      $scope.disableApply = true;
    }
  }
  $scope.changeServiceLocation = function(id) {
    if (parseInt($scope.estimate_insertGetId) > 0) {
      Orderstatuses.changeServiceLocation(id, $scope.getestimate_id).success(function(data) {
        $scope.setValueServiceLocation(id, '');
      });
    }
  }
  $scope.styleOfMeasurement = "Add";
  $scope.$on('estimateDetail', function(event, args) {
    $scope.arrMeasurements = [];
    $scope.getestimate_id = args.estimate_id;
    $scope.customer_id = args.customer_id;
    $scope.appointment_id = args.appointment_id;
    $scope.redirectFromAppointment = args.redirectFromAppointment;
    $scope.allAppointmentHistoryData.length = args.countAppHistories;
    $scope.changeInfoTemplate();
    $scope.getUserLogin();
  });
  $scope.$on('newEstimate', function(event, args) {
    $scope.openByGetTemplate('popupOrderEstimateDetail');
    $ionicLoading.hide();
    $scope.getestimate_id = '';
    $scope.Input_value.serviceLocation = 'Billing Address';
    $scope.customer_id = args.customer_id;
    $scope.jobsitedata = args.jobsite;
    $scope.appointment_id = args.appointment_id;
    $scope.Jobsite_id = '';
    $scope.pricebookdata = [{ name: '', Product_Class_name: '', id: '', warranty_name: '', quantity: '', price: '', warranty_id: '', Extended: '', Extended_Price: '', declined: '', Wholesale: '', Commercial: '', Contractor: '', Retail: '', Walk_In: '', Customer_Aquisition: '' }];
    $scope.comment.value = '';
    $scope.searchData = {};
    $scope.searchData.data = [];
    $scope.searchData.pricebookdt = [];
    $scope.Service = '0';
    $scope.OptionService = '5';
    $scope.Installer_date = '';
    $scope.Installer = '';
    $scope.Input_value.service = $scope.setValueInput($scope.Service, $scope.typeOfService);
    $scope.Input_value.optionService = $scope.setValueInput($scope.OptionService, $scope.optionOfService);
    $scope.getUserLogin();
    $scope.change_coupon('');
  });
  $scope.addEstEmail = function() {
    $scope.AdvancedEmail.emails.push({ text: '' });
  }
  $scope.removeEstEmail = function(idx) {
    if ($scope.AdvancedEmail.emails.length > 1)
      $scope.AdvancedEmail.emails.splice(idx, 1);
    $scope.dataInsertProducts = [];
  }
  $scope.estimeAutocompleteList = {};
  $scope.newquery = '';
  // $scope.itembutton = [{type:'button',name:'save'}];
  $scope.isprogress = false;
  $scope.filterAutocomplete = function(query, isInitializing, type) {
    var listProductId = _.pluck($scope.pricebookdata, 'id');
    $('#autocomplete-estimate .none-result').css('display', 'none');
    switch (type) {
      case 'estPro':
      var returnValue = { items: [] };
      var returnData = [];
      var params = { search: query, from: 'app' };
      if (query != '') {
        if ($scope.newquery != query && !$scope.isprogress) {
          $scope.isprogress = true;
          $scope.coundown = 10;
          if ($scope.myTime != null)
            clearInterval($scope.myTime);
          $scope.myTime = setInterval(function() {
            $scope.coundown--;
            if ($scope.coundown <= 0) {
              clearInterval($scope.myTime);
              $ionicLoading.show({ template: templateLoading });
              Products.getSelect2(params, "Entire Pricebook").success(function(data) {
                $scope.isprogress = false;
                if (data.length > 0) {
                  $scope.newquery = query;
                  data = _.sortBy(data, 'name');
                  var diff = differentArray(data, $scope.searchData.pricebookdt);
                  $scope.listDataProductsNew = diff;
                  returnData = diff;
                  returnData.forEach(function(item) {
                    item.type = 'item';
                    var indexItem = _.findIndex($scope.dataInsertProducts, item);
                    if (indexItem < 0 && listProductId.indexOf(item.id.toString()) < 0) {
                      returnValue.items.push(item);
                        // if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        //     returnValue.items.push(item);
                        // } else if (item.part.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                        //     returnValue.items.push(item);
                        // }
                      }
                    });
                }
                $ionicLoading.hide();
                if (returnValue.items.length > 0) {
                  $('#autocomplete-estimate .none-result').css('display', 'none');
                } else {
                  $('#autocomplete-estimate .none-result').css('display', 'block');
                }
              });
            }
          }, 100);
        } else {
          $scope.isprogress = false;
          returnData = $scope.listDataProductsNew;
          returnData.forEach(function(item) {
            item.type = 'item';
            var indexItem = _.findIndex($scope.dataInsertProducts, item);
            if (indexItem < 0 && listProductId.indexOf(item.id.toString()) < 0) {
              if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
              } else if (item.part.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                returnValue.items.push(item);
              }
            }
          });
          if (returnValue.items.length > 0) {
            $('#autocomplete-estimate .none-result').css('display', 'none');
          } else {
            $('#autocomplete-estimate .none-result').css('display', 'block');
          }
        }
      } else {
        returnData = $scope.listDataProducts;
        returnData.forEach(function(item) {
          item.type = 'item';
          var indexItem = _.findIndex($scope.dataInsertProducts, item);
          if (indexItem < 0 && listProductId.indexOf(item.id.toString()) < 0) {
            if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
              returnValue.items.push(item);
            } else if (item.part.toLowerCase().indexOf(query.toLowerCase()) > -1) {
              returnValue.items.push(item);
            }
          }
        });
        if (returnValue.items.length > 0) {
          $('#autocomplete-estimate .none-result').css('display', 'none');
        } else {
          $('#autocomplete-estimate .none-result').css('display', 'block');
        }
      }

      var itembutton = [{ type: 'button', name: 'save' }, { type: 'button', name: 'open' }];
      itembutton.forEach(function(item) {
        var index = _.findIndex(returnValue.items, item);
        if (index < 0) {
          returnValue.items.push(item);
        }
      });

      return returnValue;
      break;
      case 'sendFrom':
      var returnValue = { items: [] };
      var id = $scope.estimeAutocompleteList.sendform;
      $scope.allUser.forEach(function(item) {
        if (id != item.id) {
          if (item.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            returnValue.items.push(item);
          } else if (item.id.toString().indexOf(query) > -1) {
            returnValue.items.push(item);
          }
        }
      });
      return returnValue;
      break;
    }
  }

  $scope.getListProducts = function(params) {
    $ionicLoading.show({ template: templateLoading });
    Products.getSelect2(params, "Entire Pricebook").success(function(data) {
      data = _.sortBy(data, 'name');
      $ionicLoading.hide();
      $scope.listDataProducts = data;
    });
  }
  $scope.cancelButtonClickedMethod = function(callback) {
    $scope.initialPricebookForSearch = [];
  }
  $scope.addProductToEstimate = function() {
    var listID = [];
    for (var i = 0; i < $scope.dataInsertProducts.length; i++) {
      listID.push($scope.dataInsertProducts[i].id);
    }
    if (listID.length > 0) {
      $scope.insertItemPricebook(listID);
    }
    $scope.dataInsertProducts = [];
    //$scope.initialPricebookForSearch = [];
  }

  $scope.dataInsertProducts = [];
  $scope.onSelectAutocomplete = function(callback, type) {
    switch (type) {
      case 'estPro':
      if (callback.item != undefined) {
        $scope.searchData.data = callback.item;
        if (callback.item.type == 'item') {
          if (_.where($scope.listDataProducts, { id: callback.item.id }).length == 0) {
            $scope.listDataProducts.push(callback.item);
          }
          if ($scope.initialPricebookForSearch.indexOf(callback.item.id) < 0) {
            $scope.initialPricebookForSearch = $scope.initialPricebookForSearch.concat([callback.item.id]);
            if (parseInt(callback.item.message_status) > 0) {
              $scope.openProductMessage = true;
              $scope.productMessage = callback.item.message;
            } else {
              $scope.openProductMessage = false;
              $scope.productMessage = '';
            }
            if ($scope.openProductMessage) {
              var myClass = $('#autocomplete-estimate').attr("class");
              autocompleteClass = (myClass.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
              $('.' + autocompleteClass).css('display', 'none');
              $scope.openByGetTemplate('orderPopupProductMessage');
            }
          }
          $scope.calculatorPrice(callback.selectedItems);
        }
        $scope.dataInsertProducts = _.reject(callback.selectedItems, function(item) {
          return item.type == 'button';
        });
        if (callback.item.type == 'button' && callback.item.name == 'save') {
          return $scope.addProductToEstimate();
        }
        if (callback.item.type == 'button' && callback.item.name == 'open') {
          return;
        }
      }
      break;
      case 'sendFrom':
      $scope.AdvancedEmail.SendFrom = callback.item;
      return;
      break;
    }
  }

  $scope.calculatorPrice = function(items) {
    switch (parseInt($scope.OptionService)) {
      case 1:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Wholesale * num.defaultinvoicequantity); }, 0);
      break;
      case 2:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Commercial * num.defaultinvoicequantity); }, 0);
      break;
      case 4:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Contractor * num.defaultinvoicequantity); }, 0);
      break;
      case 5:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Retail * num.defaultinvoicequantity); }, 0);
      break;
      case 6:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Walk_In * num.defaultinvoicequantity); }, 0);
      break;
      case 7:
      var sum = _.reduce(items, function(memo, num) { return memo + parseFloat(num.Customer_Aquisition * num.defaultinvoicequantity); }, 0);
      break;
    }
    $scope.templateData.subtotal = (parseFloat($scope.total) + parseFloat(sum)).toFixed(2);
  }

  $scope.onRemoveAutocomplete = function(callback, type) {
    switch (type) {
      case 'estPro':
      var index = $scope.initialPricebookForSearch.indexOf(callback.item.id);
      $scope.initialPricebookForSearch.splice(index, 1);
      $scope.searchData.data = [];
      $scope.dataInsertProducts = _.reject(callback.selectedItems, function(item) {
        return item.id == callback.item.id;
      });
      $scope.calculatorPrice(callback.selectedItems);
      break;
      case 'sendFrom':
      $scope.AdvancedEmail.SendFrom = [];
      break;
    }
  }
  $scope.modelAutocomplete = function(modelValue, type) {
    switch (type) {
      case 'estPro':
      if ($scope.initialPricebookForSearch.length > 0) {
        for (var i = 0; i < $scope.listDataProducts.length; i++) {
          if ($scope.listDataProducts[i].id == modelValue) {
            return $scope.listDataProducts[i];
          }
        }
        return {};
      } else {
        if (modelValue.type == 'item')
          return modelValue;
      }
      break;
      case 'sendFrom':
      for (var i = 0; i < $scope.allUser.length; i++) {
        if ($scope.allUser[i].id == modelValue) {
          return $scope.allUser[i];
        }
        return {};
      };
      break;
      default:
      return;
      break;
    }
  }
  $scope.editEstimate = function(product_id, index) {
    //$scope.openByGetTemplate('popupOrderEstimateDetailItemEdit');
    $scope.estimateDataEdit = {
      product_id: product_id,
      index: index,
      name: $scope.pricebookdata[index].name,
      quantity: $scope.pricebookdata[index].quantity,
      Extended: $scope.pricebookdata[index].Extended,
      declined: $scope.pricebookdata[index].declined,
      Warranty: {
        id: $scope.pricebookdata[index].warranty_id.toString(),
        name: $scope.pricebookdata[index].warranty_name
      }
    };
    $scope.updatePricebook($scope.estimateDataEdit);
  }
  $scope.updatePricebook = function(data) {
    ///closeTarget('#popupOrderEstimateDetailItemEdit');
    $scope.pricebookdata[data.index].Extended = data.Extended;
    $scope.pricebookdata[data.index].declined = data.declined;
    $scope.pricebookdata[data.index].quantity = data.quantity;
    $scope.pricebookdata[data.index].warranty_id = data.Warranty.id;
    $scope.pricebookdata[data.index].warranty_name = data.Warranty.name;
    $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
  }
  $scope.checkRedirectApp = function() {
    if (parseInt($scope.appID) > 0) {
      $scope.appointment_id = $scope.appID;
    }
    if ($scope.redirectFromAppointment && parseInt($scope.appointment_id) > 0) {
      if ($scope.orgPage == 'schedules') {
        if ($scope.roleName == $scope.isFieldinstaller || $scope.roleName == $scope.isSalesman) {
          redirectTo('myschedule.html?appointment_id=' + $scope.appointment_id + '&org_page=schedules');
        } else {
          redirectTo('scheduleapp.html?appointment_id=' + $scope.appointment_id + '&org_page=schedules');
        }
      }
      if ($scope.orgPage == 'myschedule') {
        if ($scope.roleName == $scope.isFieldinstaller || $scope.roleName == $scope.isSalesman) {
          redirectTo('myschedule.html?appointment_id=' + $scope.appointment_id);
        } else {
          redirectTo('scheduleapp.html?appointment_id=' + $scope.appointment_id);
        }
      }
    }
  }

  $scope.updateMD_Coupon = function(MDValue, couponName) {
    if (couponName != undefined && couponName.length > 0) {
      var findCoupon = _.findWhere($scope.coupon, { name: couponName });
      $scope.change_coupon(findCoupon.id);
    }
    if (MDValue != undefined) {
      angular.forEach($scope.pricebookdata, function(item) {
        item.Extended = parseFloat(MDValue);
      })
      $scope.setPriceEstimate($scope.pricebookdata, $scope.Service);
    }
    $cordovaToast.showLongTop('Changes are applied to estimate. Please SAVE estimate.');
    $scope.closeTarget('#popupOrderEstimateDetailDiscountCoupon');
  }

  $scope.linkToEstimateInvoiceDetail = function(item) {
    if ($scope.estimate_no != item.invoice_no) {
      switch (item.ordertype_id) {
        case '4':
        $scope.closeTarget('#popupOrderEstimateDetailEstimateInvoice');
        $scope.closeTarget('#popupOrderEstimateDetail');
        setTimeout(function() {
          $scope.goToEstimateDetails(item.id, item.invoice_no);
        }, 200);
        break;
        case '5':
        $scope.closeTarget('#popupOrderEstimateDetailEstimateInvoice');
        $scope.closeTarget('#popupOrderEstimateDetail');
        setTimeout(function() {
          $scope.setTabOrder('Invoice');
          $scope.goToInvoiceDetails(item.id, item.invoice_no);
        }, 200);
        break;
      }
    }
  }

  $scope.changeIputValue = function(action, id) {
    switch (action) {
      case 'servicelocation':
      $scope.Input_value.servicelocation = $scope.setValueServiceLocation(id, $scope.jobsitedata);
      break;
      case 'service':
      $scope.Input_value.service = $scope.setValueInput(id, $scope.typeOfService);
      $scope.Service = id;
      break;
      case 'typeofservice':
      $scope.Input_value.optionService = $scope.setValueInput(id, $scope.optionOfService);
      $scope.OptionService = id;
      break;
      case 'change_coupon':
      $scope.dataInsert.coupon_id = id;
      $scope.Input_value.couponData = $scope.setValueInput(id, $scope.coupon);
      break;
    }
  }

  $scope.closeAutoComplete = function() {
    $('.ion-autocomplete-container').css("display", "none");
    //showTarget('#popupOrderEstimateDoorFormProductTable');
  }

  $scope.clearDataAndOpenAutoComplete = function() {
    $scope.initialPricebookForSearch = [];
    $scope.Measurements = {};
    $scope.DoorForm = {};
    $scope.Input_value = {};
    $scope.Measurements.can_op_go_up_action = 1;
    // $scope.openAutocomplete('ion-autocomplete-estimate');
    $scope.openAutocompleteEstimate();
  }

  $scope.changeCornerstyles = function() {
    if (parseInt($scope.Measurements.cornerstyle_id) > 0) {
      $scope.cornerstyle_label = _.where($scope.cornerstyles, { id: $scope.Measurements.cornerstyle_id })[0].name;
      $scope.DoorForm.cornerstyle_id = $scope.Measurements.cornerstyle_id;
    } else {
      $scope.cornerstyle_label = '';
      $scope.DoorForm.cornerstyle_id ='';
    }
  }

  $scope.closeFormReopenAutocomplete = function() {
    $scope.closeTarget('#orderPopupProductMessage');
    $scope.openAutocompleteEstimate();
  }

  $scope.declinedAll = function(value) {
    _.each($scope.pricebookdataOnSelectAll, function(item) {
      item.declined = value
    });
  }

  $scope.selectDeclined = function() {
    var declined_length = _.where($scope.pricebookdataOnSelectAll, { declined: 1 }).length;
    if (declined_length == $scope.pricebookdataOnSelectAll.length) {
      $scope.checkbox.isDeclinedAll = 1;
    } else {
      $scope.checkbox.isDeclinedAll = 0;
    }
  }

  $scope.appplySelectAllEstimate = function() {
    _.each($scope.pricebookdataOnSelectAll, function(item_form) {
      _.each($scope.pricebookdata, function(item_root) {
        if (parseInt(item_form.id) == parseInt(item_root.id)) {
          item_root.declined = item_form.declined;
        }
      });
    });
    $scope.change_price();
    $scope.closeTarget('#popupSelectAllItemEstimate');
    $scope.option_save_estimate('saveEstimate')
  }

  $scope.setDataForFormEditMeasurements = function(data) {
    $scope.Measurements_temp = data;
    $scope.$apply(function(val) {
      $scope.Measurements.item_id = parseInt($scope.Measurements_temp.item_id);
      $scope.Measurements.can_op_go_up_action = $scope.Measurements_temp.can_op_go_up_action;
      if (parseInt($scope.Measurements_temp.can_op_go_up_action) > 0) {
        $scope.Measurements.can_op_go_up_action = 1;
        $scope.Measurements.can_op_go_up = $scope.Measurements_temp.can_op_go_up;
        $scope.dataInch.headerBracketInches = parseFloat($scope.Measurements_temp.headerBracketInches);
        $scope.dataInch.opHangerInches = parseFloat($scope.Measurements_temp.opHangerInches);
      } else {
        $scope.Measurements.can_op_go_up = '';
        $scope.Measurements.can_op_go_up_action = 0;
        $scope.dataInch.headerBracketInches = '';
        $scope.dataInch.opHangerInches = '';
      }
      $scope.Measurements.floor_to_ceiling_at_center_plate = parseFloat($scope.Measurements_temp.floor_to_ceiling_at_center_plate);
      $scope.Measurements.floor_to_ceiling_at_drums = parseFloat($scope.Measurements_temp.floor_to_ceiling_at_drums);
      $scope.Measurements.floor_to_hor_at_backhanger = parseFloat($scope.Measurements_temp.floor_to_hor_at_backhanger);
      $scope.Measurements.floor_to_hor_at_radius = parseFloat($scope.Measurements_temp.floor_to_hor_at_radius);
      $scope.Measurements.floor_to_op_rail_18 = parseFloat($scope.Measurements_temp.floor_to_op_rail_18);
      $scope.Measurements.floor_to_op_rail_at_stop_bolt = parseFloat($scope.Measurements_temp.floor_to_op_rail_at_stop_bolt);
      $scope.Measurements.headerBracketInches = parseFloat($scope.Measurements_temp.headerBracketInches);
      $scope.Measurements.opHangerInches = parseFloat($scope.Measurements_temp.opHangerInches);
      $scope.Measurements.opening_height_left = parseFloat($scope.Measurements_temp.opening_height_left);
      $scope.Measurements.opening_height_middle = parseFloat($scope.Measurements_temp.opening_height_middle);
      $scope.Measurements.opening_height_right = parseFloat($scope.Measurements_temp.opening_height_right);
      $scope.Measurements.opening_width = parseFloat($scope.Measurements_temp.opening_width);
      $scope.Measurements.cornerstyle_id = $scope.Measurements_temp.cornerstyle_id;
      $scope.cornerstyle_label = _.where($scope.cornerstyles, { id: $scope.Measurements.cornerstyle_id })[0].name;
      $scope.DoorForm.cornerstyle_id =  $scope.Measurements.cornerstyle_id ;
      $scope.DoorForm.Question1 = $scope.Measurements_temp.Question1;
      $scope.DoorFormProduct('Question1');
      $scope.DoorForm.Model = $scope.Measurements_temp.Model;
      $scope.DoorFormProduct('Model');
      $scope.DoorForm.Construction = $scope.Measurements_temp.Construction;
      $scope.DoorFormProduct('Construction');
      $scope.DoorForm.Width = $scope.Measurements_temp.Width;
      $scope.DoorFormProduct('Width');
      $scope.DoorForm.Height = $scope.Measurements_temp.Height;
      $scope.DoorFormProduct('Height');
      $scope.DoorForm.Color_1 = $scope.Measurements_temp.Color_1;
      $scope.DoorFormProduct('Color_1');
      $scope.DoorForm.Color_2 = $scope.Measurements_temp.Color_2;
      $scope.DoorFormProduct('Color_2');
      $scope.DoorForm.Stamp = $scope.Measurements_temp.Stamp;
      $scope.DoorForm.Section = $scope.Measurements_temp.Section;
      $scope.DoorForm.Hardware = $scope.Measurements_temp.Hardware;
      $scope.DoorForm.Struts_Windload = $scope.Measurements_temp.Struts_Windload;
      $scope.getdataRadius();
      $scope.DoorForm.Radius = $scope.Measurements_temp.Radius;
      $scope.buttonSubmitEditMeasurements = "Save";
    })
  }

  $scope.openAutocompleteEstimate = function() {
    var myClassEstimate = $('#autocomplete-estimate').attr("class");
    var estimateAutocompleteClass = (myClassEstimate.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
    if (estimateAutocompleteClass != undefined) {
      $('.' + estimateAutocompleteClass).css('display', 'block');
    }
    var ionAutocompleteElement = document.getElementsByClassName('ion-autocomplete-estimate');
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').fetchSearchQuery("", true);
    angular.element(ionAutocompleteElement).controller('ionAutocomplete').showModal();
    $timeout(function() {
      angular.element('.backdrop').removeClass('visible').removeClass('active');
    }, 1000);
  }

  $scope.openFormSelectAll = function(type) {
    $scope.pricebookdataOnSelectAll = angular.copy($scope.pricebookdata);
    $scope.selectDeclined();
    $scope.openByGetTemplate('popupSelectAllItemEstimate');
  };

  $scope.open_door_form_product_table = function() {
    $scope.openByGetTemplate('popupOrderEstimateDoorFormProductTable');
  };

  $scope.changeTypeAddApp = function(value) {
    $scope.type_add_app = value;
    $scope.type_add_app_value = _.where($scope.type_add_app_select, { key: value })[0].value;
  }

  $scope.setTypeAddapp = function(type_value) {
    $scope.closeTarget('#popupConvertToSaleOrder');
    if (type_value == '3') {
      $scope.option_save_estimate('Convert_Est_to_Sale_Order');
    } else {
      $scope.dataAddAppointment = {};
      $scope.dataAddAppointment.order_id = $scope.getestimate_id;
      $scope.openByGetTemplate('popupAddApp');
      $scope.refreshAppointmentType();
    }
  }

  $scope.getSelectFieldworker = function() {
    Users.getSelectFieldworker().success(function(data) {
      $scope.fieldworkerSelect = data;
      $scope.getCallaheads();
    });
  }
  $scope.getCallaheads = function() {
    Callaheads.getSelect().success(function(data) {
      $scope.callaheads = data;
      $scope.getFlexiblecustomers();
    });
  }
  $scope.getFlexiblecustomers = function() {
    Flexiblecustomers.getSelect().success(function(data) {
      $scope.flexiblecustomers = data;
      $scope.dataAddAppointment.flexiblecustomer_id = '3'; //possibly
      var flexiblecustomer = _.findWhere($scope.flexiblecustomers, { id: '3' });
      if (flexiblecustomer) {
        $('input[name=selectedFlexName]').val(flexiblecustomer.name);
      }
      $scope.getAllOrders();
    });
  }

  $scope.getAllOrders = function() {
    var params = {
      search: '',
      customer_id: $scope.customer_id
    };
    $scope.order_idapp = {};
    Orders.getSelect2(params).success(function(data) {
      var diff = differentArray(data);
      var invoiceCreate = _.findWhere(diff, { appointment_id: $scope.app_id });
      if (invoiceCreate) {
        $scope.dataAddAppointment.order_id = invoiceCreate.id;
        $scope.orderData = diff;
      } else if (!invoiceCreate && $scope.order_id != '0') {
        $scope.dataAddAppointment.order_id = $scope.order_id;
        $scope.orderData = diff;
      } else {
        var NAdata = { id: '0', name: 'N/A', };
        diff.unshift(NAdata);
        $scope.orderData = diff;
        $scope.dataAddAppointment.order_id = '0';
      }
      var item = _.findWhere($scope.orderData, { id: $scope.dataAddAppointment.order_id });
      if (item) {
        $('input[name=selectedInvoiceNumber]').val(item.name);
      }
    });
  }
  $scope.refreshAppointmentType = function() {
    var params = {
      search: ''
    };
    $ionicLoading.show({ template: templateLoading });
    Opportunities.getAppointmentType(params).success(function(data) {
      $ionicLoading.hide();
      $scope.AppointmentType = data;
      $scope.getSelectFieldworker();
    });
  }

  $scope.$watch('dataAddAppointment.dateofappt', function(val) {
    if ($scope.type_add_app == '1') {
      var appDate = moment(val).format('MM/DD/YYYY');
      $('#formCreateToSchedule #dateofappt').val(appDate);
    }
  });


  $scope.createToSchedule = function() {
    $ionicLoading.show({ template: templateLoading });
    if ($scope.dataAddAppointment.appointmentgroup_id == null || $scope.dataAddAppointment.appointmentgroup_id == '') {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    $scope.addAppointmentsDataCopy = angular.copy($scope.dataAddAppointment);
    $scope.addAppointmentsDataCopy.customer_id = $scope.customer_id;
    $scope.addAppointmentsDataCopy.customertype_id = $scope.customertype_id;
    if ($scope.type_add_app == '1') {
      $scope.addAppointmentsDataCopy.arrivalwindow = moment($('#arrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
      $scope.addAppointmentsDataCopy.endarrivalwindow = moment($('#endarrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
      $scope.addAppointmentsDataCopy.nothomeutil = moment($('#nothomeutilView').val(), 'hh:mmA').format('HH:mm:ss');
      $scope.addAppointmentsDataCopy.dateofappt = $('#formCreateToSchedule #dateofappt').val();
      $startTimeCheck = moment($scope.addAppointmentsDataCopy.arrivalwindow, 'hh:mmA').format('HH:mm:ss');
      $endTimeCheck = moment($scope.addAppointmentsDataCopy.endarrivalwindow, 'hh:mmA').format('HH:mm:ss');
      if ($startTimeCheck < '06:00:00' || $endTimeCheck > '22:00:00') {
        $ionicLoading.hide();
        $cordovaToast.showLongTop('The appointment cannot be scheduled outside 6AM-10PM');
        return;
      }
      var check = validateTime($scope.addAppointmentsDataCopy.arrivalwindow, $scope.addAppointmentsDataCopy.endarrivalwindow);
      if (!check.status) {
        $ionicLoading.hide();
        $cordovaToast.showLongTop('End time must be greater than start time');
        return;
      }
    }
    $scope.addAppointmentsDataCopy.addby_id = $scope.currentIdLogin;
    $ionicLoading.show({ template: templateLoading });
    Orderstatuses.createToSchedule($scope.addAppointmentsDataCopy).success(function(data) {
      if (data.status) {
        $cordovaToast.showLongTop(data.msg);
        $scope.closeTarget('#popupAddApp');
        $scope.inserted_to_schedule_id = data.appointment_id;
        $scope.option_save_estimate('Convert_Est_to_Sale_Order');
      } else {
        $cordovaToast.showLongTop(data.msg);
        $ionicLoading.hide();
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  }
  $scope.validateFormCreateToSchedule = function(formValidate) {
    var exitLoop = false;
    if (formValidate.$invalid) {
      $cordovaToast.showLongTop('Please fill all the required information.!!!');
      return;
    }
    $scope.createToSchedule();
  }

  $scope.setValueShowSelect = function(getFrom, setTo, type) {
    var valText = $('#' + getFrom + ' option:selected').text();
    var valueData = $('#' + getFrom + ' option:selected').val();
    $('input[name=' + setTo + ']').val(valText);
    switch (type) {
      case 'jobsiteEdit':
      valueData == 'Select' ? valueData = '' : valueData;
      $scope.changeJobsiteEdit(valueData);
      break;
      case 'jobsites':
      valueData == 'Select' ? valueData = '' : valueData
      $scope.changeJobsite(valueData);
      break;
    }
  }

  $scope.checkContractorAndPricing = function() {
    // if(parseInt($scope.Service) == 4){
    //     $scope.openByGetTemplate('popupCheckContractorAndPricing');
    // }else{
    //     $scope.openByGetTemplate('popupConvertToSaleOrder');
    // }
    $scope.openByGetTemplate('popupConvertToSaleOrder');
  }

  $scope.selectStoreLocation =function(value){
    $scope.StoreLocation = value;
  }

  $scope.$on('updateestimatebeforesentmail', function(event, args) {
    $ionicLoading.show({
      template: templateLoading
    });
    $scope.dataInsert.data = $scope.pricebookdata;
    $scope.dataInsert.Subtotal = $scope.Subtotal;
    $scope.dataInsert.Discount = $scope.Discount;
    $scope.dataInsert.user_id = $scope.currentIdLogin;
    if ($scope.estimate_insertGetId == '') {
      $scope.dataInsert.action = 'insertEstimate';
    } else {
      $scope.dataInsert.action = 'updateEstimate';
    }
    $scope.dataInsert.Estimate_id = $scope.estimate_insertGetId;
    $scope.dataInsert.comment = $scope.comment.value;
    $scope.dataInsert.customer_id = $scope.customer_id;
    $scope.dataInsert.appointment_id = $scope.appointment_id;
    $scope.dataInsert.email_sento = $scope.email_sento.value;
    $scope.dataInsert.invoice_id = $scope.invoice_check;
    $scope.dataInsert.estimate_no = $scope.estimate_no;
    $scope.dataInsert.AdvancedEmail = $scope.AdvancedEmail;
    $scope.dataInsert.coupon_value = $scope.couponprice;
    $scope.dataInsert.store_location = $scope.StoreLocation;
    if ($scope.Service > 0) {
      $scope.dataInsert.service_id = $scope.Service;
      $scope.dataInsert.service_option = null;
    } else {
      $scope.dataInsert.service_id = $scope.OptionService;
      $scope.dataInsert.service_option = $scope.Service;
    }
    Orderstatuses.save($scope.dataInsert).success(function(data) {
      $scope.getOrders();
      $ionicLoading.hide();
      if (data.status) {
        $scope.arrMeasurements = [];
        $scope.estimate_insertGetId = data.order_id;
        $scope.getEstimateData(false);
        //if (data.msg) $cordovaToast.showLongTop(data.msg);
        $scope.$emit('estimateinvoiceupdatesuccess', {
          type: args.type,
          order_id: $scope.estimate_insertGetId
        });
      } else {
        if (data.msg) $cordovaToast.showLongTop(data.msg);
      }
    }).error(function(data, status, headers, config) {
      $ionicLoading.hide();
      console.log('error status: ' + status);
      $cordovaToast.showLongTop('Connection Error!!!');
    });
  });
  // end edit

});
