﻿var CommonDirectiveService = angular.module('CommonDirectiveService', ['common', 'ngIdle']);
CommonDirectiveService.directive('onlyDigits', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attr, ctrl) {
            var keyCode = [8, 9, 13, 37, 39, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
            element.bind("keydown", function (event) {
                if ($.inArray(event.which, keyCode) == -1) {
                    scope.$apply(function () {
                        scope.$eval(attr.onlyNum);
                        event.preventDefault();
                    });
                    event.preventDefault();
                }
            });
        }
    };
});

CommonDirectiveService.directive("passwordVerify", function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, model) {
            scope.$watch(attrs.passwordVerify, function (value) {
                if (model.$viewValue !== undefined && model.$viewValue !== '') {
                    model.$setValidity('passwordVerify', value === model.$viewValue);
                }
            });
            model.$parsers.push(function (value) {
                if (value === undefined || value === '') {
                    model.$setValidity('passwordVerify', true);
                    return value;
                }
                var isValid = value === scope.$eval(attrs.passwordVerify);
                model.$setValidity('passwordVerify', isValid);
                return isValid ? value : undefined;
            });
        }
    };
});

/******************** Input Masking TIN ************************/
CommonDirectiveService.directive('tinNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, controller) {
            element.inputmask({ mask: "[99-9999999]", greedy: false, "placeholder": "", "autoUnmask": true });
        }
    };
});

/************************************************************ Input Masking SSN************************************************/

CommonDirectiveService.directive('ssnNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, controller) {
            element.inputmask({ mask: "[999-99-9999]", greedy: false, "placeholder": "" });
        }
    };
});

CommonDirectiveService.directive('taxNumber', ['$compile', function ($compile) {
    return {
        require: 'ngModel',
        transclude: true,
        replace: true,
        restrict: 'A',
        link: function (scope, element, attrs, controller) {
            angular.element('#personalDetails').scope().$on('sendTaxCode', function (e, value) {
                if (value == "T") {
                    scope.formData.TaxId = null;
                    attrs.$set('tinNumber', true);
                    attrs.$set('ssnNumber', null);
                    $compile(element)(scope);

                } else {
                    scope.formData.TaxId = null;
                    attrs.$set('ssnNumber', true);
                    attrs.$set('tinNumber', null);
                    $compile(element)(scope);
                }
            });
        }
    }
}]);

/******************** Input Masking ZIP Code ************************/

CommonDirectiveService.directive('zipCode', ['$compile', function ($compile) {
    return {
        require: 'ngModel',
        replace: true,
        restrict: 'A',

        link: function (scope, element, attrs, controller) {
            scope.$on('sendCountryCode', function (e, value) {
                if (value == "CA") {
                    scope.formData.Zip = null;
                    attrs.$set('zipCa', true);
                    attrs.$set('zipCode', null);
                    $compile(element)(scope);

                } else if (value == "US") {
                    scope.formData.Zip = null;
                    attrs.$set('zipUs', true);
                    attrs.$set('zipCode', null);
                    attrs.$set('zipCa', null);
                    $compile(element)(scope);

                } else {
                    element.inputmask('remove');
                    scope.formData.Zip = null;
                    attrs.$set('zipCode', true);
                    attrs.$set('zipCa', null);
                    attrs.$set('zipUs', null);
                    $compile(element)(scope);
                }
            });
        }
    }
}]);

CommonDirectiveService.directive('dateLowerThan', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateDateRange = function (inputValue) {
                var fromDate = $filter('date')(inputValue, 'short');
                var toDate = $filter('date')(attrs.dateLowerThan, 'short');
                var isValid = isValidDateRange(fromDate, toDate);
                ctrl.$setValidity('dateLowerThan', isValid);
                return inputValue;
            };

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateLowerThan', function () {
                validateDateRange(ctrl.$viewValue);
            });
        }
    };
}]);

CommonDirectiveService.directive('dateGreaterThan', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateDateRange = function (inputValue) {
                var fromDate = $filter('date')(attrs.dateGreaterThan, 'short');
                var toDate = $filter('date')(inputValue, 'short');
                var isValid = isValidDateRange(fromDate, toDate);
                ctrl.$setValidity('dateGreaterThan', isValid);
                return inputValue;
            };

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateGreaterThan', function () {
                validateDateRange(ctrl.$viewValue);

            });
        }
    };
}]);

CommonDirectiveService.directive('dateLowerThan2', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateDateRange = function (inputValue) {
                var fromDate = $filter('date')(inputValue, 'short');
                var toDate = $filter('date')(attrs.dateLowerThan2, 'short');
                if (toDate == undefined)
                    return inputValue;
                var isValid = isValidDateRange(fromDate, toDate);
                ctrl.$setValidity('dateLowerThan2', isValid);
                return inputValue;
            };

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateLowerThan2', function () {
                validateDateRange(ctrl.$viewValue);
            });
        }
    };
}]);

CommonDirectiveService.directive('dateGreaterThan2', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateDateRange = function (inputValue) {
                var fromDate = $filter('date')(attrs.dateGreaterThan2, 'short');
                var toDate = $filter('date')(inputValue, 'short');
                if (toDate == undefined)
                    return inputValue;
                var isValid = isValidDateRange(fromDate, toDate);
                ctrl.$setValidity('dateGreaterThan2', isValid);
                return inputValue;
            };

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateGreaterThan2', function () {
                validateDateRange(ctrl.$viewValue);

            });
        }
    };
}]);

CommonDirectiveService.directive('dateEqualsYear', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validateDateRange = function (inputValue) {
                var date = $filter('date')(inputValue, 'short');
                var year = attrs.dateEqualsYear;

                // get full year
                var datedate = new Date(date);
                var yearFromdate = datedate.getFullYear();

                var isValid = false;
                if (year == yearFromdate) {
                    isValid = true;
                }
                ctrl.$setValidity('dateEqualsYear', isValid);
                return inputValue;
            };

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateEqualsYear', function () {
                validateDateRange(ctrl.$viewValue);
            });
        }
    };
}]);



var isValidDate = function (dateStr) {
    if (dateStr == undefined)
        return false;
    var dateTime = Date.parse(dateStr);

    if (isNaN(dateTime)) {
        return false;
    }
    return true;
};

var getDateDifference = function (fromDate, toDate) {
    return Date.parse(toDate) - Date.parse(fromDate);
};

var isValidDateRange = function (fromDate, toDate) {
    if (fromDate == "" || toDate == "")
        return true;
    if (isValidDate(fromDate) == false) {
        return false;
    }
    if (isValidDate(toDate) == true) {
        var days = getDateDifference(fromDate, toDate);
        if (days < 0) {
            return false;
        }
    }
    return true;
};

