
//replace icons with FontAwesome icons like above
var app = angular.module('WebRMS', ['localytics.directives', 'ngTagsInput']);
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

app.run(function ($rootScope, $timeout, $window) {
    $rootScope.PageMessage = { ShowMessage: false, MessageType: 'E', Title: '', ErrorMessages: [], SuccessMessages: [], ControlID: undefined }; //MessageType either S-Success/E-Error

    $rootScope.IncidentReviewList = { ID: 0, IncidentNumber: '', AgencyID: 0, AdhocQueryID: 0 };
    $rootScope.RemoveAllFromSelect = function (chosenDropDown, allValue) {
        //var lastSelectedValue = $(window.event.srcElement).parents().find(".select2-chosen option, .chzn-select option").eq($(window.event.target).attr("data-option-array-index")).attr("value");
        var lastSelectedValue = $(window.event.srcElement).parents().find("#" + chosenDropDown + " .select2-chosen option, #" + chosenDropDown + ".chzn-select option").eq($(window.event.target).attr("data-option-array-index")).attr("value");

        if (lastSelectedValue != undefined)
            lastSelectedValue = lastSelectedValue.replace("string:", "");
        var control = $('#' + chosenDropDown);
        var scopeProperty = { name: "" };

        if ((lastSelectedValue != null && lastSelectedValue == allValue) || control.val() == null) {
            control.val(lastSelectedValue);
            $('#' + chosenDropDown + ' select').trigger("chosen:updated");
            var scope = getScopeObject(control, chosenDropDown, scopeProperty);
            scope[scopeProperty.name] = [allValue];
        }
        else if (control.val() != null && control.val().length > 1) {
            var values = control.val();
            values = jQuery.grep(values, function (value) {
                return value != allValue;
            });
            control.val(values)
            $('#' + chosenDropDown + ' select').trigger("chosen:updated");
            var scope = getScopeObject(control, chosenDropDown, scopeProperty);
            scope[scopeProperty.name] = values;
        }
    }
    $rootScope.GoTo = function(name)
    {
        $timeout(function () {
            var element = $window.document.getElementById(name);
            if (element) {
                element.focus();
                if ($("#" + name) != undefined && $("#" + name).is(":visible") == false)
                    $("#" + name).trigger('chosen:activate')
            }
        });
    }

    $rootScope.GetDisplayText = function(name)
    {
        var element = $window.document.getElementById(name);
        if (element != undefined)
            return element.getAttribute("displaytext");
        else
            return name;
    }

    $rootScope.GetShowMessageStatus = function (IsInvalid) {
        // Page validation 
        if (IsInvalid == true || ($rootScope.PageMessage != null && $rootScope.PageMessage.ErrorMessages.length > 0))
            return 1;
        else if ($rootScope.PageMessage != null && $rootScope.PageMessage.SuccessMessages.length > 0)
            return 2;
        else
            return 0;
    }
});

function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : event.keyCode
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;
 
          return true;
       }

function getScopeObject(control, chosenDropDown, scopeProperty) {
    var scope = angular.element(document.getElementById(chosenDropDown)).scope()
    var modelNames = control.attr("ng-model").split(".");
    for (var i = 0; i < modelNames.length; i++) {
        if (i == (modelNames.length - 1))
            scopeProperty.name = modelNames[i];
        else
            scope = scope[modelNames[i]];
    }
    return scope;
}

app.service('IncidentListService', function ($rootScope, $http, $q) {
    this.AddIncidentForReview = function (obj) {
        $rootScope.IncidentReviewList.push(obj);
    };

    this.AddIncidentList = function (object) {
        $rootScope.IncidentReviewList = object;
    }

    this.GetIncidentForReview = function () {
        return $rootScope.IncidentReviewList;
    };

    this.ClearIncidentList = function () {
        $rootScope.IncidentReviewList = {};
    }

    return {
        AddIncidentForReview: this.AddIncidentForReview,
        GetIncidentForReview: this.GetIncidentForReview,
        AddIncidentList: this.AddIncidentList,
        ClearIncidentList : this.ClearIncidentList
    };
});

