angular.module('invoiceCtrl', []).controller('invoiceController', function($ionicActionSheet, $ionicHistory, $cordovaFile, $cordovaActionSheet, $cordovaCamera, //
    $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, $location, $timeout, $cordovaToast, $ionicLoading, $ionicPopup, //
    $location, $scope, $http, $window, $interval, Login, Products, Ordertypes, Orderstatuses, Customers, $stateParams, Saleorder) {
    withoutPopup = $scope;
    $scope.currentPage = 1;
    $scope.currentIdLogin = currentIdLogin;
    var pager = localStorage.getItem('ordertypes_pagesize');
    $scope.itemsPerPage = pager ? pager : 5;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchOrdertypes = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: ""
    };
    $scope.tier = tier;
    $scope.refund = {};
    $scope.refundValue = {};
    $scope.sendMailType = {};
    $scope.sold_all = {};
    $scope.installed_all = {};
    $scope.declined_all = {};
    $scope.comment = {};
    $scope.comment.value = '';
    $scope.Snail_Mail = {};
    $scope.Snail_Mail.value = '';
    $scope.sold_all.value = 0;
    $scope.installed_all.value = 0;
    $scope.declined_all.value = 0;
    $scope.duedate = {};
    $scope.duedate.value = "";
    $scope.acceptLicense = {};
    $scope.acceptLicense.value = 0;
    $scope.select_MD_All = 0;
    $scope.sendto = 'email';
    $scope.total = 0;
    $scope.check_export_file_pdf = 0;
    $scope.appointment_id = 0;
    $scope.due_date = '';
    $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.checkinsertpaymenthistory = 0;
    $scope.historyDate = '';
    $scope.list_paymenthistory = [];
    $scope.addBraintreesData = {};
    $scope.addBraintree = false;
    $scope.check_init_invoice = false;
    $scope.searchtype = {};
    $scope.dataInch = {};
    $scope.searchtype.value = 'Repair Parts';
    $scope.WellFargoPlan = {};
    $scope.WellFargoPlan.credit_term_plan_number = '1148 | 6 month';
    $scope.monthNames = [{
        name: 'January',
        value: 1
    }, {
        name: 'February',
        value: 2
    }, {
        name: 'March',
        value: 3
    }, {
        name: 'April',
        value: 4
    }, {
        name: 'May',
        value: 5
    }, {
        name: 'June',
        value: 6
    }, {
        name: 'July',
        value: 7
    }, {
        name: 'August',
        value: 8
    }, {
        name: 'September',
        value: 9
    }, {
        name: 'October',
        value: 10
    }, {
        name: 'November',
        value: 11
    }, {
        name: 'December',
        value: 12
    }];
    $scope.cornerstylesdata={cornerstyles_id:'',product_id:0,products:[],index:0,name:""};
    //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.couponData = '';
    $scope.DoorForm.Hardware = "Standard Hardware";
    $scope.DoorForm.Struts_Windload = "Standard Struts";
    $scope.buttonSubmit = "Check Item";
    //end New Door
    $scope.loadJobsite_id = 0;
    $scope.payment_success = [];
    $scope.payment_error = [];
    $scope.checksendBraintree = 0;
    $scope.warrantyData = [];
    $scope.MDValueAllItem = {};
    $scope.notification = 'Your access is invalid, please try again.';
    var vars = [],
        hash;
    $scope.templateData = {
        dataInfoCustomer: {
            first_name: "No",
            last_name: "Name"
        },
        subtotal: 0,
        estimate_no: ""
    };
    $scope.email_sento = {};
    $scope.dataSearchCustomer = {};
    $scope.dataSearchCustomer.customer = [];
    $scope.dataTranferPayment = {};
    $scope.initialPricebookForSearch = [];
    $scope.appID = $stateParams.appID;
    $scope.orgPage = getParameterByName('org_page');
    $scope.arrMeasurements = [];
    $scope.show_invoice_Color2 = false;
    $scope.checkboxSelectAll = {};
    $scope.checkboxSelectAll.isSoldAll = 0;
    $scope.checkboxSelectAll.isInstallAll = 0;
    $scope.checkboxSelectAll.isDeclinedAll = 0;
    $scope.check_invoice = function() {
        $scope.Cash = {};
        $scope.Check = {};
        $scope.CC_Manual = {};
        $scope.Prepaid = {};
        $scope.Payment_Plan = {};
        $scope.Credit_Memo = {};
        $scope.Manager_Credit = {};
        $scope.Instore_Credit = {};
        $scope.Signature = '';
        $scope.checkbox = {};
        $scope.checkbox.Cash_check = 0;
        $scope.checkbox.Wells_Fargo_Plan = 0;
        $scope.checkbox.Check_check = 0;
        $scope.checkbox.CC_Manual_check = 0;
        $scope.checkbox.Prepaid_check = 0;
        $scope.checkbox.Payment_Plan_check = 0;
        $scope.checkbox.Credit_Memo_check = 0;
        $scope.checkbox.Manager_Credit_check = 0;
        $scope.checkbox.Instore_Credit_check = 0;
        $scope.checkbox.use_credit_card_check = 0;
        $scope.checkbox.add_this_card = 0;
        $scope.checkbox.update_this_card = 0;
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.check_invoice($scope.invoice_id).success(function(data) {
            if (data.status) {
                $scope.jobsitedata = data.jobsitedata;
                $scope.usercredentials = data.usercredentials;
                $scope.customerId = data.customer_address.id;
                $scope.email_sento.value = data.customer_email;
                $scope.CC_Manual = data.customer_address;
                $scope.Payment_Plan = angular.copy(data.customer_address);
                $scope.dataInfoCustomer = data.dataCustomer;
                $scope.getInvoice('');
            } else {
                $ionicLoading.hide();
                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.check_saleorder = function() {
        $scope.Cash = {};
        $scope.Check = {};
        $scope.CC_Manual = {};
        $scope.Prepaid = {};
        $scope.Payment_Plan = {};
        $scope.Signature = '';
        $scope.checkbox = {};
        $scope.checkbox.Cash_check = 0;
        $scope.checkbox.Wells_Fargo_Plan = 0;
        $scope.checkbox.Check_check = 0;
        $scope.checkbox.CC_Manual_check = 0;
        $scope.checkbox.Prepaid_check = 0;
        $scope.checkbox.Payment_Plan_check = 0;
        $scope.checkbox.Credit_Memo_check = 0;
        $scope.checkbox.Manager_Credit_check = 0;
        $scope.checkbox.Instore_Credit_check = 0;
        $scope.checkbox.use_credit_card_check = 0;
        $ionicLoading.show({
            template: templateLoading
        });
        Saleorder.check_saleorder($scope.saleorder_id).success(function(data) {
            // $ionicLoading.hide();
            if (data.status) {
                $scope.jobsitedata = data.jobsitedata;
                $scope.usercredentials = data.usercredentials;
                $scope.customerId = data.customer_address.id;
                $scope.email_sento.value = data.customer_email;
                $scope.CC_Manual = data.customer_address;
                $scope.Payment_Plan = angular.copy(data.customer_address);
                $scope.dataInfoCustomer = data.dataCustomer;
                $scope.getSaleorder('');
            } else {
                $ionicLoading.hide();
                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.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.invoice_no;
    }
    $scope.year_select = function() {
        var year = [];
        min = parseInt(new Date().getFullYear()); //Make string input int
        max = min + 10;
        for (var i = min; i < max; i++) {
            year.push(i);
        }
        $scope.yearName = year;
    };
    $scope.year_select();
    $scope.getInvoice = function(check) {
        $scope.closeTarget('#popupOrderEstimateDetail');
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.getPaging($scope.invoice_id).success(function(data) {
            $ionicLoading.hide();
            $scope.order_jobsite = data.order_jobsite;
            $scope.totalend = data.balance_due;
            $scope.invoiceData = data.data;
            if ($scope.invoiceData.length == 0) {
                $scope.invoiceData = [{}];
            }
            $scope.appointments_inv = data.appointments;
            for (var i = 0; i < $scope.invoiceData.length; i++) {
                if ($scope.invoiceData[i].Measurements != undefined) {
                    $scope.invoiceData[i].Measurements.can_op_go_up = $scope.invoiceData[i].Measurements.can_op_go_up;
                    $scope.invoiceData[i].Measurements.floor_to_ceiling_at_center_plate = parseFloat($scope.invoiceData[i].Measurements.floor_to_ceiling_at_center_plate).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_ceiling_at_drums = parseFloat($scope.invoiceData[i].Measurements.floor_to_ceiling_at_drums).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_hor_at_backhanger = parseFloat($scope.invoiceData[i].Measurements.floor_to_hor_at_backhanger).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_hor_at_radius = parseFloat($scope.invoiceData[i].Measurements.floor_to_hor_at_radius).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_op_rail_18 = parseFloat($scope.invoiceData[i].Measurements.floor_to_op_rail_18).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_op_rail_at_stop_bolt = parseFloat($scope.invoiceData[i].Measurements.floor_to_op_rail_at_stop_bolt).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_left = parseFloat($scope.invoiceData[i].Measurements.opening_height_left).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_middle = parseFloat($scope.invoiceData[i].Measurements.opening_height_middle).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_right = parseFloat($scope.invoiceData[i].Measurements.opening_height_right).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_width = parseFloat($scope.invoiceData[i].Measurements.opening_width).toFixed(2);
                    $scope.invoiceData[i].Measurements.headerBracketInches = parseFloat($scope.invoiceData[i].Measurements.headerBracketInches).toFixed(2);
                    $scope.invoiceData[i].Measurements.opHangerInches = parseFloat($scope.invoiceData[i].Measurements.opHangerInches).toFixed(2);
                    $scope.invoiceData[i].Measurements.Radius = $scope.invoiceData[i].Measurements.Radius;
                }
            }
            if ($scope.tier.t1) {
                $scope.coupon = data.coupon;
                $scope.couponData = data.order_data.coupon_id;
                $scope.couponprice = data.order_data.coupon;
            }
            $scope.Jobsite_id = data.jobsite_id;
            $scope.customertype_id = data.customertype_id;
            $scope.service_id = parseInt(data.order_data.service_id);
            $scope.Representative = data.Representative;
            $scope.Date_Sale = data.order_data.sales_date;
            $scope.invoice_no = data.order_data.invoice_no;
            $scope.Representative_Installer = data.Representative_Installer;
            $scope.installer_date = data.order_data.installer_date;
            $('#signaturePaymentShow').html(data.signature.signname);
            $scope.is_invoice = data.is_invoice;
            $scope.list_product_mark = data.list_product_mark;
            $scope.listpayment_histories = data.paymenthistories;
            $scope.listpayment_histories = _.each($scope.listpayment_histories, function(value) {
                var array_time = value.created_date.split(' ');
                value.created_date = moment(Date.parseDate(array_time[0] + ' ' + String(array_time[1]))).format("MM/DD/YYYY h:mm a");
            });
            $scope.StoreLocation = data.order_data.store_location;
            $scope.store_location = data.order_data.store_location;
            $scope.comment.value = data.comment;
            $scope.signature_id = data.signature.id;
            $scope.payment_amount = data.payment_sum_amount;
            $scope.instoreCreditAmount = data.instorecredit;
            $scope.total_instore_credit = data.total_instore_credit;
            $scope.creditcard_info = data.creditcard;
            $scope.getsignature($scope.signature_id);
            $scope.refund.value = data.order_data.refund;
            $scope.appointment_id = data.order_data.appointment_id;
            $scope.duedate.value = data.order_data.due_date;
            $scope.check_payment_plan = data.check_payment_plan;
            if (parseInt(data.order_data.service_id) == 5 || parseInt(data.order_data.service_id) == 7) {
                $scope.Service = parseInt(data.order_data.service_option);
                $scope.OptionService = parseInt(data.order_data.service_id);
                $scope.Input_value.optionService = $scope.setValueInput($scope.OptionService, $scope.optionOfService);
            } else {
                $scope.Service = parseInt(data.order_data.service_id);
            }
            $scope.change_price($scope.invoiceData);
            if (check != 1) {
                $scope.replaceRes();
            }
            // edit by haudao
            $scope.Input_value.service = $scope.setValueInput($scope.Service, $scope.typeOfService);
            $scope.Input_value.couponData = $scope.setValueInput($scope.couponData, $scope.coupon);
            $scope.setValueSignature($scope.signature_id);
            $scope.setValueServiceLocation($scope.Jobsite_id, 'getData');
            // end edit
            setTimeout(function() {
                $scope.$emit('sendtotal', {
                    total: $scope.total,
                    appointment: $scope.appointments_inv,
                    order_no: $scope.invoice_no,
                    pushchatroom: $scope.pushChatRoom,
                    order_jobsite: $scope.order_jobsite,
                    order_id: $scope.invoice_id,
                    customertype_id: $scope.customertype_id
                });
            }, 200);
            $scope.changeInfoTemplate();
            $scope.dataInsertProducts = [];
            $scope.getListProducts({
                search: '',
                from: 'app'
            });
            $scope.getCornerstyles();
        });
    };
    $scope.getSaleorder = function(check) {
        $scope.closeTarget('#popupOrderEstimateDetail');
        $ionicLoading.show({
            template: templateLoading
        });
        Saleorder.getPaging($scope.saleorder_id).success(function(data) {
            $ionicLoading.hide();
            $scope.order_jobsite = data.order_jobsite;
            $scope.totalend = data.balance_due;
            $scope.invoiceData = data.data;
            if ($scope.invoiceData.length == 0) {
                $scope.invoiceData = [{}];
            }
            $scope.appointments_inv = data.appointments;
            for (var i = 0; i < $scope.invoiceData.length; i++) {
                if ($scope.invoiceData[i].Measurements != undefined) {
                    $scope.invoiceData[i].Measurements.can_op_go_up = $scope.invoiceData[i].Measurements.can_op_go_up;
                    $scope.invoiceData[i].Measurements.floor_to_ceiling_at_center_plate = parseFloat($scope.invoiceData[i].Measurements.floor_to_ceiling_at_center_plate).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_ceiling_at_drums = parseFloat($scope.invoiceData[i].Measurements.floor_to_ceiling_at_drums).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_hor_at_backhanger = parseFloat($scope.invoiceData[i].Measurements.floor_to_hor_at_backhanger).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_hor_at_radius = parseFloat($scope.invoiceData[i].Measurements.floor_to_hor_at_radius).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_op_rail_18 = parseFloat($scope.invoiceData[i].Measurements.floor_to_op_rail_18).toFixed(2);
                    $scope.invoiceData[i].Measurements.floor_to_op_rail_at_stop_bolt = parseFloat($scope.invoiceData[i].Measurements.floor_to_op_rail_at_stop_bolt).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_left = parseFloat($scope.invoiceData[i].Measurements.opening_height_left).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_middle = parseFloat($scope.invoiceData[i].Measurements.opening_height_middle).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_height_right = parseFloat($scope.invoiceData[i].Measurements.opening_height_right).toFixed(2);
                    $scope.invoiceData[i].Measurements.opening_width = parseFloat($scope.invoiceData[i].Measurements.opening_width).toFixed(2);
                    $scope.invoiceData[i].Measurements.headerBracketInches = parseFloat($scope.invoiceData[i].Measurements.headerBracketInches).toFixed(2);
                    $scope.invoiceData[i].Measurements.opHangerInches = parseFloat($scope.invoiceData[i].Measurements.opHangerInches).toFixed(2);
                    $scope.invoiceData[i].Measurements.Radius = $scope.invoiceData[i].Measurements.Radius;
                }
            }
            if ($scope.tier.t1) {
                $scope.coupon = data.coupon;
                $scope.couponData = data.order_data.coupon_id;
                $scope.couponprice = data.order_data.coupon;
            }
            $scope.customertype_id = data.customertype_id;
            $scope.Jobsite_id = data.jobsite_id;
            $scope.service_id = parseInt(data.order_data.service_id);
            $scope.Representative = data.Representative;
            $scope.Date_Sale = data.order_data.sales_date;
            $scope.invoice_no = data.order_data.invoice_no;
            $scope.Representative_Installer = data.Representative_Installer;
            $scope.installer_date = data.order_data.installer_date;
            $('#signaturePaymentShow').html(data.signature.signname);
            $scope.is_invoice = data.is_invoice;
            $scope.list_product_mark = data.list_product_mark;
            $scope.listpayment_histories = data.paymenthistories;
            $scope.listpayment_histories = _.each($scope.listpayment_histories, function(value) {
                var array_time = value.created_date.split(' ');
                value.created_date = moment(Date.parseDate(array_time[0] + ' ' + String(array_time[1]))).format("MM/DD/YYYY h:mm a");
            });
            $scope.StoreLocation = data.order_data.store_location;
            $scope.store_location = data.order_data.store_location;
            $scope.comment.value = data.comment;
            $scope.signature_id = data.signature.id;
            $scope.payment_amount = data.payment_sum_amount;
            $scope.instoreCreditAmount = data.instorecredit;
            $scope.total_instore_credit = data.total_instore_credit;
            $scope.creditcard_info = data.creditcard;
            $scope.getsignature($scope.signature_id);
            $scope.refund.value = data.order_data.refund;
            $scope.appointment_id = data.order_data.appointment_id;
            $scope.duedate.value = data.order_data.due_date;
            $scope.check_payment_plan = data.check_payment_plan;
            if (parseInt(data.order_data.service_id) == 5 || parseInt(data.order_data.service_id) == 7) {
                $scope.Service = parseInt(data.order_data.service_option);
                $scope.OptionService = parseInt(data.order_data.service_id);
                $scope.Input_value.optionService = $scope.setValueInput($scope.OptionService, $scope.optionOfService);
            } else {
                $scope.Service = parseInt(data.order_data.service_id);
            }
            $scope.change_price($scope.invoiceData);
            if (check != 1) {
                $scope.replaceRes();
            }
            // edit by haudao
            $scope.Input_value.service = $scope.setValueInput($scope.Service, $scope.typeOfService);
            $scope.Input_value.couponData = $scope.setValueInput($scope.couponData, $scope.coupon);
            $scope.setValueSignature($scope.signature_id);
            $scope.setValueServiceLocation($scope.Jobsite_id, 'getData');
            // end edit
            setTimeout(function() {
                $scope.$emit('sendtotal', {
                    total: $scope.total,
                    appointment: $scope.appointments_inv,
                    order_no: $scope.invoice_no,
                    pushchatroom: $scope.pushChatRoom,
                    order_jobsite: $scope.order_jobsite,
                    order_id: $scope.saleorder_id,
                    customertype_id: $scope.customertype_id
                });
            }, 200);
            $scope.changeInfoTemplate();
            $scope.dataInsertProducts = [];
            $scope.getListProducts({
                search: '',
                from: 'app'
            });
            $scope.getCornerstyles();
        });
    };
    $scope.updateMD = function(val) {
        $scope.closeTarget('#popupOrderInvoiceDetailDiscountCoupon');
        if (!val) return;
        angular.forEach($scope.invoiceData, function(item) {
            if (parseInt(item.disable) != 1) item.Extended = parseFloat(val);
        })
        $cordovaToast.showLongTop('MD% is applied to all items. Please tap SAVE to save other changes to selected item.');
        $scope.change_price($scope.invoiceData);
    }
    $scope.updateRefund = function(val) {
        $cordovaToast.showLongTop('Please tap SAVE to save other changes to selected item.');
        $scope.closeTarget('#popupOrderInvoiceDetailDiscountCoupon');
        $scope.closeTarget('#popupOrderInvoiceDetailEditRefund');
        $scope.refund.value = parseInt(val);
        $scope.change_price($scope.invoiceData);
    }
    $scope.updateComment = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        Orderstatuses.updateComment($scope.comment.value, order_id).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.closeTarget('#popupOrderInvoiceDetailComment');
                $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.price_change_event = function(action, value) {
        switch (action) {
            case 'select_MD':
                break;
            case 'select_MD_All':
                $scope.select_MD_All = $scope.requiredfloat(value);
                if ($scope.select_MD_All != '') {
                    for (var i = 0; i < $scope.invoiceData.length; i++) {
                        if ($scope.invoiceData[i].disable == 0) {
                            console.log($scope.select_MD_All);
                            $scope.invoiceData[i].Extended = $scope.select_MD_All;
                        }
                    }
                }
                $scope.change_price($scope.invoiceData);
                break;
        }
    };
    $scope.checkAll_event = function(action) {
        console.log(action);
        switch (action) {
            case 'sold_All':
                if ($scope.sold_all.value == 1) {
                    $scope.declined_all.value == 0;
                };
                for (var i = 0; i < $scope.invoiceData.length; i++) {
                    if ($scope.invoiceData[i].declined == 0 && $scope.invoiceData[i].disable == 0) {
                        $scope.invoiceData[i].sold = $scope.sold_all.value;
                    }
                }
                $scope.change_price($scope.invoiceData);
                break;
            case 'installed_All':
                for (var i = 0; i < $scope.invoiceData.length; i++) {
                    if ($scope.invoiceData[i].disable == 0) {
                        if ($scope.installed_all.value == 1) {
                            if ($scope.invoiceData[i].sold == 1) {
                                $scope.invoiceData[i].installed = 1;
                            }
                        } else {
                            $scope.invoiceData[i].installed = 0;
                        }
                    }
                }
                $scope.change_price($scope.invoiceData);
                break;
            case 'declined_All':
                if ($scope.declined_all.value == 1) {
                    $scope.sold_all.value == 0;
                    $scope.installed_all.value == 0
                };
                for (var i = 0; i < $scope.invoiceData.length; i++) {
                    if ($scope.invoiceData[i].sold == 0 && $scope.invoiceData[i].disable == 0) {
                        $scope.invoiceData[i].declined = $scope.declined_all.value;
                    }
                }
                $scope.change_price($scope.invoiceData);
                break;
        }
    };
    $scope.send_to_event = function(action, formValidate) {
        if (action == 'Generate_printable_PDF') {
            $scope.check_export_file_pdf = 1;
            $scope.Save_Invoice('Generate_printable_PDF', '');
            return;
        }
        if (action == 'Generate_printable_PDF_DPI') {
            $scope.check_export_file_pdf = 1;
            $scope.Save_Invoice('Generate_printable_PDF_DPI', '');
            return;
        }
        if (formValidate && formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        console.log(action);
        switch (action) {
            case 'AdvancedEmail':
                $scope.check_export_file_pdf = 1;
                $scope.AdvancedEmail.sendmail = $scope.AdvancedEmail.emails;
                $scope.Save_Invoice('AdvancedEmail', $scope.AdvancedEmail);
                break;
            case 'email':
                $scope.check_export_file_pdf = 1;
                $scope.Save_Invoice('send_pdf', $scope.email_sento.value);
                break;
            case 'Snail_Mail':
                $scope.Save_Invoice();
                $scope.create_task();
                break;
        }
    };
    $scope.export_file_pdf = function(order_id, action, mail) {
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.export_file_pdf(order_id, action, mail, $scope.Jobsite_id, $scope.currentIdLogin).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                if (data.link) {
                    $scope.cordovaBrowser(data.link);
                }
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.changequantity = function(quantity, product_id, item_id) {
        for (var i = 0; i < $scope.invoiceData.length; i++) {
            if (parseInt($scope.invoiceData[i]['id']) == parseInt(product_id) && parseInt($scope.invoiceData[i]['item_id']) == parseInt(item_id)) {
                $scope.invoiceData[i]['quantity'] = quantity;
            }
        }
        $scope.change_price($scope.invoiceData);
    }
    $scope.change_warranty = function(warranty_id, product_id, item_id) {
        for (var i = 0; i < $scope.invoiceData.length; i++) {
            if (parseInt($scope.invoiceData[i]['id']) == parseInt(product_id) && parseInt($scope.invoiceData[i]['item_id']) == parseInt(item_id)) {
                var warranty = _.where($scope.Warrantydata, {
                    id: warranty_id
                })[0];
                $scope.invoiceData[i]['warranty_id'] = warranty.id;
                $scope.invoiceData[i]['warranty_name'] = warranty.name;
            }
        }
        $scope.change_price($scope.invoiceData);
    }
    $scope.change_MD = function(Extended, product_id, item_id) {
        for (var i = 0; i < $scope.invoiceData.length; i++) {
            if (parseInt($scope.invoiceData[i]['id']) == parseInt(product_id) && parseInt($scope.invoiceData[i]['item_id']) == parseInt(item_id)) {
                $scope.invoiceData[i]['Extended'] = Extended;
            }
        }
        $scope.change_price($scope.invoiceData);
    }
    $scope.bill = '';
    $scope.TotalBill = function() {
        $scope.bill = ' $' + $scope.total / 2;
    }
    $scope.checkshowcaculator = 0;
    $scope.opencaculator = function() {
        $scope.openIonicPopup('templates/dashboard/order/invoice/invoicePopupCalculatormodal.tpl', 'Calculator');
    }
    $scope.getcustomermail = function() {
        $scope.AdvancedEmail = {};
        $scope.AdvancedEmail.emails = [];
        Orderstatuses.getcustomermail($scope.customerId).success(function(data) {
            $scope.customermail = data.customerMail;
            _.each(data.customerMail, function(item) {
                $scope.AdvancedEmail.emails.push({
                    text: item.email
                });
            });
            $scope.initialInvoiceSendFrom = $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.';
        });
    }
    $scope.AdvancedEmailCustomer = function(formValidate) {
        $ionicLoading.show({
            template: templateLoading
        });
        if (formValidate.$invalid) {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $scope.AdvancedEmail.sendmail = $scope.AdvancedEmail.emails;
        $scope.send_to_event('AdvancedEmail');
    }
    $scope.AdvancedEmailrequiredemail = function(value, $index) {
        if (value) {
            $('.indexemailrequired').removeAttr('required');
            $('#indexemail-' + $index).attr("required", "true");
        }
    }
    $scope.invoiceData = [];
    $scope.insertItemPricebook = function(data, action) {
        $ionicLoading.show({
            template: templateLoading
        });
        if (action == 'multi') {
            Ordertypes.getDataProduct(data, $scope.service_id, action).success(function(data) {
                $scope.searchResult = [];
                for (var i = 0; i < data.length; i++) {
                    var index = _.findIndex($scope.invoiceData, {
                        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.invoiceData.push(data[i]);
                    }else{
                        if(data[i].Measurements){
                            $scope.invoiceData[index].Measurements = data[i].Measurements ;
                        }
                    }
                   
                }
                $scope.change_price($scope.invoiceData);
                $scope.getListPairProduct (data);
                $(".itm-area .box-expandable").addClass('expand');
                $scope.replaceRes();
                $ionicLoading.hide();
              
            });
        } else {
            Ordertypes.getDataProduct(data.id, $scope.service_id).success(function(data) {
                $scope.searchResult = [];
                var union = arrayUnion($scope.invoiceData, data, function(item1, item2) {
                    if (item1.id == item2.id && item1.disable == 0) {
                        return item1.id == item2.id;
                    }
                });
                $scope.invoiceData = union;
                $(".itm-area .box-expandable").addClass('expand');
                $scope.change_price($scope.invoiceData);
                $scope.getListPairProduct(data);
                $scope.replaceRes();
                $ionicLoading.hide();
            });
        }
    };

    $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.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.products = products;
        $scope.cornerstylesdata.service_id = $scope.service_id;
        if(!products[index]['Measurements']){
            $scope.openByGetTemplate('popupCornerstylesInv');
          }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(){
        Products.getPairProduct($scope.cornerstylesdata).success(function(data){
             if(data.status == true){
                 $scope.invoiceData = $scope.pushPairProductToList($scope.invoiceData,data.pricebook_pair)
                 $scope.closeTarget('#popupCornerstylesInv');
                 $scope.closePopupCornerstyles();
             }else{
                 $scope.closePopupCornerstyles();
                 $cordovaToast.showLongTop(data.msg);
             }
        });
      }
    
      $scope.closePopupCornerstyles = function(){
        $scope.closeTarget('#popupCornerstylesInv');
        if($scope.cornerstylesdata.index < $scope.cornerstylesdata.products.length-1){
          $scope.selectCornerstyles($scope.cornerstylesdata.products,$scope.cornerstylesdata.index + 1)
        } else{
            $scope.change_price($scope.invoiceData);
        }
      }

      $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.setValueCornerstylesInput = function (id) {
        $scope.cornerstylesdata.cornerstyles_name = "";
        $scope.cornerstylesdata.cornerstyles_name = $scope.setValueForInputCorner($scope.cornerstyles, id).name;
    }
    $scope.setValueForInputCorner = function (arrData, id) {
        var result = '';
        var index = _.findLastIndex(arrData, {
            id: id
        });
        if (index >= 0)
            result = arrData[index];
        return result;
      }
    $scope.searchData = {};
    $scope.searchData.data = [];
    $scope.searchData.pricebookdt = [];
    $scope.refreshpricebook = function(search) {
        if (search.length > 0) {
            var params = {
                search: search
            };
            $('.caption_loading').show();
            Products.getSelect2(params, $scope.searchtype.value).success(function(data) {
                var diff = differentArray(data, $scope.searchData.pricebookdt);
                $scope.searchResult = diff;
                $('.caption_loading').hide();
            })
        }
    };
    $scope.change_price = function(data) {
        var declined_checked = 0;
        var declined_uncheck = 0;
        var sold_checked = 0;
        var sold_uncheck = 0;
        var installed_checked = 0;
        var disable = 0;
        $scope.Subtotal = 0;
        $scope.Discount = 0;
        for (var i = 0; i < data.length; i++) {
            data[i]['quantity'] = $scope.requirednumber(data[i]['quantity']);
            $('.quantity-' + data[i]['id'] + data[i]['item_id']).val(data[i]['quantity']);
            data[i]['Extended'] = $scope.requiredfloat(data[i]['Extended']);
            $('.discount-' + data[i]['id'] + data[i]['item_id']).val(data[i]['Extended']);
            data[i]['Extended_Price'] = parseFloat((data[i]['price'] * data[i]['quantity']) - ((data[i]['price'] * parseFloat(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_all.value = 0;
                $scope.Subtotal += (data[i]['price'] * data[i]['quantity']);
                $scope.Discount += ((data[i]['price'] * parseFloat(data[i]['Extended']) * data[i]['quantity']) / 100);
                declined_uncheck++;
            } else {
                declined_checked++;
            }
            if (data[i]['sold'] == 0) {
                $scope.sold_all.value = 0;
                data[i]['installed'] = 0;
                sold_uncheck++;
            } else {
                sold_checked++;
            }
            if (data[i]['installed'] == 0) {
                $scope.installed_all.value = 0;
            } else {
                installed_checked++;
            }
            if (data[i]['disable'] == 1) {
                disable++;
            }
            if (declined_checked == sold_uncheck && declined_checked != 0) {
                $scope.declined_all.value = 1;
            }
            if (installed_checked == sold_checked + disable && installed_checked != 0) {
                $scope.installed_all.value = 1;
            }
            if (sold_checked == declined_uncheck + disable && sold_checked != 0) {
                $scope.sold_all.value = 1;
            }
        }
        $scope.Discount = parseFloat($scope.Discount).toFixed(2);
        if ($scope.refund.value.length == 0) {
            $scope.refund.value = 0;
        } else {
            var item_length = $scope.refund.value.toString().split('.').length;
            $scope.refund.value = $scope.refund.value.toString().replace(/[^0-9-.]/g, '');
            if (item_length > 1 && $scope.refund.value.toString().split('.')[1] != '' || item_length > 2) {
                $scope.refund.value = parseFloat($scope.refund.value).toFixed(2);
            }
            if (item_length == 1) {
                $scope.refund.value = parseFloat($scope.refund.value);
            }
        }
        if ($scope.couponData && parseInt($scope.couponData) > 0 && $scope.coupon) {
            var curr_coupon = _.find($scope.coupon, {
                "id": $scope.couponData
            });
            if (curr_coupon.type == "%") {
                $scope.couponprice = ($scope.Subtotal - $scope.Discount) * parseInt(curr_coupon.discount) / 100;
            } else {
                $scope.couponprice = curr_coupon.discount;
            }
        }
        $scope.refund.value = $scope.requiredfloat($scope.refund.value);
        if ($scope.tier.t1) {
            $scope.total = parseFloat($scope.Subtotal - $scope.Discount - $scope.couponprice).toFixed(2);
        } else {
            $scope.total = parseFloat($scope.Subtotal - $scope.Discount).toFixed(2);
        }
        $scope.totalend = parseFloat(parseFloat($scope.total) + parseFloat($scope.instoreCreditAmount) - parseFloat($scope.refund.value) - parseFloat($scope.payment_amount)).toFixed(2);
        setTimeout(function() {
            for (var i = 0; i < data.length; i++) {
                $('.warranty-' + data[i]['id'] + data[i]['item_id']).val(data[i]['warranty_id']);
            }
            $('.editMeasurements').unbind("click");
            $('.editMeasurements').click(function() {
                $scope.buttonSubmitEditMeasurements = "Save";
                if ($(this).attr('dataDisable') == 1) {
                    $('#MeasurementsEditDoor').find("select, input").attr('disabled', 'disabled');
                    $('#MeasurementsEditDoor > .buttons').hide();
                } else {
                    $('#MeasurementsEditDoor').find("select, input").removeAttr('disabled');
                    $('#MeasurementsEditDoor > .buttons').show();
                }
                $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);
                $scope.InchesTable($scope.heightedit, 'edit');
                $scope.styleOfMeasurement = "Edit";
                $scope.openByGetTemplate('popupOrderInvoiceMeasurements');
                setTimeout(function() {
                    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.Subtotal = parseFloat($scope.Subtotal.toFixed(2));
        $scope.changeInfoTemplate();
    };
    $scope.change_coupon = function(id) {
        $scope.couponData = id;
        $scope.Input_value.couponData = $scope.setValueInput(id, $scope.coupon);
        if (id == '' || id == null || id == '0') {
            $scope.couponprice = 0;
            $scope.change_price($scope.invoiceData);
        } else {
            for (var i = 0; i < $scope.coupon.length; i++) {
                if ($scope.coupon[i].id == id) {
                    if ($scope.coupon[i].type == "%") {
                        $scope.couponprice = ($scope.Subtotal - $scope.Discount - parseFloat($scope.refund)) * parseInt($scope.coupon[i].discount) / 100;
                    } else {
                        $scope.couponprice = $scope.coupon[i].discount;
                    }
                    $scope.change_price($scope.invoiceData);
                }
            }
        }
    }
    $scope.requiredcvv = function(value, action) {
        if (!value) return 0;
        if (value.length == 0) {
            value = '';
        }
        value = value.toString().replace(/[^0-9]/g, '');
        value = value.substring(0, 4);
        if (action == 'Payment_Plan') {
            $scope.Payment_Plan.CVV2_Codes = value;
        } else {
            $scope.CC_Manual.CVV2_Code = value;
        }
    };
    $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.requiredAmount = function(value, action, index) {
        switch (action) {
            case 'Cash':
                $scope.Cash.Amount = $scope.requiredfloat(value);
                break;
            case 'Check':
                $scope.Check.Amount = $scope.requiredfloat(value);
                break;
            case 'Prepaid':
                $scope.Prepaid.Amount = $scope.requiredfloat(value);
                break;
            case 'CC_Manual':
                $scope.CC_Manual.Amount = $scope.requiredfloat(value);
                break;
            case 'Prepaid':
                $scope.Prepaid.Amount = $scope.requiredfloat(value);
                break;
            case 'ChargeDate':
                $scope.ChargeDate[index].amount = $scope.requiredfloat(value);
                break;
            case 'Payment_Plan':
                $scope.Payment_Plan.Card_Number = $scope.requirednumber(value);
                angular.element('#Payment_Plan_Card_Number').validateCreditCard(function(result) {
                    if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
                        $scope.Payment_Plan.Card_Type = result.card_type.name;
                        $('.pplogs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
                        $('#required_Payment_Plan').val(1);
                    } else {
                        $('.pplogs').html('Please input card number.');
                        $('#required_Payment_Plan').val(0);
                    }
                });
                break;
            case 'CC_Manual_cart':
                $scope.CC_Manual.card_number = $scope.requirednumber(value);
                angular.element('#CC_Manual_card_number').validateCreditCard(function(result) {
                    if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
                        $scope.CC_Manual.Card_Type_cc = result.card_type.name;
                        $('.logs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
                        $('#required_CC_Manual').val(1);
                    } else {
                        $('#required_CC_Manual').val(0);
                        $('.logs').html('Please input card number.');
                    }
                });
                break;
        }
    }
    $scope.Save_Invoice = function(action, mail) {
        $ionicLoading.show({
            template: templateLoading
        });
        var data_invoice = {};
        var duedate = moment($scope.duedate.value).format('YYYY-MM-DD');
        if (duedate == "Invalid date") duedate = $scope.duedate.value;
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        data_invoice.invoiceData = $scope.invoiceData;
        data_invoice.Discount = $scope.Discount;
        data_invoice.Subtotal = $scope.Subtotal;
        data_invoice.id = order_id;
        data_invoice.user_id = $scope.currentIdLogin;
        data_invoice.refund = $scope.refund.value;
        data_invoice.total = $scope.total;
        data_invoice.duedate = duedate;
        data_invoice.couponprice = $scope.couponprice;
        data_invoice.coupon_id = $scope.couponData;
        data_invoice.store_location = $scope.StoreLocation;
        data_invoice.service_id = $scope.service_id;
        Ordertypes.save(data_invoice).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                var number_installed_or_installed_item = _.filter($scope.invoiceData, function(item) {
                    return parseInt(item.installed) == 1 || parseInt(item.declined) == 1;
                }).length;
                if (parseInt($scope.invoice_id) > 0) {
                    if ($scope.Service == 6) {
                        $scope.getInvoice('');
                        $scope.closeTarget("#popupOrderInvoiceDetailOptions");
                        $scope.closeTarget("#popupOrderInvoiceSendToOptions");
                        $scope.closeTarget("#popupOrderInvoiceSendToDetail");
                        if ($scope.check_export_file_pdf == 1) {
                            $scope.export_file_pdf(order_id, action, mail);
                            $scope.check_export_file_pdf = 0;
                        }
                        if (action == 'beforeAddPayment') {
                            $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                        }
                        if (action == 'addPayment') $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                        $cordovaToast.showLongTop(data.msg);
                    } else {
                        if (number_installed_or_installed_item < $scope.invoiceData.length) {
                            $scope.closeTarget('#popupOrderInvoiceDetail');
                            $scope.reverttosaleorder($scope.invoice_id);
                        } else {
                            $scope.getInvoice('');
                            $scope.closeTarget("#popupOrderInvoiceDetailOptions");
                            $scope.closeTarget("#popupOrderInvoiceSendToOptions");
                            $scope.closeTarget("#popupOrderInvoiceSendToDetail");
                            if ($scope.check_export_file_pdf == 1) {
                                $scope.export_file_pdf(order_id, action, mail);
                                $scope.check_export_file_pdf = 0;
                            }
                            if (action == 'beforeAddPayment') {
                                $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                            }
                            if (action == 'addPayment') $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                            $cordovaToast.showLongTop(data.msg);
                        }
                    }
                }
                if (parseInt($scope.saleorder_id) > 0) {
                    if (data.Redirect) {
                        $scope.closeTarget('#popupOrderInvoiceDetail');
                        $scope.getOrders();
                        delete $scope.saleorder_id;
                        $scope.invoice_id = data.order_id;
                        setTimeout(function() {
                            $scope.goToInvoiceDetails($scope.invoice_id);
                        }, 100);
                        return false;
                    }
                    if (number_installed_or_installed_item == $scope.invoiceData.length) {
                        $scope.closeTarget('#popupOrderInvoiceDetail')
                        $scope.converttoinvoice($scope.saleorder_id);
                    } else {
                        $scope.getSaleorder('');
                        $scope.closeTarget("#popupOrderInvoiceDetailOptions");
                        $scope.closeTarget("#popupOrderInvoiceSendToOptions");
                        $scope.closeTarget("#popupOrderInvoiceSendToDetail");
                        if ($scope.check_export_file_pdf == 1) {
                            $scope.export_file_pdf(order_id, action, mail);
                            $scope.check_export_file_pdf = 0;
                        }
                        if (action == 'beforeAddPayment') {
                            $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                        }
                        if (action == 'addPayment') $scope.openByGetTemplate('popupOrderInvoiceTermsOfConditions');
                        $cordovaToast.showLongTop(data.msg);
                    }
                }
                $scope.getOrders();
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.create_task = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        Ordertypes.export_file_pdf(order_id, 'Generate_printable_PDF', '').success(function(data) {
            Orderstatuses.create_task($scope.Snail_Mail.value, $scope.currentIdLogin, $scope.appointment_id, 'invoice', $scope.customerId, data.link).success(function(data) {
                $ionicLoading.hide();
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            });
        });
    }
    $scope.ChargeDate = [{
        amount: '',
        ChargeDate: '',
        transaction_id: null,
        status: null
    }];
    $scope.addRowChargeDate = function(id, action) {
        if ($scope.ChargeDate.length < 3) {
            $scope.ChargeDate.push({
                amount: '',
                ChargeDate: '',
                transaction_id: null,
                status: null
            });
            $scope.resizeScroll('scrollPaymentAdd');
        }
        setTimeout(function() {
            $scope.$apply(function(val) {
                $scope.required_form(id, action);
            });
        }, 100);
    }
    $scope.removeItemChargeDate = function(index) {
        if ($scope.ChargeDate.length > 1) {
            $scope.ChargeDate.splice(index, 1);
            $scope.resizeScroll('scrollPaymentAdd');
        }
    }
    $scope.paymenthistories = {};
    $scope.Add_Payment = function() {
        if ($scope.checksendBraintree == 0) {
            $scope.payment_sum_amount = 0;
            $scope.over_payment = 0;
            if (parseInt($scope.invoice_id) > 0) {
                var order_id = $scope.invoice_id;
            }
            if (parseInt($scope.saleorder_id) > 0) {
                var order_id = $scope.saleorder_id;
            }
            $scope.checksendBraintree = 1;
            var required_form = 2;
            $ionicLoading.show({
                template: templateLoading
            });
            if ($scope.checkbox.Cash_check == 1) {
                $scope.paymenthistories.Cash = {};
                $scope.paymenthistories.Cash.amount = $scope.Cash.Amount;
                $scope.paymenthistories.Cash.method = 'Cash';
                $scope.paymenthistories.Cash.order_id = order_id;
                $scope.payment_sum_amount += parseFloat($scope.Cash.Amount);
            }
            if ($scope.checkbox.Wells_Fargo_Plan == 1) {
                $scope.paymenthistories.Wells_Fargo_Plan = {};
                $scope.paymenthistories.Wells_Fargo_Plan.method = 'Wells Fargo Plan';
                $scope.paymenthistories.Wells_Fargo_Plan.order_id = order_id;
                $scope.paymenthistories.Wells_Fargo_Plan.amount = $scope.WellFargoPlan.authorization_amount;
                $scope.paymenthistories.Wells_Fargo_Plan.authorization_number = $scope.WellFargoPlan.authorization_number;
                $scope.paymenthistories.Wells_Fargo_Plan.credit_term_plan_number = $scope.WellFargoPlan.credit_term_plan_number;
                $scope.payment_sum_amount += parseFloat($scope.WellFargoPlan.amount);
            }
            if ($scope.checkbox.Check_check == 1) {
                $scope.paymenthistories.Check = {};
                $scope.paymenthistories.Check.amount = $scope.Check.Amount;
                $scope.paymenthistories.Check.method = 'Check';
                $scope.paymenthistories.Check.check = $scope.Check.Check;
                $scope.paymenthistories.Check.authorization = $scope.Check.Authorization;
                $scope.paymenthistories.Check.order_id = order_id;
                $scope.payment_sum_amount += parseFloat($scope.Check.Amount);
            }
            if ($scope.checkbox.CC_Manual_check == 1) {
                if ($('#required_CC_Manual').val() == 0) {
                    required_form--;
                }
                $scope.paymenthistories.CC_Manual = {};
                $scope.paymenthistories.CC_Manual.method = 'CC Manual';
                $scope.paymenthistories.CC_Manual.amount = $scope.CC_Manual.Amount;
                $scope.paymenthistories.CC_Manual.cardtype = $scope.CC_Manual.Card_Type_cc;
                $scope.paymenthistories.CC_Manual.cardnumber = $scope.CC_Manual.card_number;
                $scope.paymenthistories.CC_Manual.order_id = order_id;
                $scope.paymenthistories.CC_Manual.customerInfo = $scope.CC_Manual;
                $scope.paymenthistories.CC_Manual.customer_id = $scope.CC_Manual.id;
                $scope.paymenthistories.CC_Manual.use_credit_card_check = $scope.checkbox.use_credit_card_check;
                if (parseInt($scope.checkbox.add_this_card) > 0) {
                    $scope.paymenthistories.CC_Manual.add_this_card = parseInt($scope.checkbox.add_this_card);
                } else {
                    $scope.paymenthistories.CC_Manual.add_this_card = 0;
                }
                if (parseInt($scope.checkbox.update_this_card) > 0) {
                    $scope.paymenthistories.CC_Manual.update_this_card = parseInt($scope.checkbox.update_this_card);
                } else {
                    $scope.paymenthistories.CC_Manual.update_this_card = 0;
                }
                $scope.payment_sum_amount += parseFloat($scope.CC_Manual.Amount);
            }
            if ($scope.checkbox.Prepaid_check == 1) {
                $scope.paymenthistories.Prepaid = {};
                $scope.paymenthistories.Prepaid.method = 'Prepaid';
                $scope.paymenthistories.Prepaid.amount = $scope.Prepaid.Amount;
                $scope.paymenthistories.Prepaid.order_id = order_id;
            }
            if ($scope.checkbox.Payment_Plan_check == 1) {
                if ($('#required_Payment_Plan').val() == 0) {
                    required_form--;
                }
                $scope.paymenthistories.Payment_Plan = {};
                $scope.paymenthistories.Payment_Plan.method = 'Payment Plan';
                $scope.paymenthistories.Payment_Plan.cardtype = $scope.Payment_Plan.Card_Type;
                $scope.paymenthistories.Payment_Plan.cardnumber = $scope.Payment_Plan.Card_Number;
                $scope.paymenthistories.Payment_Plan.order_id = order_id;
                $scope.paymenthistories.Payment_Plan.customerInfo = $scope.Payment_Plan;
                $scope.paymenthistories.Payment_Plan.chargedate = $scope.ChargeDate;
                $scope.paymenthistories.Payment_Plan.chargedate.forEach(function(item) {
                    item.ChargeDate = moment(item.ChargeDate).format('MM/DD/YYYY');
                })
            }
            if ($scope.checkbox.Credit_Memo_check == 1) {
                $scope.paymenthistories.Credit_Memo = {};
                $scope.paymenthistories.Credit_Memo.method = 'Credit Memo';
                $scope.paymenthistories.Credit_Memo.amount = $scope.Credit_Memo.Amount;
                $scope.paymenthistories.Credit_Memo.note = $scope.Credit_Memo.note;
                $scope.paymenthistories.Credit_Memo.order_id = order_id;
                $scope.payment_sum_amount += $scope.Credit_Memo.Amount;
            }
            if ($scope.checkbox.Manager_Credit_check == 1) {
                $scope.paymenthistories.Manager_Credit = {};
                $scope.paymenthistories.Manager_Credit.method = 'Manager Credit';
                $scope.paymenthistories.Manager_Credit.amount = $scope.Manager_Credit.Amount;
                $scope.paymenthistories.Manager_Credit.note = $scope.Manager_Credit.note;
                $scope.paymenthistories.Manager_Credit.order_id = order_id;
                $scope.payment_sum_amount += parseFloat($scope.Manager_Credit.Amount);
            }
            if ($scope.checkbox.Instore_Credit_check == 1) {
                $scope.paymenthistories.Instore_Credit = {};
                $scope.paymenthistories.Instore_Credit.amount = $scope.Instore_Credit.Amount;
                $scope.paymenthistories.Instore_Credit.method = 'In Store Credit';
                $scope.paymenthistories.Instore_Credit.order_id = order_id;
                $scope.payment_sum_amount += parseFloat($scope.Instore_Credit.Amount);
            }
            $scope.paymenthistories.invoiceId = order_id;
            $scope.paymenthistories.checkinsertpaymenthistory = $scope.checkinsertpaymenthistory;
            $scope.paymenthistories.date = $scope.historyDate;
            if ($scope.payment_sum_amount > $scope.totalend) {
                if (
                    ($scope.checkbox.Cash_check == 1 || $scope.checkbox.Check_check == 1 || $scope.checkbox.Credit_Memo_check == 1 || $scope.checkbox.Manager_Credit_check == 1) && $scope.checkbox.Wells_Fargo_Plan == 0 && $scope.checkbox.CC_Manual_check == 0 && $scope.checkbox.Instore_Credit_check == 0) {
                    if ($scope.payment_sum_amount - parseFloat($scope.totalend) > 20 && !$scope.isOverage20Payment) {
                        $scope.checksendBraintree = 0;
                        $ionicLoading.hide();
                        $cordovaToast.showLongTop('The payment you entered exceeds the total due by more than $20. Please request correct payment amount.');
                        return;
                    }
                    $scope.openByGetTemplate('confirmOverPayment');
                    $scope.over_payment = $scope.payment_sum_amount - $scope.totalend;
                } else {
                    $scope.checksendBraintree = 0;
                    $ionicLoading.hide();
                    $cordovaToast.showLongTop('The paid amount (history and new added) is larger than the total of the invoice. Please check the numbers again.');
                    return;
                }
            } else {
                $scope.createBraintree($scope.paymenthistories, required_form);
            }
        }
    }
    $scope.createBraintree = function(paymenthistories, required_form) {
        if (required_form == 2) {
            $ionicLoading.show({
                template: templateLoading
            });
            paymenthistories.over_payment = $scope.over_payment;
            Ordertypes.sentDataPayment(paymenthistories).success(function(data) {
                $scope.checksendBraintree = 0;
                $ionicLoading.hide();
                $timeout(function() {
                    $scope.closeTarget('#popupOrderInvoiceTermsOfConditions');
                    $scope.closeTarget('#popupOrderInvoiceAddPayment');
                }, 5000);
                if (data.status) {
                    $scope.payment_success = data.success;
                    $scope.payment_error = data.error;
                    if (parseInt($scope.invoice_id) > 0) {
                        $scope.getInvoice(1);
                    }
                    if (parseInt($scope.saleorder_id) > 0) {
                        $scope.getSaleorder(1);
                    }
                    if (data.arrIdHistory.length > 0) {
                        if ($scope.checkinsertpaymenthistory == 0) {
                            $scope.list_paymenthistory = data.arrIdHistory;
                        } else {
                            for (var i = 0; i < data.arrIdHistory.length; i++) {
                                $scope.list_paymenthistory.push(data.arrIdHistory[i]);
                            }
                            $cordovaToast.showLongTop($scope.list_paymenthistory);
                        }
                        $scope.historyDate = data.date;
                        if (data.error.length > 0) {
                        } else {
                            $scope.openByGetTemplate('popupOrderInvoiceAddPaymentSignature');
                            $scope.checkinsertpaymenthistory = 0;
                        }
                        $ionicLoading.hide();
                        $plan = 0;
                        for (var i = 0; i < data.success.length; i++) {
                            switch (data.success[i]['key']) {
                                case 'CC_Manual':
                                    $scope.CC_Manual.card_number = '';
                                    $scope.CC_Manual.month_cc = '';
                                    $scope.CC_Manual.year_cc = '';
                                    $scope.CC_Manual.CVV2_Code = '';
                                    $scope.CC_Manual.Amount = '';
                                    $scope.Input_value.CC_Manual_month_cc = '';
                                    $('.logs').html('Please input card number.');
                                    $scope.checkbox.CC_Manual_check = 0;
                                    break;
                                case 'Payment_Plan':
                                    $plan++;
                                    if ($plan == $scope.ChargeDate.length) {
                                        $scope.Payment_Plan.Card_Number = '';
                                        $scope.Payment_Plan.month = '';
                                        $scope.Payment_Plan.year = '';
                                        $scope.Payment_Plan.CVV2_Codes = '';
                                        $('.log').html('Please input card number.');
                                        $scope.checkbox.Payment_Plan_check = 0;
                                    }
                                    $scope.ChargeDate[data.success[i]['value']] = {
                                        amount: '',
                                        ChargeDate: '',
                                        transaction_id: null,
                                        status: null
                                    };
                                    break;
                                case 'Prepaid':
                                    $scope.Prepaid = [];
                                    $scope.checkbox.Prepaid_check = 0;
                                    break;
                                case 'Check':
                                    $scope.Check = [];
                                    $scope.checkbox.Check_check = 0;
                                    break;
                                case 'Cash':
                                    $scope.Cash = [];
                                    $scope.checkbox.Cash_check = 0;
                                    break;
                                case 'Wells Fargo Plan':
                                    $scope.WellFargoPlan.id = data.success[i]['historyInsertedId'];
                                    break;
                                case 'Credit_Memo':
                                    $scope.Credit_Memo = {};
                                    $scope.checkbox.Credit_Memo_check = 0;
                                    break;
                                case 'Manager_Credit':
                                    $scope.Manager_Credit = {};
                                    $scope.checkbox.Manager_Credit_check = 0;
                                    break;
                                case 'Instore_Credit':
                                    $scope.Instore_Credit = {};
                                    $scope.checkbox.Instore_Credit_check = 0;
                                    break;
                            }
                        }
                    } else {
                        $cordovaToast.showLongTop(data.error[0].error);
                    }
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        } else {
            $scope.checksendBraintree = 0;
            $cordovaToast.showLongTop('Invalid card number');
        }
        $scope.paymenthistories = {};
    }
    $scope.SaveWellFargoPlan = function(formValidate) {
        if (formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.SaveWellFargoPlan($scope.WellFargoPlan).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $scope.openByGetTemplate('popupOrderInvoiceAddPaymentSignature');
                $scope.closeTarget('#popupOrderInvoiceDetailAddPaymentWellFargoPlan');
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).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.invoiceQuestion1 = 'Door';
                    $scope.Input_value.Hardware="Blank";
                    $scope.DoorForm.Hardware="Standard Hardware";
                    $('#Hardware').show();
                    $("#Struts").show();
                    $("#Radius").show();
                    $scope.labelbutton = 'Next';
                } else {
                    $scope.DoorForm.Hardware =""
                    $scope.Input_value.Hardware="";
                    if ($scope.DoorForm.Question1 == "Section Section") {
                        $scope.Input_value.invoiceQuestion1 = 'Section Set';
                    } else {
                        $scope.Input_value.invoiceQuestion1 = 'Select';
                    }
                    $('#Hardware').hide();
                    $("#Struts").hide();
                    $("#Radius").hide();
                    $scope.labelbutton = 'Search';
                }
                $scope.getdataHeight();
                $scope.getdataSection();
                $scope.getdataRadius();
                break;
            case 'Model':
                if ($scope.DoorForm.Model != '' && $scope.DoorForm.Model != undefined) {
                    $scope.DoorForm.Model == '3200' ? $scope.Constructiondata = $scope.DoorData.Construction[1] : $scope.Constructiondata = $scope.DoorData.Construction[0];
                } else {
                }
                $scope.getdataStampColor1();
                $scope.getdataHeight();
                $scope.getdataSection();
                break;
            case 'Construction':
                $scope.getdataHeight();
                $scope.getdataStampColor1();
                $scope.getdataSection();
                $scope.getdataRadius();
                break;
            case 'Width':
                $scope.getdataRadius();
                break;
            case 'Height':
                $scope.getdataRadius();
                break;
            case 'Color_1':
                $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_invoice_Color2 = true;
                    $scope.DoorForm.Color_2 = '';
                } else {
                    $scope.show_invoice_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];
                }
            }
        } else {
        }
    }
    $scope.getdataStampColor1 = function() {
        if ($scope.DoorForm.Model != '' && $scope.DoorForm.Construction != '' && $scope.DoorForm.Model != undefined && $scope.DoorForm.Construction != undefined) {
            $scope.Color_1 = $scope.DoorData.Color.Color1[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model];
            $scope.Stamp = $scope.DoorData.Stamp[$scope.DoorForm.Construction + '_' + $scope.DoorForm.Model + '_' + $scope.DoorForm.Color_1];
        } else {
        }
    }
    $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];
            }
        } else {
        }
    }
    $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').attr("required", "required");
        } else {
            $('.Radius').removeAttr('required');
        }
    }
    $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.!!!');
            return;
        };
        if (style == 'door') {
            $scope.DoorFormAddProduct();
        } else if (style == 'measurementsAdd') {
            $scope.MeasurementsAddProduct();
        } else if (style == 'measurementsEdit') {
            $scope.MeasurementsEditDoor();
        } else if (style == 'payment') {
            $scope.Add_Payment();
        } else if (style == 'transferpayment') {
            $scope.tranferPayment();
        }
    }
    $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_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("_", " ");
            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('popupOrderInvoiceMeasurements');
                        $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;
                    }
                    name = Sectionsearch + " Section | " + $scope.DoorForm.Width + "x" + $scope.DoorForm.Height + ' ' + Construction + ' ' + $scope.DoorForm.Model + ' ' + color1 + color2 + $scope.DoorForm.Stamp;
                    break;
                case 'Section Section':
                case  'Section Set':
                    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 = "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) {
                $ionicLoading.hide();
                if ($scope.actionDoor == 'search') {
                    $scope.actionDoor = 'measurements';
                }
                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('#popupOrderInvoiceMeasurements');
                                $scope.closeTarget('#popupOrderInvoiceDoorFormProductTable');
                            }
                        }]
                    });
                }
            });
        } else {
            $ionicLoading.show({
                template: templateLoading
            });

            Ordertypes.getDataProduct($scope.product_idInsert, $scope.service_id).success(function(res) {
                $ionicLoading.hide();
                var data = res.pricebook;
                $scope.show_invoice_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.id;
                      });
                      if(indexMea==-1){
                        $scope.arrMeasurements.push({ id: data.id, 'data': $scope.Measurements });
                      }else{
                        $scope.arrMeasurements[indexMea] = { id: data.id, 'data': $scope.Measurements };
                      }
                }
                $scope.searchResult = [];
                
                let index = _.findIndex($scope.listDataProducts, function(pro){
                    return pro.id == data.id;
                });
                if (index==-1) {
                    $scope.listDataProducts.push(data);
                }else{
                    $scope.listDataProducts[index] = data;
                }
                if ($scope.initialPricebookForSearch.indexOf(data.id) < 0) {
                    $scope.initialPricebookForSearch = $scope.initialPricebookForSearch.concat([data.id]);
                }
                $scope.openAutocompleteInvoice();
                $scope.closeTarget('#popupOrderInvoiceMeasurements');
                $scope.closeTarget('#popupOrderInvoiceDoorFormProductTable');
                $scope.buttonSubmit = "Check Item";
                 if (parseInt(data.message_status) > 0) {
                                $scope.openProductMessage = true;
                                $scope.productMessage = data.message;
                            } else {
                                $scope.openProductMessage = false;
                                $scope.productMessage = '';
                            }
                            if ($scope.openProductMessage) {
                                var myClass = $('#autocomplete-invoice').attr("class");
                                autocompleteClass = (myClass.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
                                $('.' + autocompleteClass).css('display', 'none');
                                $scope.openByGetTemplate('orderInvoicePopupProductMessage');
                            }
            });
        }
    }
    $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('#popupOrderInvoiceMeasurements');
                $scope.closeTarget('#popupOrderInvoiceDoorFormProductTable');
                for (var i = 0; i < $scope.invoiceData.length; i++) {
                    if ($scope.invoiceData[i].id == $scope.product_idEdit && $scope.invoiceData[i].disable != 1) {
                        if ($scope.Measurements.can_op_go_up_action == '0') {
                            $scope.Measurements.can_op_go_up = '';
                        }
                        $scope.invoiceData[i].Measurements = $scope.Measurements;
                    }
                }
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                } else {
                    $cordovaToast.showLongTop('Save Successful!');
                }
            });
        } else {
            Orderstatuses.getProducttoByname($scope.NameDoor[0] + $scope.DoorForm.Radius, 'inv').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('#popupOrderInvoiceMeasurements');
                                    $scope.closeTarget('#popupOrderInvoiceDoorFormProductTable');
                                }
                            }]
                        });
                    }
                }
            });
        }
    }
    $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() {
        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();
            $scope.Measurements.can_op_go_up = '';
            $('.can_op_go_up').find("input").removeAttr('required');
        }
    }
    $scope.previousform = function() {
        $('#DoorFormAddProduct').find("select").prop('required', true);
        if ($scope.RadiusEdit != '' || $scope.RadiusEdit != undefined) {
            openPopup('#popupMeasurementsedit');
        } else {
            if ($scope.DoorForm.Question1 == 'Door') {
                openPopup('#popupMeasurements');
            }
        }
        $('#DoorFormAddProduct').find("select").prop('required', true);
        $('#DoorFormProduct').show();
        $('#notifyDoorForm').hide();
        $('#buttons1').show();
        $('#buttons2').hide();
        $('#buttons3').hide();
        $scope.buttonSubmit = "Check Item";
    }
    $scope.refreshform = function() {
        $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.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.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.clearhistory = function() {
        $scope.checkinsertpaymenthistory = 0;
        $('.Payment_form').closest('.row').find('> div').slideUp(100);
        $('#popupAddPayment').find('input').removeAttr('required');
        $('#popupAddPayment').find('select').removeAttr('required');
        if (parseInt($scope.invoice_id) > 0) {
            $scope.check_invoice();
        }
        if (parseInt($scope.saleorder_id) > 0) {
            $scope.check_saleorder();
        }
    }
    $scope.insertPaymentHistory = function(required_form) {
        if (required_form == 2) {
            Ordertypes.insertpaymenthistories($scope.paymenthistories, $scope.ChargeDate).success(function(data) {
                if (data.length > 0) {
                    $scope.paymenthistories = {};
                    if (parseInt($scope.invoice_id) > 0) {
                        $scope.check_invoice();
                    }
                    if (parseInt($scope.saleorder_id) > 0) {
                        $scope.check_saleorder();
                    }
                    $('.Payment_form').closest('.row').find('> div').slideUp(100);
                    // openPopup('#popupSignature');
                    openPopup('#popupTerms_of_conditions');
                    // $('#popupSignature .close-title-button').remove();
                    $('#popupAddPayment').find('input').removeAttr('required');
                    $('#popupAddPayment').find('select').removeAttr('required');
                    $scope.list_paymenthistory = data;
                    $cordovaToast.showLongTop('Add Payment Successfull!');
                } else {
                    $cordovaToast.showLongTop('Add Payment Not Null!');
                }
            });
        } else {
            $cordovaToast.showLongTop('Invalid card number');
        }
    }
    $scope.required_form = function(id, action) {
        if (action == 1) {
            $('#' + id).find('input').attr("required", "true");
            $('#' + id).find('select').attr("required", "true");
        } else {
            $('#' + id).find('input').removeAttr('required');
            $('#' + id).find('select').removeAttr('required');
        }
        $('.Address_2').removeAttr('required');
    }
    $scope.replaceRes = function() {
        if ($scope.invoiceData.length > 0) {
            if ($scope.invoiceData[0].id == 0 && $scope.invoiceData[0].name == 0) {
                $scope.invoiceData = [];
            }
        }
    }
    $scope.getsignature = function(id, openSignature) {
        if (!id) {
            $scope.listpayment_child = [];
            return;
        }
        $scope.setValueSignature(id);
        Ordertypes.getSignature({
            id: id,
            from: 'app'
        }).success(function(data) {
            if (openSignature) {
                $scope.showTarget('#popupOrderInvoiceDetailPaymentInformationSignature');
            }
            if (data.Signature) {
                data.Signature = data.Signature.replace('width="300"', '').replace('height="180"', '');
            }
            $('#signaturePaymentShow').html('');
            $('#signaturePaymentShow').html(data.Signature);
            $scope.dataAfterSort = [];
            $scope.orginDataPayment = data.his_child;
            $scope.arrDayPayment = _.uniq(_.pluck($scope.orginDataPayment, 'dateToSort'));
            _.each($scope.arrDayPayment, function(value) {
                $scope.createdDatePayment = value;
                $scope.paymentByDay = _.where($scope.orginDataPayment, {
                    dateToSort: $scope.createdDatePayment
                });
                _.each($scope.paymentByDay, function(value) {
                    _.extend(value, {
                        timeToSort: moment(value.created_date).format('HH:mm:ss')
                    });
                });
                $scope.oldTimeToSort = '';
                $scope.paymentByDay = _.sortBy($scope.paymentByDay, 'timeToSort');
                _.each($scope.paymentByDay, function(value) {
                    if ($scope.oldTimeToSort == value.timeToSort) {
                        _.extend(value, {
                            showSignature: false
                        });
                    } else {
                        _.extend(value, {
                            showSignature: true
                        });
                    }
                    $scope.oldTimeToSort = value.timeToSort;
                });
                $scope.dataAfterSort.push({
                    date: $scope.createdDatePayment,
                    payment: $scope.paymentByDay
                })
            });
            $scope.listpayment_child = $scope.dataAfterSort;
            if ($scope.listpayment_child.length > 0) {
                $('#list-payment-history').css('display', 'none');
            }
            !$scope.check_init_invoice ? $interval($scope.checkLogin, time_refresh) : '';
            request_notify_get_chat = true;
            $scope.check_init_invoice = true;
        });
    }
    $scope.popupSignature = function() {
    }
    $scope.clearSignature = function() {
        signaturePad.clear();
    }
    $scope.insertSignature = function() {
        if (signaturePad.isEmpty()) {
            $cordovaToast.showLongTop('Signature Not Null!');
            return;
        }
        var signImg = atob(signaturePad.toDataURL('image/svg+xml').split(',')[1]);
        var sign = signImg + '';
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.insertSignature($scope.list_paymenthistory, sign).success(function(data) {
            $ionicLoading.hide();
            if (parseInt($scope.invoice_id) > 0) {
                $scope.check_invoice();
            }
            if (parseInt($scope.saleorder_id) > 0) {
                $scope.check_saleorder();
            }
            if (data.status) {
                $('#signaturePaymentShow').html('');
                $('#signaturePaymentShow').html(data);
                $scope.list_paymenthistory = {};
                $scope.historyDate = '';
                $scope.list_paymenthistory = [];
                $scope.closeTarget('#popupAddPaymentMulti');
                $scope.closeTarget('#popupOrderInvoiceAddPaymentSignature');
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.Terms_of_conditions = function(acceptLicense) {
        if (!acceptLicense) {
            $ionicScrollDelegate.$getByHandle('scrollPaymentLicense').scrollBottom();
            $cordovaToast.showLongTop('Please agree with terms and condition above.!!!');
            return;
        }
        $scope.bill = '';
        $scope.checkshowcaculator = 0;
        $scope.openByGetTemplate('invoicePaymentAddPayment');
    }
    $scope.deleteDataPricebook = {};
    $scope.deleteConfirmInvoice = function(item) {
        $scope.openByGetTemplate('popupOrderInvoiceDetailItemDelete');
        $scope.deleteDataPricebook = item;
    }
    $scope.deleteInvoice = function(item) {
        var idx = _.findLastIndex($scope.invoiceData, {
            id: item.id
        });
        $scope.invoiceData.splice(idx, 1);
        $scope.closeTarget('#popupOrderInvoiceDetailItemDelete');
        $scope.resizeScroll('scrollInvoiceDetail');
        $scope.change_price($scope.invoiceData);
    }
    $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[1].check) {
                    $scope.addItem = data.jsondata[index].child[1].child[0].check;
                    $scope.showDeleteItem = data.jsondata[index].child[1].child[1].check;
                    $scope.showSoldInstallDeclined = data.jsondata[index].child[1].child[2].check;
                    $scope.showEditAddComment = data.jsondata[index].child[1].child[3].check;
                    $scope.showNewDoorForm = data.jsondata[index].child[1].child[4].check;
                    $scope.templateData.showNewDoorForm = $scope.showNewDoorForm;
                    $scope.showSentTo = data.jsondata[index].child[1].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.showAddPayment = data.jsondata[index].child[1].child[6].check;
                    $scope.showTransferPayment = data.jsondata[index].child[1].child[7].check;
                    $scope.showRevertToEstimate = data.jsondata[index].child[1].child[8].check;
                    $scope.showRefund = data.jsondata[index].child[1].child[9].check;
                    $scope.showCouponDropDown = data.jsondata[index].child[1].child[10].check;
                    $scope.showChangeMd = data.jsondata[index].child[1].child[11].check;
                    $scope.isOverage20Payment = data.jsondata[index].child[1].child[6].child[2].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 (parseInt($scope.invoice_id) > 0) {
                        $scope.check_invoice();
                    }
                    if (parseInt($scope.saleorder_id) > 0) {
                        $scope.check_saleorder();
                    }
                } else {
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                }
            }
        });
    }
    $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 {
                if (parseInt($scope.invoice_id) > 0) {
                    $scope.check_invoice();
                }
                if (parseInt($scope.saleorder_id) > 0) {
                    $scope.check_saleorder();
                }
            }
        });
    }
    // edit by haudao
    $scope.filterInvoiceProduct = function(query, isInitializing) {}
    $scope.onInvoiceSelectProduct = function(callback) {}
    $scope.onInvoiceRemoveProduct = function(callback) {
    }
    $scope.addInvEmail = function() {
        $scope.AdvancedEmail.emails.push({
            text: ''
        });
    }
    $scope.removeInvEmail = function(idx) {
        if ($scope.AdvancedEmail.emails.length > 1) $scope.AdvancedEmail.emails.splice(idx, 1);
    }
    $scope.invoiceAutocompleteList = {};
    $scope.newquery = '';
    $scope.isprogress = false;
    $scope.filterAutocomplete = function(query, isInitializing, type) {
        var listProductId = _.pluck($scope.invoiceData, 'id');
        $('#autocomplete-invoice .none-result').css('display', 'none');
        switch (type) {
            case 'invPro':
                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);
                                            }
                                        });
                                    }
                                    $ionicLoading.hide();
                                    if (returnValue.items.length > 0) {
                                        $('#autocomplete-invoice .none-result').css('display', 'none');
                                    } else {
                                        $('#autocomplete-invoice .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-invoice .none-result').css('display', 'none');
                        } else {
                            $('#autocomplete-invoice .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-invoice .none-result').css('display', 'none');
                    } else {
                        $('#autocomplete-invoice .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.invoiceAutocompleteList.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);
                        }
                    }
                });
                $ionicLoading.hide();
                return returnValue;
                break;
            case 'customerTransfer':
                $ionicLoading.show({
                    template: templateLoading
                });
                var returnValue = {
                    items: []
                };
                if (query.length > 0) {
                    var params = {
                        search: query
                    };
                    Customers.getSelect2(params).success(function(data) {
                        $ionicLoading.hide();
                        $scope.rootDataCustomer = data;
                        $scope.rootDataCustomer.forEach(function(item) {
                            item.fullName = item.first_name + ' ' + item.last_name + ' ' + item.street + ' ' + item.phone;
                        })
                        $scope.rootDataCustomer.forEach(function(item) {
                            if (item.fullName.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                                returnValue.items.push(item);
                            } else if (item.id.indexOf(query) > -1) {
                                returnValue.items.push(item);
                            } else if (replaceAllPhone(item.phone).indexOf(replaceAllPhone(query)) > -1) {
                                returnValue.items.push(item);
                            }
                        });
                    })
                } else {
                    $ionicLoading.hide();
                }
                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, type) {
        $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, 'multi');
        }
        $scope.initialPricebookForSearch = [];
    }
    $scope.dataInsertProducts = [];
    $scope.onSelectAutocomplete = function(callback, type) {
        switch (type) {
            case 'invPro':
                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-invoice').attr("class");
                                autocompleteClass = (myClass.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
                                $('.' + autocompleteClass).css('display', 'none');
                                $scope.openByGetTemplate('orderInvoicePopupProductMessage');
                            }
                        }
                        $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;
            case 'customerTransfer':
                $scope.dataSearchCustomer.customer = callback.item;
                $scope.Input_value.displayCustomer = callback.item.name;
                $scope.selectCustomer(callback.item.id);
                break;
        }
    }
    $scope.calculatorPrice = function(items) {
        switch (parseInt($scope.service_id)) {
            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 'invPro':
                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 'invPro':
                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.styleOfMeasurement = "Add";
    $scope.setValueServiceLocation = function(id, type) {
        if ($scope.jobsitedata.length > 0) {
            $scope.newJobsite_id = id;
            $scope.Input_value.serviceLocation = "Billing Address";
            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('#popupOrderInvoiceDetailServiceLocation');
            }
            $scope.disableApply = false;
        } else {
            $scope.disableApply = true;
        }
    }
    $scope.changeServiceLocation = function(id) {
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        Orderstatuses.changeServiceLocation(id, order_id).success(function(data) {
            $scope.setValueServiceLocation(id, '');
        });
    }
    $scope.updateServiceLocation = function() {
        $scope.setValueServiceLocation($scope.newJobsite_id, 'changeInput');
    }
    $scope.setValueSignature = function(id) {
        $scope.Input_value.signature = "";
        var index = _.findLastIndex($scope.listpayment_histories, {
            id: id
        });
        if (index >= 0) $scope.Input_value.signature = $scope.listpayment_histories[index].created_date;
    }
    $scope.$on('invoiceDetail', function(event, args) {
        delete $scope.saleorder_id;
        $scope.invoice_id = args.invoice_id;
        $scope.redirectFromAppointment_Inv = args.redirectFromAppointment;
        $scope.allAppointmentHistoryData.length = args.countAppHistories;
        $scope.getUserLogin();
    });
    $scope.$on('saleorderDetail', function(event, args) {
        delete $scope.invoice_id;
        $scope.arrMeasurements = [];
        $scope.saleorder_id = args.saleorder_id;
        $scope.redirectFromAppointment_Inv = args.redirectFromAppointment;
        $scope.allAppointmentHistoryData.length = args.countAppHistories;
        $scope.getUserLogin();
    });
    $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.editInvoice = function(product_id, index, item_id) {
        $scope.invoiceDataEdit = {
            product_id: product_id,
            index: index,
            name: $scope.invoiceData[index].name,
            quantity: $scope.invoiceData[index].quantity,
            Extended: $scope.invoiceData[index].Extended,
            sold: $scope.invoiceData[index].sold,
            installed: $scope.invoiceData[index].installed,
            declined: $scope.invoiceData[index].declined,
            disable: $scope.invoiceData[index].disable,
            item_id: item_id,
            Warranty: {
                id: $scope.invoiceData[index].warranty_id.toString(),
                name: $scope.invoiceData[index].warranty_name
            }
        };
        $scope.updateInvoiceData($scope.invoiceDataEdit);
    }
    $scope.updateInvoiceData = function(data) {
        $scope.invoiceData[data.index].Extended = data.Extended;
        $scope.invoiceData[data.index].declined = data.declined;
        $scope.invoiceData[data.index].sold = data.sold;
        $scope.invoiceData[data.index].installed = data.installed;
        $scope.invoiceData[data.index].quantity = data.quantity;
        $scope.invoiceData[data.index].warranty_id = data.Warranty.id;
        $scope.invoiceData[data.index].warranty_name = data.Warranty.name;
        $scope.change_price($scope.invoiceData);
    }
    $scope.openIonicPopup = function(templateUrl, title) {
        return $ionicPopup.show({
            templateUrl: templateUrl,
            title: title,
            scope: $scope,
            buttons: [{
                text: 'Cancel'
            }]
        })
    }
    $scope.set_month = function(value, type) {
        var index = _.findLastIndex($scope.monthNames, {
            value: parseInt(value)
        });
        if (index >= 0) {
            if (type == 'manual') {
                $scope.Input_value.CC_Manual_month_cc = $scope.monthNames[index].name;
            }
            if (type == 'plan') {
                $scope.Input_value.Payment_Plan_month = $scope.monthNames[index].name;
            }
        }
    }
    // end edit
    $scope.checkReverToEstimate = function() {
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.checkReverToEstimate({
            id: order_id
        }).success(function(data) {
            if (!data.status) {
                $ionicLoading.hide();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $scope.getOrders();
                $cordovaToast.showLongTop(data.msg);
                setTimeout(function() {
                    $scope.setTabOrder('Estimate');
                    $scope.goToEstimateDetails(data.id, data.old_est_no);
                }, 200);
            }
        });
    };
    $scope.selectCustomer = function(cusId) {
        $ionicLoading.show({
            template: templateLoading
        });
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        Ordertypes.getInvoiceByCustomerId({
            customerId: cusId,
            order_id: order_id
        }).success(function(data) {
            $ionicLoading.hide();
            $scope.dataInvoice = data;
        });
    };
    $scope.selectPayment = function(id) {
        $scope.dataTranferPayment.paymentId = id;
        $scope.openByGetTemplate('popupOrderInvoiceDetailPaymentInformationTranferPayment');
    };
    $scope.setValueForInput = function(id, type) {
        switch (type) {
            case 'invoiceToTransfer':
                if (_.where($scope.dataInvoice, {
                        id: id
                    }).length) {
                    $scope.Input_value.invoice_no = _.where($scope.dataInvoice, {
                        id: id
                    })[0].invoice_no;
                } else {
                    $scope.Input_value.invoice_no = '';
                }
                break;
        }
    };
    $scope.formatTimePayment = function(date) {
        return moment(date).format('h:mm A');
    };
    $scope.tranferPayment = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.tranferPayment($scope.dataTranferPayment).success(function(data) {
            $ionicLoading.hide();
            if (data.status) {
                $cordovaToast.showLongTop(data.msg);
                $scope.closeTarget('#popupOrderInvoiceDetailPaymentInformationTranferPayment');
                $scope.closeTarget('#popupOrderInvoiceDetailPaymentInformation');
                $scope.dataTranferPayment = {};
                if (parseInt($scope.invoice_id) > 0) {
                    $scope.getInvoice('');
                }
                if (parseInt($scope.saleorder_id) > 0) {
                    $scope.getSaleorder('');
                }
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };
    $scope.updateMD_Coupon_Refund = function(MDValue, couponName, refund) {
        if (couponName != undefined && couponName.length > 0) {
            var findCoupon = _.findWhere($scope.coupon, {
                name: couponName
            });
            $scope.change_coupon(findCoupon.id);
        } else {
            $scope.change_coupon('');
        }
        if (MDValue != undefined) {
            angular.forEach($scope.invoiceData, function(item) {
                if (parseInt(item.disable) != 1) item.Extended = parseFloat(MDValue);
            })
            $scope.change_price($scope.invoiceData);
        }
        if (refund != undefined && parseInt(refund) > 0) {
            $scope.refund.value = parseInt(refund);
            $scope.change_price($scope.invoiceData);
        }
        $cordovaToast.showLongTop('Changes are applied to invoice. Please SAVE invoice.');
        $scope.closeTarget('#popupOrderInvoiceDetailDiscountCoupon');
    }
    $scope.linkToEstimateInvoiceDetail = function(item) {
        if ($scope.invoice_no != item.invoice_no) {
            switch (item.ordertype_id) {
                case '4':
                    $scope.closeTarget('#popupOrderInvoiceDetailEstimateInvoice');
                    $scope.closeTarget('#popupOrderInvoiceDetail');
                    setTimeout(function() {
                        $scope.setTabOrder('Estimate');
                        $scope.goToEstimateDetails(item.id, item.invoice_no);
                    }, 200);
                    break;
                case '5':
                    $scope.closeTarget('#popupOrderInvoiceDetailEstimateInvoice');
                    $scope.closeTarget('#popupOrderInvoiceDetail');
                    setTimeout(function() {
                        $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 'change_coupon':
                $scope.Input_value.couponData = $scope.setValueInput(id, $scope.coupon);
                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;
        }
    }
    $scope.showPaymentHistory = function() {
        if ($scope.listpayment_histories.length > 0) {
            $('#list-payment-history').toggle();
        }
    }
    $scope.hideRevertEstimate = function() {
        switch ($scope.roleName) {
            case $scope.isSalesman:
                return true;
                break;
            case $scope.isFieldinstaller:
                return true;
                break;
            case $scope.isAdmin:
                return false;
                break;
            case $scope.isManager:
                return false;
                break;
            case $scope.isReporter:
                return true;
                break;
            case $scope.isScheduler:
                return true;
                break;
            case $scope.isWarehouse:
                return true;
                break;
            case $scope.isStrategicDevelopment:
                return false;
                break;
            case $scope.isSupportAssistant:
                return true;
                break;
            case $scope.isOutsideSales:
                return true;
                break;
            case $scope.isInFieldSupervisor:
                return true;
                break;
        }
    }
    $scope.hideTranferPayment = function() {
        switch ($scope.roleName) {
            case $scope.isSalesman:
                return true;
                break;
            case $scope.isFieldinstaller:
                return true;
                break;
            case $scope.isAdmin:
                return false;
                break;
            case $scope.isManager:
                return false;
                break;
            case $scope.isReporter:
                return true;
                break;
            case $scope.isScheduler:
                return true;
                break;
            case $scope.isWarehouse:
                return true;
                break;
            case $scope.isStrategicDevelopment:
                return false;
                break;
            case $scope.isSupportAssistant:
                return true;
                break;
            case $scope.isOutsideSales:
                return true;
                break;
            case $scope.isInFieldSupervisor:
                return true;
                break;
        }
    }
    $scope.showMD_edit = function() {
        switch ($scope.roleName) {
            case $scope.isSalesman:
                return false;
                break;
            case $scope.isFieldinstaller:
                return false;
                break;
            case $scope.isAdmin:
                return true;
                break;
            case $scope.isManager:
                return true;
                break;
            case $scope.isReporter:
                return false;
                break;
            case $scope.isScheduler:
                return false;
                break;
            case $scope.isWarehouse:
                return false;
                break;
            case $scope.isStrategicDevelopment:
                return false;
                break;
            case $scope.isSupportAssistant:
                return false;
                break;
            case $scope.isOutsideSales:
                return false;
                break;
            case $scope.isInFieldSupervisor:
                return false;
                break;
        }
    }
    $scope.editInvoiceItemInstalled = function(product_id, index, item_id) {
        $scope.openByGetTemplate('invoicePopupDetailEditMDInstalledItem');
        $scope.invoiceDataEdit = {
            product_id: product_id,
            index: index,
            name: $scope.invoiceData[index].name,
            quantity: $scope.invoiceData[index].quantity,
            Extended: $scope.invoiceData[index].Extended,
            sold: $scope.invoiceData[index].sold,
            installed: $scope.invoiceData[index].installed,
            declined: $scope.invoiceData[index].declined,
            disable: $scope.invoiceData[index].disable,
            item_id: item_id,
            Warranty: {
                id: $scope.invoiceData[index].warranty_id.toString(),
                name: $scope.invoiceData[index].warranty_name
            }
        };
    }
    $scope.clearDataAndOpenAutoComplete = function() {
        $scope.initialPricebookForSearch = [];
        $scope.openAutocompleteInvoice();
    }
    $scope.getCornerstyles = function() {
        if (!$scope.cornerstyles || $scope.cornerstyles.length == 0) {
            Orderstatuses.getCornerstyles().success(function(data) {
                $scope.cornerstyles = data;
            });
        }
    }
    $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.closeFormReopenAutocomplete = function() {
        $scope.closeTarget('#orderInvoicePopupProductMessage');
        $scope.openAutocompleteInvoice();
    }
    $scope.openAutocompleteInvoice = function() {
        var myClassInvoice = $('#autocomplete-invoice').attr("class");
        var invoiceAutocompleteClass = (myClassInvoice.replace('modal', '').replace('ion-autocomplete-container', '')).trim();
        if (invoiceAutocompleteClass != undefined) {
            $('.' + invoiceAutocompleteClass).css('display', 'block');
        }
        var ionAutocompleteElement = document.getElementsByClassName('ion-autocomplete-invoice');
        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.invoiceDataOnSelectAll = angular.copy($scope.invoiceData);
        $scope.openByGetTemplate('popupSelectAllItemInvoice');
    };
    $scope.selectAllItems = function(value, type) {
        if (type == 'sold') {
            _.each($scope.invoiceDataOnSelectAll, function(item) {
                if (item.declined == 0 && item.disable == 0) item.sold = value
            });
        }
        if (type == 'install') {
            _.each($scope.invoiceDataOnSelectAll, function(item) {
                if (item.sold == 1 && item.disable == 0) item.installed = value
            });
        }
        if (type == 'declined') {
            _.each($scope.invoiceDataOnSelectAll, function(item) {
                if (item.sold == 0 && item.disable == 0) item.declined = value
            });
        }
    }
    $scope.appplySelectAllInvoice = function() {
        _.each($scope.invoiceDataOnSelectAll, function(item_form) {
            _.each($scope.invoiceData, function(item_root) {
                if (parseInt(item_form.id) == parseInt(item_root.id)) {
                    item_root.declined = item_form.declined;
                    item_root.sold = item_form.sold;
                    item_root.installed = item_form.installed;
                }
            });
        });
        $scope.change_price($scope.invoiceData);
        $scope.closeTarget('#popupSelectAllItemInvoice');
        $scope.Save_Invoice();
    }
    $scope.open_door_form_product_table = function() {
        $scope.openByGetTemplate('popupOrderInvoiceDoorFormProductTable');
    };
    $scope.converttoinvoice = function(saleorder_id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Saleorder.convertToInvoice(saleorder_id).success(function(data) {
            if (data.status) {
                delete $scope.saleorder_id;
                $scope.invoice_id = saleorder_id;
                $scope.goToInvoiceDetails(saleorder_id);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    }
    $scope.reverttosaleorder = function(invoice_id) {
        $ionicLoading.show({
            template: templateLoading
        });
        Ordertypes.reverttosaleorder({
            order_id: invoice_id
        }).success(function(data) {
            if (data.status) {
                delete $scope.invoice_id;
                $scope.saleorder_id = invoice_id;
                $scope.goToSaleorderDetails(invoice_id);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };
    $scope.Terms_of_conditions = function() {
        $scope.amount_payment_instorecredit = 0;
        $scope.closeTarget('#popupOrderInvoiceTermsOfConditions');
        if ($scope.total_instore_credit > 0) {
            $scope.amount_payment_instorecredit = parseFloat($scope.totalend) > parseFloat($scope.total_instore_credit) ? parseFloat($scope.total_instore_credit) : parseFloat($scope.totalend);
            $scope.openByGetTemplate('popupConfirmAddPaymentInstoreCredit');
        } else {
            $scope.openByGetTemplate('popupOrderInvoiceDetailAddPayment');
        }
    }
    $scope.declineCreatePaymentWithInstoreCredit = function() {
        $scope.closeTarget('#popupConfirmAddPaymentInstoreCredit');
        $scope.openByGetTemplate('popupOrderInvoiceDetailAddPayment');
    }
    $scope.createPaymentWithInstoreCredit = function() {
        $scope.closeTarget('#popupConfirmAddPaymentInstoreCredit');
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        $scope.paymenthistories.Instore_Credit = {};
        $scope.paymenthistories.Instore_Credit.amount = $scope.amount_payment_instorecredit;
        $scope.paymenthistories.Instore_Credit.method = 'In Store Credit';
        $scope.paymenthistories.Instore_Credit.order_id = order_id;
        $scope.payment_sum_amount = $scope.amount_payment_instorecredit;
        $scope.paymenthistories.invoiceId = order_id;
        $scope.paymenthistories.checkinsertpaymenthistory = $scope.checkinsertpaymenthistory;
        $scope.paymenthistories.date = $scope.historyDate;
        $scope.createBraintree($scope.paymenthistories, 2);
    }
    $scope.checkUseCreditCard = function(is_check) {
        if (is_check == 1) {
            $('#required_CC_Manual').val(1);
            $scope.CC_Manual.card_number = $scope.creditcard_info.card_number;
            $scope.CC_Manual.month_cc = parseInt($scope.creditcard_info.expired_month);
            $scope.CC_Manual.year_cc = parseInt($scope.creditcard_info.expired_year);
            $scope.CC_Manual.CVV2_Code = '***';
            $scope.set_month($scope.CC_Manual.month_cc, 'manual');
        } else {
            $('#required_CC_Manual').val(0);
            $scope.CC_Manual.card_number = '';
            $scope.CC_Manual.month_cc = '';
            $scope.CC_Manual.year_cc = '';
            $scope.CC_Manual.CVV2_Code = '';
        }
    };
    $scope.checkInstoreCredit = function(amount) {
        if (amount > $scope.total_instore_credit) {
            return $scope.Instore_Credit.Amount = 0;
        }
    };
    $scope.resetCheckFormPayment = function() {
        $scope.Cash_check = 0;
        $scope.Wells_Fargo_Plan = 0;
        $scope.Check_check = 0;
        $scope.CC_Manual_check = 0;
        $scope.checkbox.Credit_Memo_check = 0;
        $scope.checkbox.Manager_Credit_check = 0;
        $scope.checkbox.Instore_Credit_check = 0;
        $scope.checkbox.use_credit_card_check = 0;
        $scope.checkbox.add_this_card = 0;
        $scope.checkbox.update_this_card = 0;
    };
    $scope.showWarning = function(is_check) {
        if (is_check == 1) {
            $scope.openByGetTemplate('popupWarningAddUpdateCard');
        }
    };
    $scope.noConfirmOverPayment = function() {
        $scope.checksendBraintree = 0;
        $scope.closeTarget('#confirmOverPayment');
        $cordovaToast.showLongTop('Please get correct payment amount or confirm RGD credit amount with customer.');
    };
    $scope.selectService = function(sevice, Option) {
        $scope.Service = sevice;
        if (Option != '') {
            $scope.OptionService = Option;
        }
        if (sevice == 6) {
            $scope.StoreLocation = $scope.store_location ? $scope.store_location : 'Burnsville';
            _.each($scope.invoiceData, function(item) {
                item.installed = 0;
                return item;
            })
        } else {
            $scope.StoreLocation = null;
        }
    }
    $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.selectStoreLocation = function(value) {
        $scope.StoreLocation = value;
    }
    $scope.$on('updateinvoicebeforesentmail', function(event, args) {
        $ionicLoading.show({
            template: templateLoading
        });
        var data_invoice = {};
        var duedate = moment($scope.duedate.value).format('YYYY-MM-DD');
        if (duedate == "Invalid date") duedate = $scope.duedate.value;
        if (parseInt($scope.invoice_id) > 0) {
            var order_id = $scope.invoice_id;
        }
        if (parseInt($scope.saleorder_id) > 0) {
            var order_id = $scope.saleorder_id;
        }
        data_invoice.invoiceData = $scope.invoiceData;
        data_invoice.Discount = $scope.Discount;
        data_invoice.Subtotal = $scope.Subtotal;
        data_invoice.id = order_id;
        data_invoice.user_id = $scope.currentIdLogin;
        data_invoice.refund = $scope.refund.value;
        data_invoice.total = $scope.total;
        data_invoice.duedate = duedate;
        data_invoice.couponprice = $scope.couponprice;
        data_invoice.coupon_id = $scope.couponData;
        data_invoice.store_location = $scope.StoreLocation;
        data_invoice.service_id = $scope.service_id;
        Ordertypes.save(data_invoice).success(function(data) {
            if (parseInt($scope.invoice_id) > 0) {
                $scope.getInvoice('');
            }
            if (parseInt($scope.saleorder_id) > 0) {
                $scope.getSaleorder('');
            }
            $scope.getOrders();
            $ionicLoading.hide();
            if (data.status) {
                //$cordovaToast.showLongTop(data.msg);
                $scope.$emit('estimateinvoiceupdatesuccess', {
                    type: args.type,
                    order_id: order_id
                });
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    });
})