/************************************************************ Customer Lookup Start********************************************/
CommonDirectiveService.directive('customerlookupDirective', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName",
        template: '<div ng-include="contentUrl"></div>'
    }
}).controller('CustomerGridCtrl', ['$scope', '$http', 'myGrid', 'appConfig', 'viewModelHelper', '$routeParams',
    'validationMsg', 'validationPatterns', '$q', 'Messages', 'commonUtils', 'commonDataService',
    function ($scope, $http, myGrid, appConfig, viewModelHelper, $routeParams, validationMsg, validationPatterns, $q, Messages,
        commonUtils, commonDataService) {
        $scope.ControllerName = '';
        $scope.ViewModelName = '';
        $scope.DivId = '';
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        $scope.IsCustomerRoleDisabled = false;
        $scope.dateRegex = validationPatterns.dateRegex;
        $scope.createBtnShow = false;
        $scope.formData = {
            Id: '',
            CustomerName: '',
            City: '',
            State: '',
            Country: 'US',
            Zip: '',
            Phone: '',
            IsShowPersonnelPrimaryContact: false
        };

        $scope.BindCustomerIdDetails = function (controllerName, viewModal, divId) {
            //Don't rename view model from Calling page.
            validationMsg.clear();
            $scope.createBtnShow = false;
            validationMsg.showLookupMessage(false);
            $scope.formData = {
                Id: '',
                CustomerName: '',
                City: '',
                State: '',
                Country: 'US',
                Zip: '',
                Phone: '',
                CustomerRole: '',
                IsShowPersonnelPrimaryContact: false
            };
            $scope.IsCustomerRoleDisabled = false;
            if (viewModal == 'JudgeSearchViewModel') {
                $scope.formData.CustomerRole = 'JUD';
                $scope.IsCustomerRoleDisabled = true;
            }

            if (viewModal == "SearchAffiliateViewModel") {
                $scope.formData.CustomerRole = "AFF";
                $scope.IsCustomerRoleDisabled = true;
            }
            //Fix Issue no. EQ-3155
            if (viewModal == "searchLookupViewModel") {
                $scope.formData.IsShowPersonnelPrimaryContact = true;
            }

            $scope.gridShow = false;
            $scope.ControllerName = controllerName;
            $scope.ViewModelName = viewModal;
            $scope.DivId = divId;
            $scope.formData.Id = angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName].CustomerId;
            $scope.gridOptions.noRecord = false;
            viewModelHelper.ShowPopup(divId, "Customer Lookup", 1200, 'auto')
        };

        $scope.master = {};
        $scope.gridShow = false;
        $scope.gridOptions = myGrid.gridOptions;
        $scope.edit = myGrid.edit;
        $scope.jumpToPage = myGrid.jumpToPage;

        /*Below two line to selection of row */
        $scope.gridOptions.enableRowHeaderSelection = false;
        $scope.gridOptions.multiSelect = false;
        $scope.customerID = {};
        $scope.customerName = {};
        $scope.customerData = {};
        $scope.currentPageSize;
        $scope.currentPageNo;
        //Below line Commented by Vivek another loading getting close
        //viewModelHelper.ShowProgress();


        $scope.CountryReq = $http({
            method: 'Get', url: appConfig.apiPath + 'LookupMaster/GetCountry', headers: { "Authorization": "Bearer " + commonUtils.readCookie("accessToken") },
        }).success(function (data, status, headers, config) {
            $scope.country = data;
        }).error(function (data, status, headers, config) {
            validationMsg.error([Messages.InternalServerError]);
            validationMsg.showLookupMessage(true);
        });



        $q.all([$scope.ActiveStatusReq, $scope.CountryReq, $scope.CustTypeReq, $scope.CustRoleTypeReq, $scope.GenderTypeReq]).then(function (values) {
            //Below line Commented by Vivek another loading getting close
            //viewModelHelper.CloseProgress(); 
        });

        if ($routeParams.customerId != null && $routeParams.customerId != '') {
            $scope.formData.Id = $routeParams.customerId;
        }

        function createColumnForCustomerLookupGrid() {
            $scope.gridOptions.columnDefs = [
                { name: 'select', width: '6%', allowCellFocus: false, enableColumnMenu: false, enableCellEdit: false, cellTemplate: '<img src="../../../../../Content/images/quick_select.png" ng-click="grid.appScope.navigate(row)" style="cursor:pointer;margin-left:10px"/>' },
                { name: 'Id', displayName: 'Customer Id', allowCellFocus: false, width: '11%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false, cellTemplate: '<span>{{grid.appScope.maskCustomerId(row.entity.Id)}}<span/>' },
                { name: 'CustomerName', displayName: 'Customer Name', width: '20%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'City', displayName: 'City', width: '15%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'State', displayName: 'State', width: '15%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Country', displayName: 'Country', width: '20%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                {
                    name: 'Address', displayName: 'Address', width: '25%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                        return row.entity.Address;
                    }
                },
                { name: 'Zip', displayName: 'Zipcode', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Membership', displayName: 'Membership', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
            ];
        }

        $scope.maskCustomerId = function (customerId) {
            var customerIdArray = customerId.toString().split('');
            for (var i = 0; i < customerIdArray.length - 3; i++) {
                customerIdArray[i] = "*";
            }
            return customerIdArray.join('');
        }

        $scope.navigate = function (row) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: '',
                CustomerName: '',
                PersonnelId: '',
                PersonnelName: ''
            };

            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: row.entity.Id,
                CustomerName: row.entity.CustomerName,
                // added for maintain show personnel (start)
                CustomerContact: row.entity.Phone,
                CustomerEmail: row.entity.Email,
                CustomerAddress: row.entity.Address + "\n" + row.entity.City + " " + row.entity.State + " " + row.entity.Country
                //  added for maintain show personnel (end)
            };
            $('#' + $scope.DivId).dialog('close');
            //Added for corporate partner start
            var customerForm = row.entity.Id;
            var corporatePartner = angular.element('#formCreateCorporatePartner').scope();
            if (corporatePartner != null) {
                corporatePartner.getDataByContactID(customerForm);
            }
            //Added for corporate partner end

            if ($("#divCustomerName").length > 0) {
                $("#divCustomerName").show();
            }
        }

        $scope.paginate = function (dir) {
            if (dir == 'pageSize') {
                $scope.gridOptions.currPage = Math.floor((($scope.currentPageSize * ($scope.gridOptions.currPage - 1)) / $scope.gridOptions.paginationPageSize) + 1);
                $scope.SearchData();
                return;
            }

            if (dir == 'next') {
                $scope.gridOptions.currPage++
            }

            if (dir == 'prev') {
                $scope.gridOptions.currPage--
            }

            if (dir == 'last' && $scope.gridOptions.currPage >= $scope.gridOptions.paginationTotalPages) {
                return false;
            }

            if (dir == 'last' && $scope.gridOptions.currPage < $scope.gridOptions.paginationTotalPages) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationTotalPages;
            }

            if (dir == 'first' && $scope.gridOptions.currPage <= 1) {
                return false;
            }

            if (dir == 'first' && $scope.gridOptions.currPage > 1)
                $scope.gridOptions.currPage = 1;

            if ($scope.gridOptions.currPage > $scope.gridOptions.paginationTotalPages) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationTotalPages;
                return false;
            }
            if ($scope.gridOptions.currPage < 1) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationCurrentPage;
                return false;
            }
            $scope.SearchData();
        },

         $scope.updatePagination = function () {
             CustomerLookupCountPages();
             CustomerLookupRowDetails();
         }

        $scope.loadGrid = function (customerForm) {
            $scope.createBtnShow = true;
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.gridOptions.currPage = 1;
            $scope.gridOptions.paginationPageSize = 10;
            if (customerForm.$valid) {
                $scope.SearchData();
            }
            else {
                $scope.gridShow = false;
                customerForm.txtCustomerId.$dirty = true;
                customerForm.txtCustomerName.$dirty = true;
                customerForm.txtCity.$dirty = true;
                customerForm.txtState.$dirty = true;
                customerForm.txtZip.$dirty = true;
                customerForm.txtPhone.$dirty = true;
            }
        }

        $scope.maintainCountry = {
            USA: 'US'
        }

        $scope.SearchData = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.customerData = angular.copy($scope.formData);
            $scope.customerData.PageSize = $scope.gridOptions.paginationPageSize;
            $scope.customerData.OffSet = ($scope.gridOptions.currPage - 1) //* $scope.gridOptions.paginationPageSize);  //$scope.PaginationValues.OffSet * $scope.gridOptions.paginationPageSize;
            //$scope.customerData.Country = $('#ddlCountry :selected').text();
            $scope.customerData.OrderBy = "id";  //default
            $scope.customerData.IsAscending = true;  //default

            //Below code is for Bug EQ-EQ-2446
            if (!$scope.customerData.Id && !$scope.customerData.CustomerName && !$scope.customerData.City && !$scope.customerData.State && !$scope.customerData.Country && !$scope.customerData.Zip && !$scope.customerData.Phone) {
                validationMsg.error([Messages.NoSearchCriteria]);
                validationMsg.showLookupMessage(true);
                valildateData = false;
                return false;
            }

            if ($scope.customerData.CustomerName && !$scope.customerData.City && !$scope.customerData.State && !$scope.customerData.Country && !$scope.customerData.Zip && !$scope.customerData.Phone) {
                validationMsg.error([Messages.CustomarNameSearchValidation]);
                validationMsg.showLookupMessage(true);
                valildateData = false;
                return false;
            }

            viewModelHelper.ShowProgress();

            commonDataService.postData('MaintainCustomerProfile/GetCustomerDetails', function (response) {
                viewModelHelper.CloseProgress();
                $scope.gridShow = true;
                if (response.length > 0 && response != 'null') {
                    createColumnForCustomerLookupGrid();
                    $scope.gridOptions.noRecord = true;
                    $scope.gridOptions.data = response;
                    $scope.updatePagination();
                    $scope.gridOptions.paginationCurrentPage = $scope.gridOptions.currPage;
                    $scope.currentPageSize = $scope.gridOptions.paginationPageSize;
                    $scope.currentPageNo = $scope.gridOptions.currPage;
                }
                else {
                    $scope.gridOptions.noRecord = false;
                    validationMsg.error([Messages.CustomerSearchFailed]);
                    validationMsg.showLookupMessage(true);
                }
            }, function (response) {
                viewModelHelper.CloseProgress();
                validationMsg.error([Messages.InternalServerError]);
                validationMsg.showLookupMessage(true);
            }, $scope.customerData);


            //$http.post(appConfig.apiPath + 'MaintainCustomerProfile/GetCustomerDetails', $scope.customerData, { "Authorization": "Bearer " + commonUtils.readCookie("accessToken") }).
            //	  then(function (response) {
            //	      viewModelHelper.CloseProgress();
            //	      $scope.gridShow = true;
            //	      if (response.length > 0 && response != 'null') {
            //	          createColumnForCustomerLookupGrid();
            //	          $scope.gridOptions.noRecord = true;
            //	          $scope.gridOptions.data = response;
            //	          $scope.updatePagination();
            //	          $scope.gridOptions.paginationCurrentPage = $scope.gridOptions.currPage;
            //	          $scope.currentPageSize = $scope.gridOptions.paginationPageSize;
            //	          $scope.currentPageNo = $scope.gridOptions.currPage;
            //	      }
            //	      else {
            //	          $scope.gridOptions.noRecord = false;
            //	          validationMsg.error([Messages.CustomerSearchFailed]);
            //	          validationMsg.showLookupMessage(true);
            //	      }
            //	  }, function (response) {
            //	      viewModelHelper.CloseProgress();
            //	      validationMsg.error([Messages.InternalServerError]);
            //	      validationMsg.showLookupMessage(true);
            //	  });

        }

        $scope.reset = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.formData = {
                Id: '',
                FirstName: '',
                MiddleName: '',
                LastName: '',
                PreferredName: '',
                CustomerStatus: '',
                CustomerName: '',
                CompanyName: '',
                City: '',
                State: '',
                Country: 'US',
                Zip: '',
                Phone: '',
                Email: '',
                CustomerType: 'I',
                CustomerRole: '',
                DOB: '',
                Gender: '',
                SSN: '',
                IsShowPersonnelPrimaryContact: false
            };
            //$scope.gridShow = false;
            $scope.createBtnShow = false;
        }

        $scope.navigateCustomerLookup = function () {
            window.location.href = "/Customer/MaintainCustomer/Index";
        }

        $scope.NavigateMaintainCustomer = function () {
            var selectedRow = $scope.gridApi.selection.getSelectedRows();
            if (selectedRow.length == 1) {
                $scope.UpdateParentGridRoles(selectedRow[0]);
                //Added for Maintain Corporate Partner Usecase ContactID lookup for select button
                var customerForm = selectedRow[0].Id;
                var corporatePartner = angular.element('#formCreateCorporatePartner').scope();
                if (corporatePartner != undefined) {
                    corporatePartner.getDataByContactID(customerForm);
                }
                //End
            } else {
                //validationMsg.error([Messages.RowSelection]);
                //validationMsg.show(true);
                validationMsg.error([Messages.SelectRecord]);
                validationMsg.showLookupMessage(true);
            }

        };

        $scope.UpdateParentGridRoles = function (selectedRow) {
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: selectedRow.Id,
                CustomerName: selectedRow.CustomerName,
                PersonnelId: selectedRow.Id,
                PersonnelName: selectedRow.CustomerName,
            };
            $('#' + $scope.DivId).dialog('close');
            if ($("#divCustomerName").length > 0) {
                $("#divCustomerName").show();
            }
        }

        $scope.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
        }

        function CustomerLookupCountPages() {
            if ($scope.gridOptions.data.length > 0) {
                var totPages = Math.ceil($scope.gridOptions.data[0].TotalRecords / $scope.gridOptions.paginationPageSize);
                $scope.gridOptions.paginationTotalPages = Math.ceil($scope.gridOptions.data[0].TotalRecords / $scope.gridOptions.paginationPageSize);
            }
        }

        function CustomerLookupRowDetails() {
            if ($scope.gridOptions.data.length > 0) {
                $scope.gridOptions.TotalRecords = $scope.gridOptions.data[0].TotalRecords;
                $scope.gridOptions.rowMin = (($scope.gridOptions.currPage - 1) * $scope.gridOptions.paginationPageSize) + 1;
                $scope.gridOptions.rowMax = (($scope.gridOptions.currPage * $scope.gridOptions.paginationPageSize) > $scope.gridOptions.TotalRecords) ? $scope.gridOptions.TotalRecords : ($scope.gridOptions.currPage * $scope.gridOptions.paginationPageSize);
            }
        }

        $scope.jumpToPage = function (e) {
            if (e.keyCode == 13) {
                if ($scope.gridOptions.currPage > $scope.gridOptions.paginationTotalPages) {
                    alert(Messages.InvalidPageNo);
                    $scope.gridOptions.currPage = $scope.currentPageNo;
                    return false;
                }
                $scope.SearchData();
            }
        }

        $scope.CancelCustomerSearch = function () {
            $('#' + $scope.DivId).dialog('close');
        };

        $scope.getZipCodeMask = function () {

            $scope.$emit('sendCountryCode', $scope.formData.Country);
        };
    }]);