app.service('pageMessageService', function ($rootScope, $http, $q) {
    this.SetMessage = function (result, messageTitle) {
        if (result != null && result.data != null && (result.data.success == false || result.data.Result == 'ERROR')) {
            $rootScope.PageMessage.ShowMessage = true;
            $rootScope.PageMessage.MessageType = 'E';
            $rootScope.PageMessage.ErrorMessages.push({ Message: result.data.Message });
            //$rootScope.PageMessage.Title = messageTitle;
            return false;
        }
        else {
            return true;
        }
    },
    this.ResetValidationMessages = function () {
        $rootScope.PageMessage = { ShowMessage: false, MessageType: 'E', Title: '', ErrorMessages: [], SuccessMessages: [] };
    },
    this.SetValidationMessage = function(message, controlId)
    {
        $rootScope.PageMessage.ShowMessage = true;
        $rootScope.PageMessage.MessageType = 'E';
        $rootScope.PageMessage.ErrorMessages.push({ Message: message, ControlID: controlId });
    },
    this.SetSuccessMessage = function (message) {
        $rootScope.PageMessage.ShowMessage = true;
        $rootScope.PageMessage.MessageType = 'S';
        $rootScope.PageMessage.SuccessMessages.push({ Message: message });
    },
    this.Get = function (url, failureFunc) {
         var deferred = $q.defer();
         $rootScope.PageMessage = { ShowMessage: false, MessageType: 'E', Title: '', ErrorMessages: [], SuccessMessages: [] };
         $("#loading").show();
         $http.get(url).then(function (result) {
             if (result != null && result.data != null && (result.data.success == false || result.data.Result == 'ERROR')) {
                 $rootScope.PageMessage.ShowMessage = true;
                 $rootScope.PageMessage.MessageType = 'E';
                 if (result.data.Message == 'ACCESS DENIED')
                     $rootScope.PageMessage.ErrorMessages.push({ Message: "Your session might be expired or action is not authorized. Please refresh the page." });
                 else 
                    $rootScope.PageMessage.ErrorMessages.push({ Message: result.data.Message });
                 if (failureFunc != undefined)
                     failureFunc();
                 deferred.reject(result);
             }
             else
                 deferred.resolve(result);
         },
        function (error) {
            $rootScope.PageMessage.ShowMessage = true;
            $rootScope.PageMessage.MessageType = 'E';
            $rootScope.PageMessage.ErrorMessages.push({ Message: "Something went wrong in the system, please try again." });
            if (failureFunc != undefined)
                failureFunc();
            return deferred.reject(error);
        })
        .finally(function () {
            if ($("#loading") != undefined)
                $("#loading").hide();
        });
        return deferred.promise;
    },
    this.PostWithCSRFToken = function (url, postData, config, failureFunc) {
        var deferred = $q.defer();
        $rootScope.PageMessage = { ShowMessage: false, MessageType: 'E', Title: '', ErrorMessages: [], SuccessMessages: [] };
        $("#loading").show();
        
        $http.post(url, postData, config).then(function (result) {
            if (result != null && result.data != null && (result.data.success == false || result.data.Result == 'ERROR')) {
                $rootScope.PageMessage.ShowMessage = true;
                $rootScope.PageMessage.MessageType = 'E';
                if (result.data.Message == 'ACCESS DENIED')
                    $rootScope.PageMessage.ErrorMessages.push({ Message: "Your session might be expired or action is not authorized. Please refresh the page." });
                else
                    $rootScope.PageMessage.ErrorMessages.push({ Message: result.data.Message });
                if (angular.isFunction(failureFunc) == true)
                    failureFunc();
                deferred.reject(result);
            }
            else
                deferred.resolve(result);
        },
       function (error) {
           $rootScope.PageMessage.ShowMessage = true;
           $rootScope.PageMessage.MessageType = 'E';
           $rootScope.PageMessage.ErrorMessages.push({ Message: "Something went wrong in the system, please try again." });
           if (angular.isFunction(failureFunc))
               failureFunc();
           return deferred.reject(error);
       })
       .finally(function () {
           if ($("#loading") != undefined)
               $("#loading").hide();
       });
        return deferred.promise;
    },
    this.Post = function (url, postData, failureFunc) {
        var deferred = $q.defer();
        $rootScope.PageMessage = { ShowMessage: false, MessageType: 'E', Title: '', ErrorMessages: [], SuccessMessages: [] };
        $("#loading").show();
        $http({
            url: url, data: postData, method: "POST"
            }).then(function (result) {
            if (result != null && result.data != null && (result.data.success == false || result.data.Result == 'ERROR')) {
                $rootScope.PageMessage.ShowMessage = true;
                $rootScope.PageMessage.MessageType = 'E';
                if (result.data.Message == 'ACCESS DENIED')
                    $rootScope.PageMessage.ErrorMessages.push({ Message: "Your session might be expired or action is not authorized. Please refresh the page." });
                else
                    $rootScope.PageMessage.ErrorMessages.push({ Message: result.data.Message });
                if (angular.isFunction(failureFunc) == true)
                    failureFunc();
                deferred.reject(result);
            }
            else
                deferred.resolve(result);
        },
       function (error) {
           $rootScope.PageMessage.ShowMessage = true;
           $rootScope.PageMessage.MessageType = 'E';
           $rootScope.PageMessage.ErrorMessages.push({ Message: "Something went wrong in the system, please try again." });
           if (angular.isFunction(failureFunc))
               failureFunc();
           return deferred.reject(error);
       })
       .finally(function () {
           if ($("#loading") != undefined)
               $("#loading").hide();
       });
        return deferred.promise;
    }
});

app.directive('rptmodal', function () {
    return {
        template: '<div class="modal fade" >' +
            '<div class="modal-dialog modal-lg" style="width: 400px; margin: 300px auto;!important">' +
              '<div class="modal-content"  style="border: solid 1px #ccc;border-radius:5px 7px;">' +
              '<div class="modal-header" style="padding: 10px;!important">' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="font-size: 20px;!important"><span aria-hidden="true">&times;</span></button>' +
                 '<h5 class="modal-title">{{ title }}</h5>' +
                '</div>' +
                '<div class="modal-body" ng-transclude ></div>' +
              '</div>' +
            '</div>' +
          '</div>',
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: true,
        link: function postLink(scope, elm, attr) {
            scope.title = attr.title;
            if (attr.mnisearch == undefined) {
                scope.$watch(attr.visible, function (value) {
                    if (value == true)
                        $(elm).modal('show');
                    else
                        $(elm).modal('hide');
                });
            }
            else {
                scope.$watch(attr.visible, function (value) {
                    if (attr.visible == true)
                        $(elm).modal('show');
                    else
                        $(elm).modal('hide');
                });
            }

            $(elm).on('shown.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attr.visible] = true;
                });
            });

            $(elm).on('hidden.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attr.visible] = false;
                });
            });
        }
    };
});

app.directive('modal', function () {
    return {
        template: '<div class="modal fade">' +
            '<div class="modal-dialog modal-lg">' +
              '<div class="modal-content">' +
                '<div class="modal-header">' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                 '<h4 class="modal-title">{{ title }}</h4>' +
                '</div>' +
                '<div class="modal-body" ng-transclude></div>' +
              '</div>' +
            '</div>' +
          '</div>',
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: true,
        link: function postLink(scope, elm, attr) {
            scope.title = attr.title;
            if (attr.mnisearch == undefined) {
                scope.$watch(attr.visible, function (value) {
                    if (value == true)
                        $(elm).modal('show');
                    else
                        $(elm).modal('hide');
                });
            }
            else {
                scope.$watch(attr.visible, function (value) {
                    if (attr.visible == true)
                        $(elm).modal('show');
                    else
                        $(elm).modal('hide');
                });
            }

            $(elm).on('shown.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attr.visible] = true;
                });
            });

            $(elm).on('hidden.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attr.visible] = false;
                });
            });
        }
    };
});