/************************************************************ Customer Lookup End**********************************************/

/************************************************************ Show Lookup Start************************************************/
CommonDirectiveService.directive('showlookupDirective', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName",
        template: '<div ng-include="contentUrl"></div>'
    }
}).controller('showLookupCtrl', ['$scope', '$http', 'myGrid', 'appConfig', 'viewModelHelper',
    '$routeParams', 'Messages', 'validationMsg', 'validationPatterns', 'commonDataService', function ($scope, $http, myGrid,
        appConfig, viewModelHelper, $routeParams, Messages, validationMsg, validationPatterns, commonDataService) {


        $scope.master = {};
        $scope.gridShow = false;
        //$scope.gridOptions = myGrid.gridOptions;
        //$scope.edit = myGrid.edit;
        //$scope.jumpToPage = myGrid.jumpToPage;

        $scope.gridOptions = {
            showColumnMenu: false,
            paginationPageSizes: [10, 25, 50, 100],
            paginationPageSize: 10,
            paginationCurrentPage: 1,
            paginationTotalPages: 0,
            paginationCurrentClass: 'current',
            enablePaginationControls: false,
            currPage: 1,
            rowMin: 1,
            rowMax: 10,
            gridEdit: false,
            rowIndex: null,
            totalRecords: 0,
            rowObj: {},
            noRecord: false,
            enableRowHeaderSelection: false,
            multiSelect: false
        };


        /*Below two line to selection of row */
        //$scope.gridOptions.enableRowHeaderSelection = false;
        //$scope.gridOptions.multiSelect = false;
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        $scope.dateRegex = validationPatterns.dateRegex;
        $scope.ControllerName = '';
        $scope.ViewModelName = '';
        $scope.DivId = '';

        //define view modal
        $scope.showData = {
            ShowNo: '',
            ShowName: '',
            ShowYear: '',
            ShowEventCode: '',
            EventName: '',
            City: '',
            State: '',
            Zip: '',
            CustomerId: '',
            CustomerName: '',
            ShowType: '',
            FromDate: '',
            ToDate: '',
        };

        //dropdown binding
        $scope.BindShowType = function () {
            commonDataService.getData('LookupMaster/GetShowType',
                function (result) {
                    if (result.length > 0) {
                        $scope.ShowType = result;
                    }
                },
                function (failure) {
                    validationMsg.error([Messages.InternalServerError]);
                    validationMsg.showLookupMessage(true);
                });
        };

        $scope.BindShowType();

        $scope.ShowYear = GetShowYears();

        function GetShowYears() {
            var startYear = '1951';
            var currYear = new Date().getFullYear();
            var endYear = currYear + 4;
            var Years = new Array();
            for (var i = startYear; i <= endYear; i++) {
                Years.push({ ShowYear: i.toString(), YearName: i.toString() });
            }
            return Years;
        };

        //show lookup popup
        $scope.OpenShowLookup = function (controllerName, viewModal, divId) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            //view modal        
            $scope.showData = {
                ShowNo: '',
                ShowName: '',
                ShowYear: '',
                ShowEventCode: '',
                EventName: '',
                City: '',
                State: '',
                Zip: '',
                CustomerId: '',
                CustomerName: '',
                ShowType: '',
                FromDate: '',
                ToDate: '',
            };
            $scope.gridShow = false;
            $scope.ControllerName = controllerName;
            $scope.ViewModelName = viewModal;
            $scope.DivId = divId;
            viewModelHelper.ShowPopup(divId, "Show Lookup", 1200, 'auto')
            $scope.showData.ShowNo = angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName].ShowNo;

        };

        //define grid column
        function createColumnForShowLookupGrid() {
            $scope.gridOptions.columnDefs = [
                { name: 'select', pinnedLeft: true, width: '6%', allowCellFocus: false, enableColumnMenu: false, enableCellEdit: false, cellTemplate: '<img src="../../../../../Content/images/quick_select.png" ng-click="grid.appScope.navigate(row)" style="cursor:pointer;margin-left:10px"/>' },
                { name: 'ShowNo', displayName: 'Show #', allowCellFocus: false, width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'ShowYear', displayName: 'Show Year', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                {
                    name: 'ShowName', displayName: 'Show Name', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                        return row.entity.ShowName;
                    }
                },
                { name: 'ShowType', displayName: 'Show Type', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'ShowEventCode', displayName: 'Event Code', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                {
                    name: 'EventName', displayName: 'Event Name', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                        return row.entity.EventName;
                    }
                },
                { name: 'CustomerId', displayName: 'Sponsor Id', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                {
                    name: 'CustomerName', displayName: 'Sponsor Name', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                        return row.entity.CustomerName;
                    }
                },
                { name: 'FromDate', displayName: 'Show Start Date', width: '12%', cellTemplate: '<cell-date value="row.entity.FromDate"></cell-date>', enableColumnMenu: false, enableCellEdit: false, cellFilter: 'date:\'MM/dd/yyyy\'', allowCellFocus: false },
                { name: 'ToDate', displayName: 'Show End Date', width: '10%', cellTemplate: '<cell-date value="row.entity.ToDate"></cell-date>', enableColumnMenu: false, enableCellEdit: false, cellFilter: 'date:\'MM/dd/yyyy\'', allowCellFocus: false },
                { name: 'City', displayName: 'City', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'State', displayName: 'State', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Zip', displayName: 'Zip Code', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
            ];
        }

        //Navigation to parent page
        $scope.navigate = function (row) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                ShowNo: '',
                ShowName: '',
            };
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                ShowNo: row.entity.ShowNo,
                ShowName: row.entity.ShowName,
            };
            $('#' + $scope.DivId).dialog('close');
        }

        //Navigation to parent page using select button
        $scope.selectAndNavigate = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            var selectedRow = $scope.gridApi.selection.getSelectedRows();
            if (selectedRow.length == 1) {
                $scope.UpdateParentGridRoles(selectedRow[0]);
            } else {
                validationMsg.error([Messages.SelectRecord]);
                validationMsg.showLookupMessage(true);
            }
        };

        $scope.UpdateParentGridRoles = function (selectedRow) {
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                ShowNo: selectedRow.ShowNo,
                ShowName: selectedRow.ShowName,
            };
            $('#' + $scope.DivId).dialog('close');
        }


        var selectedRowShowNo = '';
        var selectedRowShowName = '';
        $scope.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
            ShowLookupCountPages();
            ShowLookupRowDetails();
            $scope.gridApi.pagination.on.paginationChanged($scope, function (currentPage, pageSize) {
                validationMsg.clear();
                validationMsg.showLookupMessage(false);
                ShowLookupCountPages();
                ShowLookupRowDetails();
                $scope.gridOptions.currPage = currentPage;
            });

            gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                selectedRowShowNo = row.entity.ShowNo;
                selectedRowShowName = row.entity.ShowName;
            });
        }

        function ShowLookupCountPages() {
            var totPages = Math.ceil($scope.gridOptions.data.length / $scope.gridOptions.paginationPageSize);
            $scope.gridOptions.paginationTotalPages = Math.ceil($scope.gridOptions.data.length / $scope.gridOptions.paginationPageSize);
        }

        function ShowLookupRowDetails() {
            $scope.gridOptions.totalRecords = $scope.gridOptions.data.length;
            $scope.gridOptions.rowMin = (($scope.gridOptions.paginationCurrentPage - 1) * $scope.gridOptions.paginationPageSize) + 1;
            $scope.gridOptions.rowMax = (($scope.gridOptions.paginationCurrentPage * $scope.gridOptions.paginationPageSize) > $scope.gridOptions.totalRecords) ? $scope.gridOptions.totalRecords : ($scope.gridOptions.paginationCurrentPage * $scope.gridOptions.paginationPageSize);
        }

        $scope.jumpToPage = function (e) {
            var pageNo = parseInt($scope.gridOptions.currPage);
            if (isNaN(String.fromCharCode(e.keyCode))) {
                e.preventDefault();
            }

            if (e.keyCode == 13) {
                if ($scope.gridOptions.currPage > $scope.gridOptions.paginationTotalPages) {
                    alert(Messages.InvalidPageNo);
                    $scope.gridOptions.currPage = $scope.gridOptions.paginationCurrentPage;
                    return false;
                }

                if (pageNo == null || pageNo == '' || isNaN(pageNo)) {
                    pageNo = $scope.gridOptions.paginationCurrentPage;
                    $scope.gridOptions.currPage = pageNo;
                }

                $scope.gridApi.pagination.seek(pageNo);
            }
        }

        //focus Go button
        $scope.onButtonFocus = function () {
            angular.element('#btnEnterSearch').focus()
            //angular.element('#btnEnterClear').focus()
        }

        //function to load grid
        $scope.lookupShowGrid = function (searchShowLookupForm) {

            validationMsg.clear();
            validationMsg.showLookupMessage(false);

            if (($scope.showData.ShowNo == "") && ($scope.showData.ShowName == "") && ($scope.showData.ShowYear == "") && ($scope.showData.ShowEventCode == "") && ($scope.showData.EventName == "") &&
                ($scope.showData.City == "") && ($scope.showData.State == "") && ($scope.showData.Zip == "") && ($scope.showData.CustomerId == "") && ($scope.showData.CustomerName == "") && ($scope.showData.ShowType == "")
                && ($scope.showData.FromDate == "") && ($scope.showData.ToDate == "")) {
                validationMsg.error([Messages.SearchErrorMessage]);
                validationMsg.showLookupMessage(true);
            }
            else {
                validationMsg.clear();
                validationMsg.showLookupMessage(false);

                if ($scope.showData.FromDate != "" && $scope.showData.ToDate == "") {
                    validationMsg.error([Messages.EnterToDate]);
                    validationMsg.showLookupMessage(true);
                    return false;
                }
                else if ($scope.showData.ToDate != "" && $scope.showData.FromDate == "") {
                    validationMsg.error([Messages.EnterFromDate]);
                    validationMsg.showLookupMessage(true);
                    return false;
                }
                else {
                    if ($scope.showData.FromDate != "" && $scope.showData.ToDate != "") {
                        if ($scope.showData.FromDate.indexOf("/") != -1 && $scope.showData.ToDate.indexOf("/") != -1) {
                            var fromDate = ($scope.showData.FromDate).replace(/\D/g, '/');
                            var toDate = ($scope.showData.ToDate).replace(/\D/g, '/');
                            var chkFromDate, chkToDate;
                            chkFromDate = new Date(fromDate);
                            chkToDate = new Date(toDate);

                            if (chkToDate < chkFromDate) {
                                validationMsg.error([Messages.ValidateDate]);
                                validationMsg.showLookupMessage(true);
                                return false;
                            }
                        }
                    }
                }

                if (searchShowLookupForm.$valid) {
                    viewModelHelper.ShowProgress();
                    $scope.$apply();
                    viewModelHelper.apiPost('/MaintainShow/FindShowsForLookup', $scope.showData,
                         function (result) {
                             if (result.length > 0 && result != 'null') {
                                 validationMsg.clear();
                                 validationMsg.showLookupMessage(false);
                                 $scope.gridShow = true;
                                 createColumnForShowLookupGrid();
                                 $scope.gridOptions.data = result;
                                 ShowLookupCountPages();
                                 ShowLookupRowDetails();
                                 $scope.gridOptions.noRecord = true;
                                 $scope.$apply();
                             }
                             else {
                                 $scope.gridShow = true;
                                 $scope.gridOptions.noRecord = false;
                             }
                             viewModelHelper.CloseProgress();
                         }, function (failure) {
                             viewModelHelper.CloseProgress();
                             validationMsg.error([Messages.InternalServerError]);
                             validationMsg.showLookupMessage(true);
                             $scope.$apply();
                         });

                }
                else {
                    $scope.gridShow = false;
                    searchShowLookupForm.txtShowId.$dirty = true;
                    searchShowLookupForm.txtShowName.$dirty = true;
                    searchShowLookupForm.txtShowEventName.$dirty = true;
                    searchShowLookupForm.txtShowEventCode.$dirty = true;
                    searchShowLookupForm.txtShowCity.$dirty = true;
                    searchShowLookupForm.txtShowState.$dirty = true;
                    searchShowLookupForm.txtShowZip.$dirty = true;
                    searchShowLookupForm.txtCustomerId.$dirty = true;
                    searchShowLookupForm.txtCustomerName.$dirty = true;
                }
            }
        }

        //close the look up
        $scope.closeShowLookup = function () {
            $('#' + $scope.DivId).dialog('close');
        };

        //clearing search fields
        $scope.reset = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.showData = angular.copy($scope.master);
            $scope.showData = {
                ShowNo: '',
                ShowName: '',
                ShowYear: '',
                ShowEventCode: '',
                EventName: '',
                City: '',
                State: '',
                Zip: '',
                CustomerId: '',
                CustomerName: '',
                ShowType: '',
                FromDate: '',
                ToDate: '',
            };
            $scope.gridShow = false;
            $scope.gridOptions.noRecord = false;
        }

    }]);