app.directive('dismodel', function () {
    return {
        restrict: 'A',
        //transclude: true,
        scope: true,
        link: function postLink(scope, elm, attr) {
            if (attr.dismodel != undefined) {
                // Helps to control the disability of chosen dropdowns 
                try {
                    var evalValue = attr.dismodel;
                    if ($(".chosen-select") != undefined) {
                        $(elm).show();
                        if (evalValue.indexOf('entity') > 0 || evalValue.length > 10) //add scope prior to the javascript entity name. example, "entity.ID" should be "scope.entity.ID"
                            evalValue = "scope." + evalValue;
                        if (eval(evalValue)) {
                            var timeout = setInterval(function () {
                                if ($(elm) != undefined) {
                                    $(elm).parent().find(".chosen-select").prop('disabled', true).trigger('chosen:updated');
                                    $(elm).parent().find(".disable-chosen").off('click');
                                    scope.$apply();
                                }
                            }, 1000);
                        }
                        else {
                            var timeout = setInterval(function () {
                                if ($(elm) != undefined) {
                                    $(elm).parent().find(".chosen-select").prop('disabled', false).trigger('chosen:updated');
                                    //$(elm).parent().find(".disable-chosen").off('click');
                                    scope.$apply();
                                }
                            }, 1000);
                        }
                    }
                }
                catch (err) { }
            }
            //if (attr.dismodel == "hide") {
            //    scope.$watch(elm.attr, function (value) {
            //        $(elm).hide();
            //    });
            //}
            //else if (attr.dismodel == "read") {

            //    var objects = $(elm).find(":input");
            //    if (objects != undefined)
            //        objects.prop("disabled", true);
            //    else
            //        $(elm).prop("disabled", true);
            //}
            //else {
            //    $(elm).show();
            //    var objects = $(elm).find(":input");
            //    if (objects != undefined)
            //        objects.prop("disabled", false);
            //    else
            //        $(elm).prop("disabled", false);
            //}



            //$(elm).on('shown.bs.modal', function () {
            //    scope.$apply(function () {
            //        scope.$parent[attr.visible] = true;
            //    });
            //});

            //$(elm).on('hidden.bs.modal', function () {
            //    scope.$apply(function () {
            //        scope.$parent[attr.visible] = false;
            //    });
            //});
            return elm;
        }
    };
});

app.directive('ngModelOnblur', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1, // needed for angular 1.2.x
        link: function (scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return;

            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function () {
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(elm.val());
                });
            });
        }
    };
});

app.directive('ngModelOnblurWtihAgeCalc', function () {
    return {
        restrict: 'A',
        scope: {
            relativeDate: '=',
        },
        require: 'ngModel',
        priority: 1, // needed for angular 1.2.x
        link: function (scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return;

            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function () {
                scope.$parent.$apply(function () {
                    ngModelCtrl.$setViewValue(elm.val());
                    if (scope.relativeDate != '' && scope.relativeDate != null && scope.relativeDate != undefined) {
                        if (ngModelCtrl.$valid && ngModelCtrl.$dirty) {
                            scope.$parent.entity.Age = age(elm.val(), scope.relativeDate);
                            ngModelCtrl.$setPristine();
                        }
                    }
                });
            });
        }
    };
});

//app.directive('select', function () {
//    return {
//        restrict: 'E',
//        require: '?ngModel',
//        link: function (scope, element, attr, ngModelCtrl) {
//            if (ngModelCtrl && attr.multiple) {
//                ngModelCtrl.$isEmpty = function (value) {
//                    return !value || value.length === 0;
//                }
//            }
//        }
//    }
//});

app.directive('convertNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attr, ctrl) {
            ctrl.$parsers.push(function (value) {
                //console.log('parse', value);
                return parseInt(value, 10);
            });

            ctrl.$formatters.push(function (value) {
                //console.log('format', value);
                if (value == null || value == undefined)
                    return "";
                else
                    return value.toString();
            });
        }
    }
});

app.directive('enforceMaxTags', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelController) {
            var maxTags = attrs.maxTags ? parseInt(attrs.maxTags, '10') : null;
            ngModelController.$validators.checkLength = function (value) {
                if (value && maxTags && value.length > maxTags) {
                    value.splice(value.length - 1, 1);
                }
                return value;
            };
        }
    };
});

function age(dob, relativeDate) {
    var birthDate = new Date(dob);

    if (!isNaN(birthDate)) {
        var _relativeDate = new Date(relativeDate);

        var age = _relativeDate.getFullYear() - birthDate.getFullYear();
        var m = _relativeDate.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && _relativeDate.getDate() < birthDate.getDate())) {
            age--;
        };

        if (age > 99) age = 99;

        if (age < 0)
            age = "";

        if (age == 0) {
            var _totaldays = daysBetween(_relativeDate, birthDate);

            if (_totaldays == 0)
                age = "NN";
            else if ((_totaldays <= 6) && (_totaldays >= 1))
                age = "NB";
            else if ((_totaldays <= 364) && (_totaldays >= 7))
                age = "BB";
        }

        return age;

    }
    else
        return "";
}


function daysBetween(today, birth) {

    // Do the math.
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var millisBetween = today.getTime() - birth.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    return Math.round(days);
}
function daysInMonth(iMonth, iYear) {
    if (iMonth < 0 || iMonth > 11)
        return 0;

    if (iMonth == 1)
        return (28 + isLeapYear(iYear));
    else
        if (iMonth == 3 || iMonth == 5 || iMonth == 8 || iMonth == 10)
            return (30);
        else
            return (31);
}

function isLeapYear(iYear) {
    return (iYear % 4 ? 0 : iYear % 100 ? 1 : iYear % 400 ? iYear == 200 ? 1 : 0 : 1);
}

function updatePagerIcons(table) {
    var replacement =
    {
        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
    };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    })
}

function GetStringDate(jsonDate) {
    var date = new Date(parseInt(jsonDate.substr(6)))
    var datePart = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
    var monthPart = date.getMonth() > 8 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
    return monthPart + '/' + datePart + '/' + date.getFullYear();
}

function formatdate(oevent) {
    var val;
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {   
        if (obj.value.length == 2) obj.value = obj.value + "/";
        if (obj.value.length == 5) obj.value = obj.value + "/";
        return true;
    }
    else {
        if (slashonly(oevent)) {
            if (obj.value.length == 1) { obj.value = "0" + obj.value; return true; }
            else if (obj.value.length == 4) {
                val = obj.value.substring(0, 3) + "0" + obj.value.substring(5, 3);
                obj.value = val; return true;
            }
            else return false;
        }
        else if (backspaceonly(oevent))
        { return true; }
        else return false;
    }

}

function formatJSONDate(value) {
    if (value == null) {
        return "";
    }
    else {
        var date = eval(value.replace(/\/Date\((.*?)\)\//gi, "new Date($1)"));
        var dateString = ((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
        if (dateString == '1/1/1')
        { return ""; }
        else
        { return dateString; }
    }
}

function validateDate(obj) {
    if ($(obj).val() != "") {
        var date = new Date($(obj).val());
        if (Object.prototype.toString.call(date) === "[object Date]") {
            // it is a date
            if (isNaN(date.valueOf())) {
                bootbox.alert($(obj).val() + " is not a valid date.", function () { $(obj).val(''); $(obj).focus(); });
                return false;
            }
        }
        else {
            bootbox.alert($(obj).val() + " is not a valid date.", function () { $(obj).val(''); $(obj).focus(); });
            return false;
        }
    }
}

function isDate(val) {
    if (val != "") {
        var date = new Date(val);
        if (Object.prototype.toString.call(date) === "[object Date]") {
            // it is a date
            if (isNaN(date.valueOf())) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
    else{
        return false;
    }
}

function convertJsonToDate(date) {
    var localDate = new Date(date.match(/\d+/)[0] * 1)
    return localDate.getMonth() + 1 + '/' + localDate.getDate() + '/' + localDate.getFullYear();
}

function convertToSSNFormat(value) {
    var ssnString = "";
    value = $.trim(value);
    if (value != undefined && value != null && value.length > 0) {
        ssnString = value.substring(0, 3);
        if (value.length > 3)
            ssnString = ssnString + '-' + value.substring(3, 5);
        if (value.length > 5)
            ssnString = ssnString + '-' + value.substring(5);
    }
    return ssnString;
}

function convertToPhoneFormat(value) {
    var phoneString = "";
    if (value != undefined && value != null && value.length > 0) {
        phoneString = value.substring(0, 3);
        if (value.length > 3)
            phoneString = phoneString + '-' + value.substring(3, 6);
        if (value.length > 6)
            phoneString = phoneString + '-' + value.substring(6);
    }
    return phoneString;
}

function convertToZipFormat(value) {
    var zipString = "";
    if (value != undefined && value != null && value.length > 0) {
        zipString = value.substring(0, 5);
        if (value.length > 5)
            phoneString = phoneString + '-' + value.substring(5);
    }
    return zipString;
}


function formattime(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {
        if (oevent.value.length == 2) {
            oevent.value = oevent.value + ":"; // {
            return true;
        }
    }
    else {
        if (colononly(oevent)) {
            if (oevent.value.length == 1) {
                oevent.value = "0" + oevent.value;
                return true;
            }
            else return false;
        }
        else if (backspaceonly(oevent))
        { return true; }
        else return false;
    }
    return false;
}

function validTimeField(obj) {
    var time = document.getElementsByClassName('validateTime');
    for (var i = 0; i < time.length; i++) {
        time[i].addEventListener('keyup', function (e) {
            var reg = /[0-9]/;
            if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number 
            if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
        });
    };
}

function formatssn(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {
        if (obj.value.length == 3) obj.value = obj.value + "-";
        if (obj.value.length == 6) obj.value = obj.value + "-";
        return true;
    }
    else if (backspaceonly(oevent))
    { return true; }
    else return false;
}

function formatphone(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {
        if (obj.value.length == 3) obj.value = obj.value + "-";
        if (obj.value.length == 7) obj.value = obj.value + "-";
        return true;
    }
    else if (backspaceonly(oevent))
    { return true; }
    else return false;
}

function formatzip(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {
        if (obj.value.length == 5) obj.value = obj.value + "-";
        return true;
    }
    else if (backspaceonly(oevent))
    { return true; }
    else if (oevent.keyCode == 37 || oevent.keyCode == 39 || oevent.keyCode == 123)
    { return true; }
    else return false;
}

function formatinctxt(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericOnly(oevent))
    { return true; }
    else return false;
}

function formatString(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenCommaPeriodSpaceOnly(oevent)) {
        return true;
    }
    else return false;
}
function formatAddress(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenCommaPeriodSpaceOnly(oevent)) {
        return true;
    }
    else if (oevent.keyCode == 188 || oevent.keyCode == 189 || oevent.keyCode == 190 || oevent.keyCode == 191 || oevent.keyCode == 55 || oevent.keyCode == 222 || oevent.keyCode == 51){
        return true;
    }
    else
        return false;
}

function formatAddressCity(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (AlphaCommaPeriodHypenForwardslashAmpersandQuotePoundCharactersOnly(oevent)) {
        return true;
    }
    else if (oevent.keyCode == 188 || oevent.keyCode == 189 || oevent.keyCode == 190 || oevent.keyCode == 191 || oevent.keyCode == 222 || oevent.keyCode == 32 ) {
        return true;
    }
    else
        return false;
}

function formatFieldForAlphanumericSpace(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (AlphaNumericSpaceOnly(oevent)) {
        return true;
    }
    else return false;
}
function formatIncidentNumber(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenOnly(oevent)) {
        return true;
    }
    else return false;
}
// changing the function upperAlphaNumericOnly to alphaNumericOnly for the user to type in lower case
function formatORINumber(oevent) {
    if (alphaNumericOnly(oevent))
    { return true; }
    else return false;
}
function formatCityIndicator(oevent) {
    if (upperAlphaNumericOnly(oevent))
    { return true; }
    else return false;
}
function formatDecimal(oevent) {
    if (numbersDecimalonly(oevent))
    { return true; }
    else return false;
}
function formatInteger(oevent) {
    if (numbersonly(oevent))
    { return true; }
    else return false;
}
function formatNegInteger(oevent) {
    if (negNumbersOnly(oevent))
    { return true; }
    else return false;
}

function formatStateSpecInteger(oevent) {
    //var stateCode = document.getElementById('stateCode');
    //if (stateCode != null && stateCode.value == "PA") {
    var allowNegetiveNumbers = document.getElementById('allowNegetiveNumbers');
    if (allowNegetiveNumbers != null && allowNegetiveNumbers.value.toLowerCase() == "false") {
        if (numbersonly(oevent)) {
            return true
        }
    }
    else {
        if (negNumbersOnly(oevent))
        { return true; }
    }
    return false;
}
function formatNegDecimal4(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (negNumberDecimalOnly(oevent))
    {
        if (only4(obj,oevent))
        {
            return true;
        }
        else
        { 
         return false;
        }

    }
    else return false;
}
function formatAge(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonlyAge(oevent))
    { return true; }
    else return false;
}
function formatStatuteCode(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenOnly(oevent)) {
        return true;
    }
    else return false;
}