/************************************************************ Show Lookup End***************************************************/


/************************************************************ Location Lookup Start*********************************************/
CommonDirectiveService.directive('locationlookupDirective', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName",
        template: '<div ng-include="contentUrl"></div>'
    }
}).controller('locationlookupCtrl', ['$scope', '$http', 'appConfig', 'viewModelHelper', '$routeParams', 'validationMsg', 'Messages', function ($scope, $http, appConfig, viewModelHelper, $routeParams, validationMsg, Messages) {

    $scope.master = {};
    $scope.gridShow = false;

    $scope.gridOptionsShowLocationLookup = {
        showColumnMenu: false,
        paginationPageSizes: [10, 25, 50, 100],
        paginationPageSize: 10,
        paginationCurrentPage: 1,
        paginationTotalPages: 0,
        paginationCurrentClass: 'current',
        enablePaginationControls: false,
        currPage: 1,
        rowMin: 1,
        rowMax: 10,
        gridEdit: false,
        rowIndex: null,
        totalRecords: 0,
        rowObj: {},
        noRecord: false,
        enableRowHeaderSelection: false,
        multiSelect: false
    };

    $scope.ControllerName = '';
    $scope.ViewModelName = '';
    $scope.DivId = '';
    $scope.currentPageSize;
    $scope.currentPageNo;

    $scope.LocationViewModel = function () {
        $scope.LocationLookupViewModel = {
            LocationId: '',
            LocationName: '',
            AddressLine1: '',
            AddressLine2: '',
            City: '',
            State: '',
            ZipCode: '',
            ArenaId: '',
            ArenaName: ''
        };

        $scope.SelectedLocationLookupViewModel = {
            LocationId: '',
            LocationName: ''
        }
    };

    $scope.LocationViewModel();

    $scope.OpenLocationLookup = function (controllerName, viewModal, divId) {
        $scope.LocationViewModel();
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        $scope.gridShow = false;
        $scope.gridOptionsShowLocationLookup.noRecord = false;
        $scope.searchLocationLookupForm.$setPristine();
        $scope.ControllerName = controllerName;
        $scope.ViewModelName = viewModal;
        $scope.DivId = divId;
        $scope.LocationLookupViewModel.LocationId = angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName].LocationId;
        viewModelHelper.ShowPopup(divId, "Location Lookup", 1200, 'auto')
    };

    $scope.gridOptionsShowLocationLookup.columnDefs = [
		{
		    name: 'select', width: '5%', allowCellFocus: false, enableColumnMenu: false, enableCellEdit: false, cellTemplate: '<img src="../../../../../Content/images/quick_select.png" ng-click="grid.appScope.QuickSelectedLocationLookup(row)" style="cursor:pointer;margin-left:10px"/>'
		},
		{
		    name: 'LocationId', type: 'number', displayName: 'Location Id', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false
		},
		{
		    name: 'LocationName', type: 'string', displayName: 'Location Name', width: '15%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.LocationName;
		    }
		},
		{
		    name: 'AddressLine1', type: 'string', displayName: 'Address 1', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.AddressLine1;
		    }
		},
		{
		    name: 'AddressLine2', type: 'string', displayName: 'Address 2', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.AddressLine2;
		    }
		},
		{
		    name: 'City', displayName: 'City', type: 'string', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.City;
		    }
		},
		{
		    name: 'State', displayName: 'State', type: 'string', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.State;
		    }
		},
		{
		    name: 'ZipCode', displayName: 'Zip', type: 'string', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false
		},
		{
		    name: 'ArenaId', displayName: 'Arena Id', type: 'number', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false
		},
		{
		    name: 'ArenaName', displayName: 'Arena Name', type: 'string', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
		        return row.entity.ArenaName;
		    }
		}
    ];

    $scope.searchLocation = function (searchLocationLookupForm) {
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        if (searchLocationLookupForm.$valid) {

            searchLocationLookupForm.txtLocationName.$dirty = false;
            searchLocationLookupForm.txtLocationAddressLine1.$dirty = false;
            searchLocationLookupForm.txtLocationAddressLine2.$dirty = false;
            searchLocationLookupForm.txtLocationCity.$dirty = false;
            searchLocationLookupForm.txtLocationState.$dirty = false;
            searchLocationLookupForm.txtLocationArenaName.$dirty = false;

            if ($scope.LocationLookupViewModel.LocationId == "" && $scope.LocationLookupViewModel.LocationName == "" && $scope.LocationLookupViewModel.AddressLine1 == ""
				&& $scope.LocationLookupViewModel.AddressLine2 == "" && $scope.LocationLookupViewModel.City == "" && $scope.LocationLookupViewModel.State == ""
				&& $scope.LocationLookupViewModel.ZipCode == "" && $scope.LocationLookupViewModel.ArenaId == "" && $scope.LocationLookupViewModel.ArenaName == "") {
                validationMsg.error([Messages.SelectAtLeastOneCriteria]);
                validationMsg.showLookupMessage(true);
                return false;
            }
            $scope.getLocationData();
        }
        else {
            viewModelHelper.CloseProgress();
            searchLocationLookupForm.txtLocationName.$dirty = true;
            searchLocationLookupForm.txtLocationAddressLine1.$dirty = true;
            searchLocationLookupForm.txtLocationAddressLine2.$dirty = true;
            searchLocationLookupForm.txtLocationCity.$dirty = true;
            searchLocationLookupForm.txtLocationState.$dirty = true;
            searchLocationLookupForm.txtLocationArenaName.$dirty = true;
        }
    };

    $scope.getLocationData = function () {
        $scope.data = angular.copy($scope.LocationLookupViewModel);
        $scope.data.PageSize = $scope.gridOptionsShowLocationLookup.paginationPageSize;
        $scope.data.OffSet = ($scope.gridOptionsShowLocationLookup.currPage - 1)
        $scope.data.OrderBy = "id";
        $scope.data.IsAscending = true;
        viewModelHelper.ShowProgress();
        viewModelHelper.apiPost('/MaintainShow/GetForLookupLocation', $scope.data,
        function (result) {
            viewModelHelper.CloseProgress();
            if (result.data.ShowLocations.length > 0) {
                $scope.gridShow = true;
                $scope.gridOptionsShowLocationLookup.noRecord = true;
                $scope.gridOptionsShowLocationLookup.data = result.data.ShowLocations;
                $scope.totalRecordsCount = result.data.TotalRecords;
                $scope.UpdateLocationLookupPagination();
                $scope.gridOptionsShowLocationLookup.paginationCurrentPage = $scope.gridOptionsShowLocationLookup.currPage;
                $scope.currentPageSize = $scope.gridOptionsShowLocationLookup.paginationPageSize;
                $scope.currentPageNo = $scope.gridOptionsShowLocationLookup.currPage;
            }
            else {
                $scope.gridOptionsShowLocationLookup.noRecord = false;
            }
        },
        function (failure) {
            viewModelHelper.CloseProgress();
            validationMsg.error(failure);
            validationMsg.showLookupMessage(true);
        });
    }

    $scope.UpdateLocationLookupPagination = function () {
        LocationLookupCountPages();
        LocationLookupRowDetails();
    }
    $scope.paginateLocationLookup = function (dir) {
        if (dir == 'pageSize') {
            $scope.gridOptionsShowLocationLookup.currPage = Math.floor((($scope.currentPageSize * ($scope.gridOptionsShowLocationLookup.currPage - 1)) / $scope.gridOptionsShowLocationLookup.paginationPageSize) + 1);
            $scope.getLocationData();
            return;
        }

        if (dir == 'next') {
            $scope.gridOptionsShowLocationLookup.currPage++
        }

        if (dir == 'prev') {
            $scope.gridOptionsShowLocationLookup.currPage--
        }

        if (dir == 'last' && $scope.gridOptionsShowLocationLookup.currPage >= $scope.gridOptionsShowLocationLookup.paginationTotalPages) {
            return false;
        }

        if (dir == 'last' && $scope.gridOptionsShowLocationLookup.currPage < $scope.gridOptionsShowLocationLookup.paginationTotalPages) {
            $scope.gridOptionsShowLocationLookup.currPage = $scope.gridOptionsShowLocationLookup.paginationTotalPages;
        }

        if (dir == 'first' && $scope.gridOptionsShowLocationLookup.currPage <= 1) {
            return false;
        }

        if (dir == 'first' && $scope.gridOptionsShowLocationLookup.currPage > 1)
            $scope.gridOptionsShowLocationLookup.currPage = 1;

        if ($scope.gridOptionsShowLocationLookup.currPage > $scope.gridOptionsShowLocationLookup.paginationTotalPages) {
            $scope.gridOptionsShowLocationLookup.currPage = $scope.gridOptionsShowLocationLookup.paginationTotalPages;
            return false;
        }
        if ($scope.gridOptionsShowLocationLookup.currPage < 1) {
            $scope.gridOptionsShowLocationLookup.currPage = $scope.gridOptionsShowLocationLookup.paginationCurrentPage;
            return false;
        }
        $scope.getLocationData();
    },
    $scope.clearLocation = function (searchLocationLookupForm) {
        $scope.LocationViewModel();
        //$scope.gridShow = false;
        //$scope.gridOptionsShowLocationLookup.noRecord = false;
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        searchLocationLookupForm.txtLocationName.$dirty = false;
        searchLocationLookupForm.txtLocationAddressLine1.$dirty = false;
        searchLocationLookupForm.txtLocationAddressLine2.$dirty = false;
        searchLocationLookupForm.txtLocationCity.$dirty = false;
        searchLocationLookupForm.txtLocationState.$dirty = false;
        searchLocationLookupForm.txtLocationArenaName.$dirty = false;
        $scope.searchLocationLookupForm.$setPristine();
    };

    $scope.QuickSelectedLocationLookup = function (row) {
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
            LocationId: '',
            LocationName: ''
        };

        angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
            LocationId: row.entity.LocationId,
            LocationName: row.entity.LocationName
        };

        $('#' + $scope.DivId).dialog('close');
    };

    $scope.SelectedShowLocationLookup = function () {
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
            LocationId: '',
            LocationName: ''
        };

        angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
            LocationId: $scope.SelectedLocationLookupViewModel.LocationId,
            LocationName: $scope.SelectedLocationLookupViewModel.LocationName
        };

        if ($scope.SelectedLocationLookupViewModel.LocationId == '') {
            validationMsg.error([Messages.SelectRecord]);
            validationMsg.showLookupMessage(true);
        }
        else {
            $('#' + $scope.DivId).dialog('close');
        }
    };


    $scope.closeShowLocationLookup = function () {
        $('#' + $scope.DivId).dialog('close');
    };

    $scope.gridOptionsShowLocationLookup.onRegisterApi = function (gridApi) {
        $scope.gridApi = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.SelectedLocationLookupViewModel = {
                LocationId: row.entity.LocationId,
                LocationName: row.entity.LocationName
            };
        });
    }

    function LocationLookupCountPages() {
        if ($scope.gridOptionsShowLocationLookup.data.length > 0) {
            var totPages = Math.ceil($scope.totalRecordsCount / $scope.gridOptionsShowLocationLookup.paginationPageSize);
            $scope.gridOptionsShowLocationLookup.paginationTotalPages = Math.ceil($scope.totalRecordsCount / $scope.gridOptionsShowLocationLookup.paginationPageSize);
        }
    }

    function LocationLookupRowDetails() {
        if ($scope.gridOptionsShowLocationLookup.data.length > 0) {
            $scope.gridOptionsShowLocationLookup.TotalRecords = $scope.totalRecordsCount;
            $scope.gridOptionsShowLocationLookup.rowMin = (($scope.gridOptionsShowLocationLookup.currPage - 1) * $scope.gridOptionsShowLocationLookup.paginationPageSize) + 1;
            $scope.gridOptionsShowLocationLookup.rowMax = (($scope.gridOptionsShowLocationLookup.currPage * $scope.gridOptionsShowLocationLookup.paginationPageSize) > $scope.gridOptionsShowLocationLookup.TotalRecords) ? $scope.gridOptionsShowLocationLookup.TotalRecords : ($scope.gridOptionsShowLocationLookup.currPage * $scope.gridOptionsShowLocationLookup.paginationPageSize);
        }
    }

    $scope.jumpToPageShowLocationLookup = function (e) {
        if (e.keyCode == 13) {
            if ($scope.gridOptionsShowLocationLookup.currPage > $scope.gridOptionsShowLocationLookup.paginationTotalPages) {
                alert(Messages.InvalidPageNo);
                $scope.gridOptionsShowLocationLookup.currPage = $scope.currentPageNo;
                return false;
            }
            $scope.getLocationData();
        }
    };
}]);
/************************************************************ Location Lookup End************************************************/