function formatGAStatuteCode(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenPeriodOnly(oevent)) {
        return true;
    }
    else return false;
}

function formatPAStatuteCode(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (alphaNumericHyphenCommaPeriodSpaceBracketsOnly(oevent))
    {
        return true;
    }
    else return false;
}
function formatAgeOffender(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonlyAgeOffender(oevent))
    { return true; }
    else return false;
}



function formatNIBRSInteger(oevent) {
    var obj = document.getElementById(document.activeElement.id);
    if (numbersonly(oevent)) {
        alert(oevent.value.length);
        if (oevent.value.length < 10) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return false;
    }
}

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true; 
        // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}
function numbersrangeonly(e, numberRange) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;
        // numbers
    else if ((numberRange.indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}
function negNumbersOnly(e) {
    var key;
    var keychar;
    
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
    {
        console.log('else');
        return true;
    }

    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27) || (key == 37) || (key == 38) || (key == 39) || (key == 40))
    { 
        return true;
    } 
    else if (key > 47 && key < 58)
        return true;
    else if ((("-").indexOf(keychar) > -1))
        return true;
    else
        return false;
}

function negNumberDecimalOnly(e) {

    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;

    else if (key > 47 && key < 58)
        return true;
    else if ((("-").indexOf(keychar) > -1))
            return true;
    else if (((".").indexOf(keychar) > -1))
        return true;
    else
        return false;
    }
 
function only4(el,evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;

    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }

    if (charCode == 46 && el.value.indexOf(".") !== -1) {
        return false;
    }  
    el =document.getElementById(el.id);
    if (el.value.indexOf(".") !== -1) {
        var range = document.selection.createRange();

        if (range.text != "") {
        }
        else {
            var number = el.value.split('.');
            if (number.length >0 && number[0].length > 1)
                return false;
            if (number.length == 2 && number[1].length > 3)
        return false;
}
    }

    return true;
}

function numbersonlyAgeOffender(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}
function numbersonlyAge(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // numbers
    else if ((("0123456789NBnb").indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}
function numbersDecimalonly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // numbers
    else if ((("0123456789.").indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}

function numbersOneDecimalonly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;
    else if(keychar == "." && $(e.target) != undefined && $(e.target).val() != undefined && $(e.target).val().indexOf(keychar) > -1) // allow only one decimal point
        return false;
        // numbers
    else if ((("0123456789.").indexOf(keychar) > -1))
        return true;
        //else if ((key>=48 && key<=57) || (key>=96 && key<=105))
        //return true; 
    else
        return false;
}
function slashonly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 191))
        return true;

        // numbers
    else if ((("/").indexOf(keychar) > -1))
        return true;
    else
        return false;
}


function backspaceonly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 8))
        return true;
    else
        return false;
}
function colononly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 186))
        return true;

        // numbers
    else if (((":").indexOf(keychar) > -1))
        return true;
    else
        return false;
}

function isDecimal(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // numbers
    else if ((("0123456789").indexOf(keychar) > -1))
        return true;
    if (
        (key != 46 || $(this).val().indexOf('.') != -1)       // “.” CHECK DOT, AND ONLY ONE.
        )
        return false;
    else
        return false;
}

function periodonly(e) {

    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 186))
        return true;

        // numbers
    else if (((".").indexOf(keychar) > -1))
        return true;
    else
        return false;
}

function alphaNumericOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);

    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").indexOf(keychar) > -1)) {
        return true;
    }
    else if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105))
        return true;
    else
        return false;
}
// Validates number in range 1 to 10. 
function digitKeyOnly(e) {
    var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
    var value = Number(e.target.value + e.key) || 0;

    if ((keyCode >= 37 && keyCode <= 40) || (keyCode == 8 || keyCode == 9 || keyCode == 13) || (keyCode >= 48 && keyCode <= 57)) {
        return isValidNumber(value, 0, 10);
    }
    return false;
}