/************************************************************ Show Event Lookup Start*********************************************/
CommonDirectiveService.directive('showeventlookupDirective', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName",
        template: '<div ng-include="contentUrl"></div>'
    }
}).controller('showeventlookupCtrl', ['$scope', '$http', 'appConfig', 'viewModelHelper', '$routeParams',
    'validationMsg', 'Messages', 'validationPatterns', 'formattedDate', 'commonDataService', function ($scope, $http, appConfig,
        viewModelHelper, $routeParams, validationMsg, Messages, validationPatterns, formattedDate, commonDataService) {
        $scope.dateRegex = validationPatterns.dateRegex;
        $scope.master = {};
        $scope.gridShow = false;

        $scope.gridOptionsShowEventLookup = {
            showColumnMenu: false,
            paginationPageSizes: [10, 25, 50, 100],
            paginationPageSize: 10,
            paginationCurrentPage: 1,
            paginationTotalPages: 0,
            paginationCurrentClass: 'current',
            enablePaginationControls: false,
            currPage: 1,
            rowMin: 1,
            rowMax: 10,
            gridEdit: false,
            rowIndex: null,
            totalRecords: 0,
            rowObj: {},
            noRecord: false,
            enableRowHeaderSelection: false,
            multiSelect: false
        };

        $scope.ControllerName = '';
        $scope.ViewModelName = '';
        $scope.DivId = '';
        $scope.ShowEventStatus = '';
        //define view modal

        $scope.ShowEventViewModel = function () {
            $scope.ShowEventSearchViewModel = {
                EventCode: '',
                EventName: '',
                FromDate: '',
                ToDate: '',
                Status: {
                    Code: '',
                    Name: ''
                },
            };

            $scope.ShowEventLookupViewModel = {
                EventCode: '',
                EventName: '',
                FromDate: '',
                ToDate: '',
                Status: {
                    Code: '',
                    Name: ''
                },
                Comments: '',
                UserName: '',
                IsAdded: '',
                IsUpdated: '',
                IsDeleted: ''
            };

        };

        $scope.ShowEventViewModel();

        $scope.BindShowEventStatus = function () {
            commonDataService.getData('LookupMaster/GetActiveStatus',
                function (result) {
                    $scope.ShowEventStatus = result;
                });
        };

        $scope.BindShowEventStatus();

        $scope.OpenShowEventLookup = function (controllerName, viewModal, divId) {
            $scope.ShowEventViewModel();
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.gridShow = false;
            $scope.gridOptionsShowEventLookup.noRecord = false;
            $scope.searchShowEventLookupForm.$setPristine();
            $scope.ControllerName = controllerName;
            $scope.ViewModelName = viewModal;
            $scope.DivId = divId;
            $scope.ShowEventSearchViewModel.EventCode = angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName].EventCode;
            viewModelHelper.ShowPopup(divId, "Show Event Lookup", 1200, 'auto')
        };

        $scope.gridOptionsShowEventLookup.columnDefs = [
            {
                name: 'select', width: '5%', allowCellFocus: false, enableColumnMenu: false, enableCellEdit: false, cellTemplate: '<img src="../../../../../Content/images/quick_select.png" ng-click="grid.appScope.QuickSelectedShowEventLookup(row)" style="cursor:pointer;margin-left:10px"/>'
            },
            {
                name: 'EventCode', displayName: 'Event Code', type: 'number', width: '10%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false
            },
            {
                name: 'EventName', displayName: 'Event Name', type: 'string', width: '20%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                    return row.entity.EventName;
                }
            },
            {
                name: 'FromDate', displayName: 'From Date', cellTemplate: '<div>{{grid.appScope.EventDateFormat(row.entity.FromDate);}}</div>', type: 'date', width: '15%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellFilter: 'date:\'MM/dd/yyyy\''
            },
            {
                name: 'ToDate', displayName: 'To Date', cellTemplate: '<div>{{grid.appScope.EventDateFormat(row.entity.ToDate);}}</div>', type: 'date', width: '15%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellFilter: 'date:\'MM/dd/yyyy\''
            },
            {
                name: 'Status.Name', displayName: 'Status', type: 'string', width: '15%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false
            },
            {
                name: 'Comments', displayName: 'Comments', type: 'string', width: '20%', enableColumnMenu: false, enableSorting: true, enableCellEdit: false, allowCellFocus: false, cellTooltip: function (row, col) {
                    return row.entity.Comments;
                }
            },
        ];

        $scope.EventDateFormat = function (dateString) {
            // return formattedDate.getFormattedDate(value);
            var dateObj = new Date(dateString);
            function pad(n) { return n < 10 ? "0" + n : n; }
            var result = pad(dateObj.getMonth() + 1) + "/" + pad(dateObj.getDate()) + "/" + dateObj.getFullYear();
            return result;
        };

        $scope.searchShowEvent = function (searchShowEventLookupForm) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            if (searchShowEventLookupForm.$valid) {
                searchShowEventLookupForm.txtShowEventCode.$dirty = false;
                searchShowEventLookupForm.txtShowEventName.$dirty = false;
                searchShowEventLookupForm.txtShowEventFromDate.$dirty = false;
                searchShowEventLookupForm.txtShowEventToDate.$dirty = false;

                if ($scope.ShowEventSearchViewModel.EventCode == "" && $scope.ShowEventSearchViewModel.EventName == "" && $scope.ShowEventSearchViewModel.FromDate == ""
                    && $scope.ShowEventSearchViewModel.ToDate == "" && $scope.ShowEventSearchViewModel.Status.Code == "") {
                    validationMsg.error([Messages.SelectAtLeastOneCriteria]);
                    validationMsg.showLookupMessage(true);
                    return false;
                }

                viewModelHelper.ShowProgress();
                commonDataService.postData('ShowEvent/Get',
                function (result) {
                    viewModelHelper.CloseProgress();
                    if (result.length > 0) {
                        $scope.gridShow = true;
                        $scope.gridOptionsShowEventLookup.noRecord = true;
                        $scope.gridOptionsShowEventLookup.data = result;

                        $scope.gridOptionsShowEventLookup.currPage = 1;
                        $scope.gridOptionsShowEventLookup.paginationPageSize = 10;
                        $scope.gridOptionsShowEventLookup.paginationCurrentPage = 1;
                        $scope.gridOptionsShowEventLookup.paginationTotalPages = 0;

                        ShowEventLookupCountPages();
                        ShowEventLookupRowDetails();
                        $scope.searchShowEventLookupForm.$setPristine();
                        //$scope.$apply();
                    }
                    else {
                        $scope.gridShow = true;
                        $scope.gridOptionsShowEventLookup.noRecord = false;
                    }
                },
                    function (failure) {
                        viewModelHelper.CloseProgress();
                        validationMsg.error(failure);
                        validationMsg.showLookupMessage(true);
                    }, $scope.ShowEventSearchViewModel);
            }
            else {
                viewModelHelper.CloseProgress();
                searchShowEventLookupForm.txtShowEventCode.$dirty = true;
                searchShowEventLookupForm.txtShowEventName.$dirty = true;
                searchShowEventLookupForm.txtShowEventFromDate.$dirty = true;
                searchShowEventLookupForm.txtShowEventToDate.$dirty = true;
            }
        };

        $scope.clearShowEvent = function (searchShowEventLookupForm) {
            $scope.ShowEventViewModel();
            //$scope.gridShow = false;
            //$scope.gridOptionsShowEventLookup.noRecord = false;
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            searchShowEventLookupForm.txtShowEventCode.$dirty = false;
            searchShowEventLookupForm.txtShowEventName.$dirty = false;
            searchShowEventLookupForm.txtShowEventFromDate.$dirty = false;
            searchShowEventLookupForm.txtShowEventToDate.$dirty = false;
            $scope.searchShowEventLookupForm.$setPristine();
        };

        $scope.QuickSelectedShowEventLookup = function (row) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                EventCode: '',
                EventName: '',
                ToDate: '',
                FromDate: ''
            };

            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                EventCode: row.entity.EventCode,
                EventName: row.entity.EventName,
                ToDate: row.entity.ToDate,
                FromDate: row.entity.FromDate
            };

            $('#' + $scope.DivId).dialog('close');
        };

        $scope.SelectedShowEventLookup = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                EventCode: '',
                EventName: '',
                ToDate: '',
                FromDate: ''
            };

            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                EventCode: $scope.ShowEventLookupViewModel.EventCode,
                EventName: $scope.ShowEventLookupViewModel.EventName,
                ToDate: row.entity.ToDate,
                FromDate: row.entity.FromDate
            };

            if ($scope.ShowEventLookupViewModel.EventCode == '') {
                validationMsg.error([Messages.SelectRecord]);
                validationMsg.showLookupMessage(true);
            }
            else {
                $('#' + $scope.DivId).dialog('close');
            }
        };

        $scope.closeShowEventLookup = function () {
            $('#' + $scope.DivId).dialog('close');
        };

        $scope.gridOptionsShowEventLookup.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
            ShowEventLookupCountPages();
            ShowEventLookupRowDetails();
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.gridApi.pagination.on.paginationChanged($scope, function (currentPage, pageSize) {
                validationMsg.clear();
                validationMsg.showLookupMessage(false);
                ShowEventLookupCountPages();
                ShowEventLookupRowDetails();
                $scope.gridOptionsShowEventLookup.currPage = currentPage;
            });

            gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                validationMsg.clear();
                validationMsg.showLookupMessage(false);
                $scope.ShowEventLookupViewModel = row.entity;
            });
        };

        function ShowEventLookupCountPages() {
            var totPages = Math.ceil($scope.gridOptionsShowEventLookup.data.length / $scope.gridOptionsShowEventLookup.paginationPageSize);
            $scope.gridOptionsShowEventLookup.paginationTotalPages = Math.ceil($scope.gridOptionsShowEventLookup.data.length / $scope.gridOptionsShowEventLookup.paginationPageSize);
        };

        function ShowEventLookupRowDetails() {
            $scope.gridOptionsShowEventLookup.totalRecords = $scope.gridOptionsShowEventLookup.data.length;
            $scope.gridOptionsShowEventLookup.rowMin = (($scope.gridOptionsShowEventLookup.paginationCurrentPage - 1) * $scope.gridOptionsShowEventLookup.paginationPageSize) + 1;
            $scope.gridOptionsShowEventLookup.rowMax = (($scope.gridOptionsShowEventLookup.paginationCurrentPage * $scope.gridOptionsShowEventLookup.paginationPageSize) > $scope.gridOptionsShowEventLookup.totalRecords) ? $scope.gridOptionsShowEventLookup.totalRecords : ($scope.gridOptionsShowEventLookup.paginationCurrentPage * $scope.gridOptionsShowEventLookup.paginationPageSize);
        };

        $scope.jumpToPageShowEventLookup = function (e) {
            var pageNo = parseInt($scope.gridOptionsShowEventLookup.currPage);
            if (isNaN(String.fromCharCode(e.keyCode))) {
                e.preventDefault();
            }

            if (e.keyCode == 13) {
                if ($scope.gridOptionsShowEventLookup.currPage > $scope.gridOptionsShowEventLookup.paginationTotalPages) {
                    alert("Invalid page number");
                    $scope.gridOptionsShowEventLookup.currPage = $scope.gridOptionsShowEventLookup.paginationCurrentPage;
                    return false;
                }

                if (pageNo == null || pageNo == '' || isNaN(pageNo)) {
                    pageNo = $scope.gridOptionsShowEventLookup.paginationCurrentPage;
                    $scope.gridOptionsShowEventLookup.currPage = pageNo;
                }

                $scope.gridApi.pagination.seek(pageNo);
            }
        };
    }]);
/************************************************************ Show Event Lookup End************************************************/

/************************************************************ Affiliate Lookup Start*****************************************************************/
CommonDirectiveService.directive('affiliatelookupDirective', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName",
        template: '<div ng-include="contentUrl"></div>'
    }
}).controller('affiliateDetailsCtrl', ['$scope', '$http', 'myGrid', 'appConfig', 'viewModelHelper', '$routeParams',
    'validationMsg', 'validationPatterns', '$q', 'Messages', 'commonUtils', 'commonDataService', function ($scope, $http, myGrid, appConfig,
        viewModelHelper, $routeParams, validationMsg, validationPatterns, $q, Messages, commonUtils, commonDataService) {
        $scope.ControllerName = '';
        $scope.ViewModelName = '';
        $scope.DivId = '';
        validationMsg.clear();
        validationMsg.showLookupMessage(false);
        $scope.createBtnShow = false;
        $scope.formData = {
            Id: '',
            FirstName: '',
            MiddleName: '',
            LastName: '',
            PreferredName: '',
            CustomerStatus: '',
            CustomerName: '',
            CompanyName: '',
            City: '',
            State: '',
            Country: '',
            Zip: '',
            Phone: '',
            Email: '',
            CustomerType: '',
            CustomerRole: 'AFF',
            DOB: '',
            Gender: '',
            SSN: '',
        };

        $scope.OpenAffiliateLookupDetails = function (controllerName, viewModal, divId) {
            validationMsg.clear();
            $scope.createBtnShow = false;
            validationMsg.showLookupMessage(false);
            $scope.formData = {
                Id: '',
                FirstName: '',
                MiddleName: '',
                LastName: '',
                PreferredName: '',
                CustomerStatus: '',
                CustomerName: '',
                CompanyName: '',
                City: '',
                State: '',
                Country: '',
                Zip: '',
                Phone: '',
                Email: '',
                CustomerType: '',
                CustomerRole: 'AFF',
                DOB: '',
                Gender: '',
                SSN: '',
            };
            $scope.searchCustomerForm.ddlStatus.$dirty = false;
            $scope.gridShow = false;
            $scope.ControllerName = controllerName;
            $scope.ViewModelName = viewModal;
            $scope.DivId = divId;
            $scope.formData.Id = angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName].CustomerId;
            $scope.gridOptions.noRecord = false;
            viewModelHelper.ShowPopup(divId, "Affiliate Lookup", 1200, 'auto')
        };

        //$scope.master = {};
        //$scope.gridShow = false;
        //$scope.gridOptions = myGrid.gridOptions;
        //$scope.jumpToPage = myGrid.jumpToPage;

        ///*Below two line to selection of row */
        //$scope.gridOptions.enableRowHeaderSelection = false;
        //$scope.gridOptions.multiSelect = false;
        $scope.customerID = {};
        $scope.customerName = {};
        $scope.customerData = {};
        $scope.currentPageSize;
        $scope.currentPageNo;

        $scope.gridOptions = {
            showColumnMenu: false,
            paginationPageSizes: [10, 25, 50, 100],
            paginationPageSize: 10,
            paginationCurrentPage: 1,
            paginationTotalPages: 0,
            paginationCurrentClass: 'current',
            enablePaginationControls: false,
            currPage: 1,
            rowMin: 1,
            rowMax: 10,
            gridEdit: false,
            rowIndex: null,
            totalRecords: 0,
            rowObj: {},
            noRecord: false,
            enableRowHeaderSelection: false,
            multiSelect: false
        };

        ////Commented by vivek related to maintain show loading is coming in create mode
        ////viewModelHelper.ShowProgress();

        $scope.ActiveStatusReq = $http({
            method: 'Get', url: appConfig.apiPath + 'LookupMaster/GetActiveStatus', headers: { "Authorization": "Bearer " + commonUtils.readCookie("accessToken") }
        }).success(function (data, status, headers, config) {
            $scope.activeStatus = data;
        }).error(function (data, status, headers, config) {
            validationMsg.error([Messages.InternalServerError]);
            validationMsg.showLookupMessage(true);
        });

        $scope.GenderTypeReq = $http({
            method: 'Get', url: appConfig.apiPath + 'LookupMaster/GetGenderType', headers: { "Authorization": "Bearer " + commonUtils.readCookie("accessToken") }
        }).success(function (data, status, headers, config) {
            $scope.gender = data;
        }).error(function (data, status, headers, config) {
            validationMsg.error([Messages.InternalServerError]);
            validationMsg.showLookupMessage(true);
        });

        function createColumnForCustomerLookupGrid() {
            $scope.gridOptions.columnDefs = [
                { name: 'select', width: '6%', allowCellFocus: false, enableColumnMenu: false, enableCellEdit: false, cellTemplate: '<img src="../../../../../Content/images/quick_select.png" ng-click="grid.appScope.navigate(row)" style="cursor:pointer;margin-left:10px"/>' },
                { name: 'Id', displayName: 'Customer Id', allowCellFocus: false, width: '11%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'CompanyName', displayName: 'Company Name', width: '20%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'FirstName', displayName: 'First Name', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'MiddleName', displayName: 'Middle Name', width: '11%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'LastName', displayName: 'Last Name', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'DateOfBirth', displayName: 'D.O.B', width: '10%', enableColumnMenu: false, enableCellEdit: false, cellFilter: 'date:\'MM/dd/yyyy\'', allowCellFocus: false },
                { name: 'Email', displayName: 'Email Id', width: '20%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Phone', displayName: 'Phone', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Address', displayName: 'Address', width: '25%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'City', displayName: 'City', width: '15%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'State', displayName: 'State', width: '15%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Country', displayName: 'Country', width: '20%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
                { name: 'Zip', displayName: 'Zipcode', width: '10%', enableColumnMenu: false, enableCellEdit: false, allowCellFocus: false },
            ];
        }

        $scope.navigate = function (row) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: '',
                CustomerName: '',
                Affiliate: {
                    Code: '',
                    Name: ''
                }
            };

            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: row.entity.Id,
                CustomerName: row.entity.CustomerName,
                Affiliate: {
                    Code: row.entity.Id,
                    Name: row.entity.CustomerName
                }
            };
            $('#' + $scope.DivId).dialog('close');
        }

        $scope.paginate = function (dir) {
            if (dir == 'pageSize') {
                $scope.gridOptions.currPage = Math.floor((($scope.currentPageSize * ($scope.gridOptions.currPage - 1)) / $scope.gridOptions.paginationPageSize) + 1);
                $scope.SearchData();
                return;
            }

            if (dir == 'next') {
                $scope.gridOptions.currPage++
            }

            if (dir == 'prev') {
                $scope.gridOptions.currPage--
            }

            if (dir == 'last' && $scope.gridOptions.currPage >= $scope.gridOptions.paginationTotalPages) {
                return false;
            }

            if (dir == 'last' && $scope.gridOptions.currPage < $scope.gridOptions.paginationTotalPages) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationTotalPages;
            }

            if (dir == 'first' && $scope.gridOptions.currPage <= 1) {
                return false;
            }

            if (dir == 'first' && $scope.gridOptions.currPage > 1)
                $scope.gridOptions.currPage = 1;

            if ($scope.gridOptions.currPage > $scope.gridOptions.paginationTotalPages) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationTotalPages;
                return false;
            }
            if ($scope.gridOptions.currPage < 1) {
                $scope.gridOptions.currPage = $scope.gridOptions.paginationCurrentPage;
                return false;
            }
            $scope.SearchData();
        },

         $scope.updatePagination = function () {
             CustomerLookupCountPages();
             CustomerLookupRowDetails();
         }

        $scope.loadGrid = function (customerForm) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.gridOptions.currPage = 1;
            $scope.gridOptions.paginationPageSize = 10;
            if (customerForm.$valid) {
                $scope.SearchData();
            }
            else {
                $scope.gridShow = false;
                customerForm.txtCustomerId.$dirty = true;
                customerForm.txtFirstName.$dirty = true;
                customerForm.txtMiddleName.$dirty = true;
                customerForm.txtLastName.$dirty = true;
                customerForm.txtCompanyName.$dirty = true;
                customerForm.ddlStatus.$dirty = true;
            }
        }

        $scope.SearchData = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.customerData = angular.copy($scope.formData);
            $scope.customerData.PageSize = $scope.gridOptions.paginationPageSize;
            $scope.customerData.OffSet = ($scope.gridOptions.currPage - 1)
            $scope.customerData.OrderBy = "id";  //default
            $scope.customerData.IsAscending = true;  //default
            $scope.customerData.CustomerStatus = $scope.customerData.CustomerStatus.Name;

            viewModelHelper.ShowProgress();
            commonDataService.postData('MaintainCustomerProfile/GetCustomerDetails', function (response) {
                viewModelHelper.CloseProgress();
                $scope.gridShow = true;
                if (response.length > 0 && response != 'null') {
                    createColumnForCustomerLookupGrid();
                    $scope.gridOptions.noRecord = true;
                    $scope.gridOptions.data = response;
                    $scope.updatePagination();
                    $scope.gridOptions.paginationCurrentPage = $scope.gridOptions.currPage;
                    $scope.currentPageSize = $scope.gridOptions.paginationPageSize;
                    $scope.currentPageNo = $scope.gridOptions.currPage;
                }
                else {
                    $scope.gridOptions.noRecord = false;
                }
            }, function (response) {
                viewModelHelper.CloseProgress();
                validationMsg.error([Messages.InternalServerError]);
                validationMsg.showLookupMessage(true);
            }, $scope.customerData);

            //$http.post(appConfig.apiPath + 'MaintainCustomerProfile/GetCustomerDetails', $scope.customerData, { "Authorization": "Bearer " + commonUtils.readCookie("accessToken") }).
            // then(function (response) {
            //	      viewModelHelper.CloseProgress();
            //	      $scope.gridShow = true;
            //	      if (response.data.length > 0 && response.data != 'null') {
            //	          createColumnForCustomerLookupGrid();
            //	          $scope.gridOptions.noRecord = true;
            //	          $scope.gridOptions.data = response.data;
            //	          $scope.updatePagination();
            //	          $scope.gridOptions.paginationCurrentPage = $scope.gridOptions.currPage;
            //	          $scope.currentPageSize = $scope.gridOptions.paginationPageSize;
            //	          $scope.currentPageNo = $scope.gridOptions.currPage;
            //	      }
            //	      else {
            //	          $scope.gridOptions.noRecord = false;
            //	      }
            //	  }, function (response) {
            //	      viewModelHelper.CloseProgress();
            //	      validationMsg.error([Messages.InternalServerError]);
            //	      validationMsg.showLookupMessage(true);
            //	  });

        }

        $scope.reset = function (customerForm) {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            $scope.formData = {
                Id: '',
                FirstName: '',
                MiddleName: '',
                LastName: '',
                PreferredName: '',
                CustomerStatus: '',
                CustomerName: '',
                CompanyName: '',
                City: '',
                State: '',
                Country: '',
                Zip: '',
                Phone: '',
                Email: '',
                CustomerType: '',
                CustomerRole: 'AFF',
                DOB: '',
                Gender: '',
                SSN: '',
            };
            $scope.createBtnShow = false;
            customerForm.ddlStatus.$dirty = false;
        }

        $scope.NavigateMaintainCustomer = function () {
            validationMsg.clear();
            validationMsg.showLookupMessage(false);
            var selectedRow = $scope.gridApiAffiliate.selection.getSelectedRows();
            if (selectedRow.length == 1) {
                $scope.UpdateParentGridRoles(selectedRow[0]);
            } else {
                validationMsg.error([Messages.SelectRecord]);
                validationMsg.showLookupMessage(true);
            }
        };

        $scope.UpdateParentGridRoles = function (selectedRow) {
            angular.element('#' + $scope.ControllerName).scope()[$scope.ViewModelName] = {
                CustomerId: selectedRow.Id,
                CustomerName: selectedRow.CustomerName
            };
            $('#' + $scope.DivId).dialog('close');
        }

        $scope.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApiAffiliate = gridApi;
        }

        function CustomerLookupCountPages() {
            if ($scope.gridOptions.data.length > 0) {
                var totPages = Math.ceil($scope.gridOptions.data[0].totalRecords / $scope.gridOptions.paginationPageSize);
                $scope.gridOptions.paginationTotalPages = Math.ceil($scope.gridOptions.data[0].totalRecords / $scope.gridOptions.paginationPageSize);
            }
        }

        function CustomerLookupRowDetails() {
            if ($scope.gridOptions.data.length > 0) {
                $scope.gridOptions.totalRecords = $scope.gridOptions.data[0].totalRecords;
                $scope.gridOptions.rowMin = (($scope.gridOptions.currPage - 1) * $scope.gridOptions.paginationPageSize) + 1;
                $scope.gridOptions.rowMax = (($scope.gridOptions.currPage * $scope.gridOptions.paginationPageSize) > $scope.gridOptions.totalRecords) ? $scope.gridOptions.totalRecords : ($scope.gridOptions.currPage * $scope.gridOptions.paginationPageSize);
            }
        }

        $scope.jumpToPage = function (e) {
            if (e.keyCode == 13) {
                if ($scope.gridOptions.currPage > $scope.gridOptions.paginationTotalPages) {
                    alert(Messages.InvalidPageNo);
                    $scope.gridOptions.currPage = $scope.currentPageNo;
                    return false;
                }
                $scope.SearchData();
            }
        }

        $scope.CancelCustomerSearch = function () {
            $('#' + $scope.DivId).dialog('close');
        };
    }]);