function isValidNumber(number, minValue, maxValue) {
    return (minValue <= number && number <= maxValue)
}



function alphaNumericHyphenCommaPeriodSpaceOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -.,").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}

function alphaNumericHyphenCommaPeriodSpaceBracketsOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -.,()").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}

function alphaNumericHyphenCommaPeriodOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.,").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}

function alphaNumericHyphenOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}

function alphaNumericHyphenPeriodOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

    // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}


function AlphaCommaPeriodHypenForwardslashAmpersandQuotePoundCharactersOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

    // alpha+numbers
    else if ((("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-/&'#").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}

function AlphaNumericSpaceOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}
function upperAlphaNumericHyphenOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}
function upperAlphaNumericOnly(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    keychar = String.fromCharCode(key);
    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;

        // alpha+numbers
    else if ((("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").indexOf(keychar) > -1)) {
        return true;
    }
    else
        return false;
}
function BuildUploadControl() {
    //$('.ajax-upload-dragdrop').remove();
    $("#divNoImgMsg").hide();
    $('.ajax-file-upload-statusbar').remove();
    $('.ajax-file-upload-error').remove();
    $("#fileuploader").uploadFile({
        url: ImageUploadURL,
        fileName: "filename",
        miltiple: true,
        allowedTypes: allowedTypes,
        showStatusAfterSuccess: false,
        showFileCounter: false,
        showAbort: false,
        showCancel: false,
        maxFileSize: 20480000,
        dynamicFormData: function () {

            var data = { "type": entityType, "entityid": SelectedPersonID }

            return data;

        },

        onSubmit: function (e) {
            isUploadInProgress = true;
        },
        afterUploadAll: function (files) {
            $("#uploaddiv").hide();
            isUploadInProgress = false;
            $("#uploaddiv").hide();
            $.get(GetAllImageIDURL + 'id=' + SelectedPersonID, function (results) { BuildImageSlider(results.imageids, SelectedPersonID); });
        },
        onError: function (files, status, errMsg) {
            isUploadInProgress = false;
        }
    });
}

function BuildImageSlider(imageids, entityID) {
    $('#lightSlider').empty();
    $(".lSPager").remove();

    var slider = $('#lightSlider').lightSlider({ thumbItem: 10, item: 10 });

    if (imageids[0] == "-1") {
        var newEl = ' <li class="lslide"></li>';
        slider.prepend(newEl);
        $("#divNoImgMsg").show();
        $("#imgSlidingDiv").addClass('collapsed');
    }
    else {
        $("#divNoImgMsg").hide();
        for (var i = 0 ; i < imageids.length ; i++) {
            var newEl = ' <li class="lslide"><a href="#" id=' + imageids[i] + ' data-id=' + imageids[i] + '   class="ImageClass" data-item-id=' + entityID + '  rel="b1"><img src="' + ImageURL + 'id=' + imageids[i] + '"></a><a  href="#" data-id=' + imageids[i] + '  id="deleteImg"><br><i class="ace-icon text-danger center fa fa-trash-o bigger-110"></i></a></li>';
            slider.prepend(newEl);
        }
    }
    slider.refresh();
}