/************************************************************ Affiliate Lookup End*********************************************************/

/****************************************************** Confirm On Exit Directive Start ********************************************/
CommonDirectiveService.directive('confirmOnExit', function () {
    return {
        restrict: 'A',
        link: function ($scope, elem, attrs) {
            window.onbeforeunload = function () {

                if (angular.element(elem[0]).hasClass('ng-dirty') && !angular.element(elem[0]).hasClass('ng-submitted')) {
                    return "Unsaved data will be lost.";
                }
            }

            $scope.$on('$locationChangeStart', function (event, next, current) {
                if (angular.element(elem[0]).hasClass('ng-dirty') && !angular.element(elem[0]).hasClass('ng-submitted')) {
                    if (!confirm("The changes you made are not saved.\nAre you sure you want to exit the screen?")) {
                        event.preventDefault();
                    }
                }
            });
        }
    }
});
/******************************************************* Confirm On Exit Directive End *****************************************************/

/************************************************* Confirm UnSaved Changes Exit Directive Start ***********************************************/
CommonDirectiveService.directive('confirmUnsavedChanges', function () {
    return {
        priority: -1,
        restrict: 'A',
        scope: {
            confirmUnsavedChanges: '='
        },
        link: function (scope, elem, attrs) {
            elem.bind('click', function (e) {
                if (scope.confirmUnsavedChanges) {
                    if (!confirm("The changes you made are not saved.\nAre you sure you want to exit the screen?\nClick Ok to exit, or Cancel to return to the record you are editing.")) {
                        e.stopImmediatePropagation();
                        e.preventDefault();
                    }
                }
            });
        }
    }
});
/************************************************* Confirm UnSaved Changes Exit Directive End ***********************************************/