function loadPageVar(sVar) {
    return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

function AutoGenerateBarCode(BarCode, ReportNumber1, ReportNumber2, ReportNumber3, SequenceNumber) {
    BarCode = "";
    if (ReportNumber1 != null && ReportNumber1 != undefined && ReportNumber1 != "")
        BarCode = BarCode + ' ' + $.trim(ReportNumber1);

    if (ReportNumber2 != null && ReportNumber2 != undefined && ReportNumber2 != "")
        BarCode = BarCode + ' ' + $.trim(ReportNumber2);

    if (ReportNumber3 != null && ReportNumber3 != undefined && ReportNumber3 != "")
        BarCode = (BarCode + ' ' + $.trim(ReportNumber3));

    BarCode = ($.trim(BarCode));

    BarCode = (BarCode.replace(/\ /g, '-') + ':' + SequenceNumber);

    return BarCode;
}

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

String.prototype.padRight = function (l, c) {
    return this + Array(l - this.length + 1).join(c || " ");
}

function padLeft(str, prefix, max) {
    str = str.toString();
    return str.length < max ? padLeft(prefix + str, prefix, max) : str;
}

function padRight(str, suffix, max) {
    str = str.toString();
    return str.length < max ? padRight(str + suffix, suffix, max) : str;
}

function getFormattedDateTime(date)
{
    return padLeft((date.getMonth() + 1), '0', 2) + "/"
            + padLeft(date.getDate(), '0', 2) + "/"
            + date.getFullYear() + ' '
            + padLeft(date.getHours(), '0', 2) + ':'
            + padLeft(date.getMinutes(), '0', 2) + ' '
            + (date.getHours() < 12 ? 'AM' : 'PM');
}

function getFormattedDate(date) {
    return padLeft((date.getMonth() + 1), '0', 2) + "/"
            + padLeft(date.getDate(), '0', 2) + "/"
            + date.getFullYear()
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function validatelat(x) {
    var reg = new RegExp("^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$");
    return /^(?=.)-?((8[0-5]?)|([0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/.test(x.key);
    
}

function validatelong(x) {
    return /^(?=.)-?((0?[8-9][0-9])|180|([0-1]?[0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/.test(x.key);
}

function validatePALat(x) {
    //return /^(?=.)((39)|(4[0-2]?))?(?:\.[0-9]{1,6})?$/.test(x.key);
    return /^(?=.)-?((8[0-5]?)|([0-7]?[0-9]))?(?:\.[0-9]{1,20})?$/.test(x.key);
}

function BuildUploadControlForPublishedReports() {
    //$('.ajax-upload-dragdrop').remove();
    $('.ajax-file-upload-statusbar').remove();
    $('.ajax-file-upload-error').remove();

    $("#fileuploader").uploadFile({
        url: ImageUploadURL,
        fileName: "filename",
        miltiple: true,
        allowedTypes: allowedTypes,
        showStatusAfterSuccess: false,
        showFileCounter: false,
        showAbort: false,
        showCancel: false,
        maxFileSize: 51200000,
        //resolve:{
        //    controllerscope:function(){return $scope;}
        //},
        dynamicFormData: function () {
            var reportDetails = $('#detail').val();
            var description = $('#Description').val();
            var fromDate = $('#fromdate').val();
            var toDate = $('#todate').val();
            var data = { "type": entityType, "ReportDetails": reportDetails, "Description": description, "FromDate": fromDate, "ToDate": toDate }
            return data;

        },

        onSubmit: function (e) {
            isUploadInProgress = true;
        },
        afterUploadAll: function (files) {
            $("#uploaddiv").hide();
            isUploadInProgress = false;
        },
        onError: function (files, status, errMsg) {
            isUploadInProgress = false;

        }

    });
}

function getUrlVars() {
    var vars = [], hash;
    if (window.location.href.indexOf('?') > -1) {
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}


function thousandSep(val) {
    return String(val).split("").reverse().join("")
                  .replace(/(\d{3}\B)/g, "$1,")
                  .split("").reverse().join("");
}

function getMonthName(monthNumber) {
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return months[monthNumber - 1];
}

function validateTime(inputField) {
    var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);

    //if (isValid) {
    //    inputField.style.backgroundColor = '#bfa';
    //} else {
    //    inputField.style.backgroundColor = '#fba';
    //}

    return isValid;
}

function formatjasondate(jdate) {

    var dd = "AM";

    if (jdate == '/Date(-62135578800000)/')
        return '';    

    var dt = new Date(jdate.match(/\d+/)[0] * 1);

    var year = dt.getFullYear();

    if (year == '3938') {
        return '';
    }

    var hh = dt.getHours();

    var day = dt.getDate() > 9 ? dt.getDate() : '0' + dt.getDate();

    var m = dt.getMonth();
    var mnth = m > 9 ? m : '0' + m;

    var h = hh;
    if (h >= 12) {
        h = hh - 12;
        dd = "PM";
    }
    if (h == 0) {
        h = 12;
    }

    var hour = h > 9 ? h : '0' + h;

    var minutes = dt.getMinutes() > 9 ? dt.getMinutes() : '0' + dt.getMinutes();
    var sec = dt.getSeconds() > 9 ? dt.getSeconds() : '0' + dt.getSeconds();
    return parseInt(mnth) + 1 + "/" + day + "/" + dt.getFullYear() + " " + hour + ":" + minutes + ":" + sec + " " + dd
}

function numbersonlywithbackspace(e) {
    if (numbersonly(e))
    {
        return true;
    }
    else if (backspaceonly(e)) {
        return true;
    }
    else return false;
}
function numbersonly1(e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [8, 9, 27, 13, 190,]) !== -1 ||
        // Allow: Ctrl+A, Command+A
        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
        // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        // let it happen, don't do anything
        return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode >= 105)) {
        e.preventDefault();
    }
    if (e.keyCode == 101 || e.keyCode == 97 || e.keyCode == 100 || e.keyCode == 102 || e.keyCode == 103 || e.keyCode == 104
        || e.keyCode == 99 || e.keyCode == 98 || e.keyCode == 110 || e.keyCode == 46) {
        e.preventDefault();
    }    
}

function MergeJQGridCells(gridName, mergeByColumn, cellNames) {
    var CellNames = cellNames.split(",");
    //Get the id set displayed to the interface
    var rows = $("#" + gridName + "").getDataIDs();
    //How many are currently displayed
    var length = rows.length;
    for (var i = 0; i < length; i++) {
        //Get a message from top to bottom
        var before = $("#" + gridName + "").jqGrid('getRowData', rows[i]);

        for (j = i + 1; j <= length; j++) {
            //Compare with the information above. If the value is the same, merge the number of rows + 1 and set rowspan to hide the current cell
            var end = $("#" + gridName + "").jqGrid('getRowData', rows[j]);

            for (var c = 0; c < CellNames.length; c++) {
                var colname = CellNames[c];
                //Define number of merged rows
                var rowSpanTaxCount = 1;
                if (before[colname] == end[colname] && before[mergeByColumn] == end[mergeByColumn]) {
                    rowSpanTaxCount++;
                    $("#" + gridName + "").setCell(rows[j], colname, '', { display: 'none' });
                }
                else {
                    rowSpanTaxCount = 1;
                    // break;
                }
                if (rowSpanTaxCount > 1)
                    $("#" + colname + "" + rows[i] + "").attr("rowspan", rowSpanTaxCount);
            }

        }
    }
}

function getEndRange(dtCtrl) {
    var currDate = new Date();
    var lastDay = new Date(currDate.getFullYear(), currDate.getMonth() + 1, 0);
    var remDays = lastDay.getDay() - currDate.getDay();

    if (typeof lv_IsPublicPortal === "undefined") {
        lv_IsPublicPortal = "";
    }
    if (typeof dtCtrl_endDate === "undefined") {
        dtCtrl_endDate = "";
    }
    var returnValue = "";
    if (dtCtrl == "DP") {
        if (dtCtrl_endDate > 0 && lv_IsPublicPortal == 'True') {
            returnValue = new Date("12/31/" + dtCtrl_endDate);
        } else {
            returnValue = '+0d'
        }
    }
    else if (dtCtrl == "MY") {
        if (dtCtrl_endDate > 0 && lv_IsPublicPortal == 'True') {
            returnValue = new Date(dtCtrl_endDate, 11, 31);
        }
        else {
            returnValue = '+' + remDays + 'd'
        }
    }
    return returnValue;
}
   
function formatAdvanceddate(oevent) {
    var isValid, validOutput, valOutput, message="", actualDate;
    isValid = true;
    var obj = document.getElementById(oevent.target.id);
    if (numbersonly(oevent)) {
        //Check date validity
        if (obj.value.length > 0) {
            validOutput = CheckValidDate(obj.value);
            valOutput = validOutput.split(":")
            isValid = valOutput[0];
            message = valOutput[1];
            actualDate = valOutput[2];
        }
     
        //toDate should be greater than from date
        if (isValid.toString() == "true" && obj.id.toString().includes("searchdate2")) {
            var index = obj.id.toString().slice(0, 1);
            var obj1 = document.getElementById(index + 'searchdate1');
            validOutput = CheckToDate(obj1.value,obj.value);
            valOutput = validOutput.split(":")
            isValid = valOutput[0];
            message = valOutput[1];       
        }

         //FromDate should be less than To date
        if (isValid.toString() == "true" && obj.id.toString().includes("searchdate1")) {
            var index = obj.id.toString().slice(0, 1);
            if ( typeof( document.getElementById(index + 'searchdate2')) != 'undefined' && document.getElementById(index + 'searchdate2') != null )
            {
                var obj1 = document.getElementById(index + 'searchdate2');
                validOutput = CheckToDate(obj.value, obj1.value);
                valOutput = validOutput.split(":")
                isValid = valOutput[0];
                message = valOutput[1];
            }
        }

        //Date should not be beyond currentdate
        if (isValid.toString() == "true" && obj.value.length > 0) {
           validOutput = CheckCurrentDate(obj.value);
            valOutput = validOutput.split(":")
            isValid = valOutput[0];
            message = valOutput[1];  
        }
        if (isValid.toString() == "false" && obj.value.length > 0) {
            bootbox.alert(message, function () { obj.value = ""; $(obj).focus(); });
        }
        
        obj.value = "";
        if (actualDate != undefined) {
            obj.value = actualDate;
        }       
        return isValid;

    }
   else {
        if (slashonly(oevent)) {
            if (obj.value.length == 1) { obj.value = "0" + obj.value; return true; }
            else if (obj.value.length == 4) {
                val = obj.value.substring(0, 3) + "0" + obj.value.substring(5, 3);
                obj.value = val; return true;
              }
            else return false;
        }
        else if (backspaceonly(oevent)) { return true; }
        else return false;
    }

}

//new Date() not working for Feb29, Apr31, Jun31, Sep31, Nov31 issues. Hence, customised code
//Timestamp too not working as per the requirement
function CheckValidDate(dateValue) {
    var isValid = true, Message = "";
    var monthNum = 0, daysNum = 0, date = 0, year = 0;
    if (dateValue.length < 10 && dateValue.length > 0) {
        var dateMonYear = dateValue.split("/");
        monthNum = dateMonYear[0];
        date = dateMonYear[1];
        year = dateMonYear[2];
    }
    else {
        monthNum = dateValue.substring(0, 2);
        date = dateValue.substring(3, 5);
        year = dateValue.substring(6, 10);
    }
    if (dateValue.length > 0) {
        //check month
        if (monthNum > 0 && monthNum <= 12) {
            if (monthNum < 10 && monthNum.length < 2) { monthNum = "0" + monthNum; }
            isValid = true;
            //check date
            if (date > 0 && date <= 31) {
                if (date < 10 && date.length < 2) { date = "0" + date; }
                isValid = true;
            }
            else {
                isValid = false;
                Message = "Please check the date value entered. " + dateValue + " is an invalid date.";
            }
        }
        else {
            isValid = false;
            Message = "Please check the month value entered. " + dateValue + " is an invalid date.";
        }

        //check the year to be > 999
        if (year.length = 4 && year > 999) {
            //get the number of days for the selected month
            if (monthNum > 0 && monthNum < 13) {
                switch (monthNum) {
                    case '01': case '03': case '05': case '07': case '08': case '10': case '12': {
                        daysNum = 31;
                        break;
                    }
                    case '04': case '06': case '09': case '11': {
                        daysNum = 30;
                        break;
                    }
                    case '02':
                        {
                            if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
                                daysNum = 29;
                            else
                                daysNum = 28;
                            break;
                        }
                }
                //check the date for the selected month
                if (date <= daysNum) {
                    isValid = true;
                }
                else {
                    isValid = false;
                    Message = "Please check the date entered for the month. " + dateValue + " is an invalid date.";
                }
            }
        }
        else {
            isValid = false;
            Message = "Please check the year value entered. " + dateValue + " is an invalid date.";
        }
    }
    else {
        isValid = false;
        Message = "Please check the date value entered. " + dateValue + " is an invalid date.";
    }

    return isValid + ":" + Message + ":" + monthNum + "/" + date + "/" + year;
}
 
function CheckToDate(FromDate, ToDate) {
    var isValid = true, Message = "";
    var stDate = new Date(FromDate.toString());
    var endDate = new Date(ToDate.toString());
    if (endDate >= stDate) {
        isValid = true;
    }
    else if (endDate < stDate) {
        isValid = false;
        Message = "Please check the date value entered. " + ToDate + " should be greater than or equal to " + FromDate + " .";
    }
    return isValid + ":" + Message;
}

function CheckCurrentDate(dateValue) {
    var isValid = true, Message = "";
    var currentDate = new Date();
    var formatcurrentDate = currentDate.getMonth() + 1 + "/" + currentDate.getDate() + "/" + currentDate.getFullYear();
    if (new Date(dateValue) > new Date(formatcurrentDate)) {
        isValid = false;
        Message = "Please check the date value entered. " + dateValue + " should not be greater than current date.";
    }
    return isValid + ":" + Message;
}

function formatFilename(event)
{
    if (event.key == "[" || event.key == "]" || event.key == "/" || event.key == ">" || event.key == "<" || event.key == ":" || event.key == "=" || event.key == "?")
    {
        return false; // ignore the key press event
    }
    return true;
};