/************************************************* No change error popup on save Directive Start ***********************************************/
CommonDirectiveService.directive('noChangeCheck', function () {
    return {
        priority: -1,
        restrict: 'A',
        scope: {
            noChangeCheck: '='
        },
        link: function (scope, elem, attrs) {
            elem.bind('click', function (e) {
                if (!scope.noChangeCheck) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    alert("No changes were detected");
                }
            });
        }
    }
});
/************************************************* No change error popup on save Directive End ***********************************************/

/************************************************* No dirty check Directive Start ***********************************************/
CommonDirectiveService.directive('noDirtyCheck', function (validationMsg) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var alwaysFalse = {
                get: function () {
                    return false;
                },
                set: function () { }
            };
            Object.defineProperty(ctrl, '$pristine', alwaysFalse);
            Object.defineProperty(ctrl, '$dirty', alwaysFalse);
        }
    }
});
/*************************************************No dirty check Directive End ***********************************************/

/************************************************************ Listbox with checkbox Start***********************************************************/
CommonDirectiveService.directive('checklistModel', ['$parse', '$compile', function ($parse, $compile) {
    // contains
    function contains(arr, item, comparator) {
        if (angular.isArray(arr)) {
            for (var i = arr.length; i--;) {
                if (comparator(arr[i], item)) {
                    return true;
                }
            }
        }
        return false;
    }

    // add
    function add(arr, item, comparator) {
        arr = angular.isArray(arr) ? arr : [];
        if (!contains(arr, item, comparator)) {
            arr.push(item);
        }
        return arr;
    }

    // remove
    function remove(arr, item, comparator) {
        if (angular.isArray(arr)) {
            for (var i = arr.length; i--;) {
                if (comparator(arr[i], item)) {
                    arr.splice(i, 1);
                    break;
                }
            }
        }
        return arr;
    }
    function postLinkFn(scope, elem, attrs) {
        // exclude recursion, but still keep the model
        var checklistModel = attrs.checklistModel;
        attrs.$set("checklistModel", null);
        // compile with `ng-model` pointing to `checked`
        $compile(elem)(scope);
        attrs.$set("checklistModel", checklistModel);

        // getter / setter for original model
        var getter = $parse(checklistModel);
        var setter = getter.assign;
        var checklistChange = $parse(attrs.checklistChange);
        var checklistBeforeChange = $parse(attrs.checklistBeforeChange);

        // value added to list
        var value = attrs.checklistValue ? $parse(attrs.checklistValue)(scope.$parent) : attrs.value;


        var comparator = angular.equals;

        if (attrs.hasOwnProperty('checklistComparator')) {
            if (attrs.checklistComparator[0] == '.') {
                var comparatorExpression = attrs.checklistComparator.substring(1);
                comparator = function (a, b) {
                    return a[comparatorExpression] === b[comparatorExpression];
                };

            } else {
                comparator = $parse(attrs.checklistComparator)(scope.$parent);
            }
        }

        // watch UI checked change
        scope.$watch(attrs.ngModel, function (newValue, oldValue) {
            if (newValue === oldValue) {
                return;
            }

            if (checklistBeforeChange && (checklistBeforeChange(scope) === false)) {
                scope[attrs.ngModel] = contains(getter(scope.$parent), value, comparator);
                return;
            }

            setValueInChecklistModel(value, newValue);

            if (checklistChange) {
                checklistChange(scope);
            }
        });

        function setValueInChecklistModel(value, checked) {
            var current = getter(scope.$parent);
            if (angular.isFunction(setter)) {
                if (checked === true) {
                    setter(scope.$parent, add(current, value, comparator));
                } else {
                    setter(scope.$parent, remove(current, value, comparator));
                }
            }

        }

        // declare one function to be used for both $watch functions
        function setChecked(newArr, oldArr) {
            if (checklistBeforeChange && (checklistBeforeChange(scope) === false)) {
                setValueInChecklistModel(value, scope[attrs.ngModel]);
                return;
            }
            scope[attrs.ngModel] = contains(newArr, value, comparator);
        }

        // watch original model change
        // use the faster $watchCollection method if it's available
        if (angular.isFunction(scope.$parent.$watchCollection)) {
            scope.$parent.$watchCollection(checklistModel, setChecked);
        } else {
            scope.$parent.$watch(checklistModel, setChecked, true);
        }
    }

    return {
        restrict: 'A',
        priority: 1000,
        terminal: true,
        scope: true,
        compile: function (tElement, tAttrs) {
            if ((tElement[0].tagName !== 'INPUT' || tAttrs.type !== 'checkbox') && (tElement[0].tagName !== 'MD-CHECKBOX') && (!tAttrs.btnCheckbox)) {
                throw 'checklist-model should be applied to `input[type="checkbox"]` or `md-checkbox`.';
            }

            if (!tAttrs.checklistValue && !tAttrs.value) {
                throw 'You should provide `value` or `checklist-value`.';
            }

            // by default ngModel is 'checked', so we set it if not specified
            if (!tAttrs.ngModel) {
                // local scope var storing individual checkbox model
                tAttrs.$set("ngModel", "checked");
            }

            return postLinkFn;
        }
    };
}]);
/************************************************************ Listbox with checkbox End*************************************************************/

/******************** Screen Idle Timeout Start************************/
CommonDirectiveService.directive('screenidle', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            //scope.contentUrl = attrs.templateUrl;
        },
        scope: {},
        controller: "@",
        name: "controllerName"
    }
}).controller('idleTimeCtrl', ['$scope', '$http', 'myGrid', 'appConfig', 'viewModelHelper', '$routeParams', 'Messages', 'validationMsg', 'validationPatterns', 'Idle', function ($scope, $http, myGrid, appConfig, viewModelHelper, $routeParams, Messages, validationMsg, validationPatterns, Idle) {
    $scope.started = false;

    function closeModals() {
        if ($scope.warning) {
            $("#dvDialog").dialog().dialog('close');
            $scope.warning = false;
        }

        if ($scope.timedout) {
            $scope.timedout.close();
            $scope.timedout = false;
        }
    }

    $scope.$on('IdleStart', function () {
        closeModals();
        viewModelHelper.ShowDialog("You'll be logged out in few second(s).", 'Idle Timeout', '200', '200');
        $scope.warning = true;
    });

    $scope.$on('IdleEnd', function () {
        closeModals();
    });

    $scope.$on('IdleTimeout', function () {
        closeModals();
        $http.get(appConfig.basePath + 'umbraco/surface/Login/IdleTimeOut').
			  then(function (response) {
			      if (response != null) {
			          window.location.href = response.data;
			      }
			  }, function (response) {
			      viewModelHelper.CloseProgress();
			      validationMsg.error([Messages.InternalServerError]);
			      validationMsg.showLookupMessage(true);
			  });

        $scope.timedout = true;
    });

    $scope.start = function () {
        closeModals();
        Idle.watch();
        $scope.started = true;
    };

    $scope.stop = function () {
        closeModals();
        Idle.unwatch();
        $scope.started = false;
    };
    Idle.watch();
}]).config(function (IdleProvider) {
    IdleProvider.idle(1200);
    IdleProvider.timeout(60);
});

/******************** Screen Idle Timeout End************************/

/***************************************************************************** Jump To Page Start *****************************************************************************/

CommonDirectiveService.directive('jumpToPage', function () {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            element.bind("keypress", function (e) {
                if (isNaN(String.fromCharCode(e.keyCode))) {
                    e.preventDefault();
                }

                if (e.keyCode === 13) {
                    scope.$apply(function () {
                        var gridOptions = scope.$eval(attrs.jumpToPageGridOptions);
                        var pageNo = parseInt(gridOptions.currPage);
                        if (pageNo === null || pageNo === "" || isNaN(pageNo)) {
                            pageNo = gridOptions.paginationCurrentPage;
                            gridOptions.currPage = pageNo;
                        }

                        if (pageNo > gridOptions.paginationTotalPages || pageNo === 0) {
                            alert('Invalid page number');
                            gridOptions.currPage = gridOptions.paginationCurrentPage;
                            return false;
                        }

                        var gridApi = scope.$eval(attrs.jumpToPageGrid);
                        gridApi.pagination.seek(pageNo);
                        scope.callBack();
                    });
                }
            });
        }
    };
});

/****************************************************************************** Jump To Page End ******************************************************************************/

/***************************************************************************** Pagization Start *****************************************************************************/

CommonDirectiveService.directive('customPagination', ["commonUtils", function (commonUtils) {
    return {
        restrict: "E",
        scope: {
            gridApi: '=',
            gridOptions: '=',
            isServerside: '=',
            callBack: '&'
        },
        templateUrl: '/../webapps/Shared/customPagination.html',
        link: function (scope, element, attrs) {
            scope.paginate = function (dir) {
                if (dir === "pageSize") {
                    scope.gridOptions.currPage = Math.floor(((scope.gridOptions.currentPageSize * (scope.gridOptions.currPage - 1)) / scope.gridOptions.paginationPageSize) + 1);
                }

                if (dir === "next") {
                    scope.gridOptions.currPage++;
                }

                if (dir === "prev") {
                    scope.gridOptions.currPage--;
                }

                if (dir === "last" && scope.gridOptions.currPage >= scope.gridOptions.paginationTotalPages) {
                    return false;
                }

                if (dir === "last" && scope.gridOptions.currPage < scope.gridOptions.paginationTotalPages) {
                    scope.gridOptions.currPage = scope.gridOptions.paginationTotalPages;
                }

                if (dir === "first" && scope.gridOptions.currPage <= 1) {
                    return false;
                }

                if (dir === "first" && scope.gridOptions.currPage > 1)
                    scope.gridOptions.currPage = 1;

                if (scope.gridOptions.currPage > scope.gridOptions.paginationTotalPages) {
                    scope.gridOptions.currPage = scope.gridOptions.paginationTotalPages;
                    //return false;
                }
                if (scope.gridOptions.currPage < 1) {
                    scope.gridOptions.currPage = scope.gridOptions.paginationCurrentPage;
                    //return false;
                }
                scope.callBack();
            };
        }
    };
}]);

/****************************************************************************** Pagization End ******************************************************************************/