var hex = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
var languageData;
var CUrl = window.location.href;
var SUrl = CUrl.split("/");
//var DUrl = '/';
var DUrl = (SUrl[2].substr(0, 3) == "127" ? "http://osiris.monsanto.com/" : SUrl[0] + "//" + SUrl[2] + "/");
var PUrl = SUrl[SUrl.length - 1].substr(0, (SUrl[SUrl.length - 1].indexOf('?') == -1 ? SUrl[SUrl.length - 1].length : SUrl[SUrl.length - 1].indexOf('?'))); 

var CURRENT_PAGE = 30708;

var loopFlag = 1;
var loopCount = 0;
var PageTitle = '';
var afterCode = '';
var bootboxLoading;
var filesUpload = {};

var allUserJSON = [];
var subTask = false;
var mainTask = 0;
var calID;
var currentEle;
var value;
var mainCalData;
var getTaskInfo;
var getTaskData;
var subTaskDataTableInfo;
var TaskDataTableInfo;
var FROM;
var dateInit;

var logMessages = [];

(function () {
    var oldLog = console.log;
    console.log = function (message) {
        logMessages.push(message);
        oldLog.apply(console, arguments);
    };
})();

if (localStorage.getItem("UserId") != undefined) {
//    if (localStorage.getItem('PrevPage') != undefined && localStorage.getItem('PrevPage') != "") {
//        if(PUrl != localStorage.getItem('PrevPage')) {
//            window.location.href = localStorage.getItem('PrevPage');
//        }
    if (PUrl == "index.html") {
//    } else if(PUrl != "app_select.html") {
        window.location.href = "app_select.html";
    }
//    if(PUrl != "app_dashboard.html") {
//        window.location.href = "app_dashboard.html";
//    }
} else {
//    localStorage.removeItem('PrevPage');
    if (PUrl != "index.html") {
        window.location.href = "index.html";
    }
}

//var Fields = {
//    var inFields = [];
//}

var Functions = {
    testFunction: {
        call: function (options) {

            options = Functions.compareObjectArray(Functions.testFunction.options, options);

            handleAlerts.Position(options.position);

            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.dialog({
                    message: options.message,
                    title: options.title,
                    buttons: options.buttons,
                    onEscape: options.onEscape,
                    backdrop: options.modalClose,
                    size: options.size
                });
            }
        },
        options: {
            message: ' ',
            title: '',
            buttons: {}, //{buttonName : {label: 'Your button text',className: "some-class",callback: function() {}}}
            onEsc: null, //true, false
            position: null, //center, bottom
            size: null, //large, small
            modalClose: undefined //true, false (true if onEsc is true)
        }
    },

    onTimer: function (timeCounter, message, callback, element) {
        if (element != undefined) {
            if ($(element).find('.blockUI').length > 0) {
                $($(element).find('.m-blockui').children()[0]).html(message + ' (' + timeCounter + ')')
            } else {
                handleAlerts.BlockElement({
                    MESSAGE: message + ' (' + timeCounter + ')',
                    ELEMENT: element
                });
            }
            timeCounter--;
            if (timeCounter < 0) {
                callback();
                handleAlerts.UnblockElement(element);
            } else {
                setTimeout(function () { Functions.onTimer(timeCounter, message, callback, element); }, 1000);
            }
        } else {
            handleAlerts.Position('center');
            handleAlerts.ShowLoading(message + ' (' + timeCounter + ')');
            timeCounter--;
            if (timeCounter < 0) {
                callback();
                handleAlerts.HideAlerts();
            } else {
                setTimeout(function () { Functions.onTimer(timeCounter, message, callback); }, 1000);
            }
        }
    },

    titleCase: function (str) {
        var splitStr = str.toLowerCase().split(' ');
        for (var i = 0; i < splitStr.length; i++) {
            // You do not need to check if i is larger than splitStr length, as your for does that for you
            // Assign it back to the array
            splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
        }
        // Directly return the joined string
        return splitStr.join(' ');
    },

    compareObjectArray: function (defaultVal, other) {

        other = other || {};
        for (obj in defaultVal) {
            if (typeof other[obj] == "undefined") {
                other[obj] = defaultVal[obj];
            }
        }

        return other;
    },

    ajaxResult: function (result, array) {
        if (array == 'array') {
            result = JSON.parse($(result).find('string').first().text());
        } else if (array == 'text') {
            result = $(result).find('string').first().text();
        }
        return result;
    },
    
    keys: function (obj) {
        var keys = [];

        for(var key in obj)
        {
            if(obj.hasOwnProperty(key))
            {
                keys.push(key);
            }
        }
        return keys;
    },

    indexOfObject: function (arr, property, value, ret, exact) {
        var Ret = -1;
        if (value != undefined && arr != undefined) {
            if (property == "singleArr") {
                for( var i = 0, len = arr.length; i < len; i++ ) {
                    if( $.inArray(value,arr[i]) != -1 ) {
                        if (ret == undefined || ret == '') {
                            Ret = i;
                            break;
                        } else {
                            Ret = arr[i][ret];
                            break;
                        }
                    }
                }
            } else {
                for (var i = 0; i < arr.length; i++) {
                    if (exact == undefined || exact == false) {
                        if (arr[i][property] != undefined && arr[i][property].toString().indexOf(value.toString()) != -1) {
                            if (ret == undefined || ret == '') {
                                Ret = i;
                            } else {
                                Ret = arr[i][ret];
                            }
                            break;
                        }
                    } else {
                        if (arr[i][property] != undefined && arr[i][property].toString() == value.toString()) {
                            if (ret == undefined || ret == '') {
                                Ret = i;
                            } else {
                                Ret = arr[i][ret];
                            }
                            break;
                        }
                    }
                }
            }
        }
        return Ret;
    },

    filterArray: function (array, filters) {

        var ret = [],
            i = 0,
            l = (array == undefined ? 0 : array.length),
            filter;

        all: for (; i < l; ++i) {

            for (filter in filters) {
                if (!filters[filter](array[i][filter])) {
                    continue all;
                }
            }

            ret[ret.length] = array[i];

        }

        return ret;

    }, //Functions.filterArray(JSON.parse(GetData.localStorage('Catalog')),{Category: function(value) {return value == 11;}, Name: function(value) {return value.substr(value.lastIndexOf("|")+1) == "jatole1";}})

    filterSingleArray: function (array, filters) {

        var ret = [],
            i = 0,
            l = array.length;

        all: for (; i < l; ++i) {

            for (var t = 0; t < filters.length; ++t) {
                if (!(array[i][filters[t][0]] == filters[t][1])) {
                    continue all;
                }
            }

            ret.push(array[i]);
        }

        return ret;

    }, //Functions.filterArray(JSON.parse(GetData.localStorage('Catalog')),{Category: function(value) {return value = 11;}, Name: function(value) {return value.substr(value.lastIndexOf("|")+1) == "jatole1";}})

    onlyUnique: function (xs, key) {
        var loopArr = [];
        if (key == undefined) {
            for (var i = 0; i < xs.length; i++) {
                if (loopArr.indexOf(xs[i]) == -1) {
                    loopArr.push(xs[i]);
                }
            }
        } else {
            for (var i = 0; i < xs.length; i++) {
                if (loopArr.indexOf(xs[i][key]) == -1) {
                    loopArr.push(xs[i][key]);
                }
            }
        }
        return loopArr;
    },

    sumUniqueValue: function (xs, key, value) {
        var loopArr = {};
        for (var i = 0; i < xs.length; i++) {
            if (loopArr[xs[i][key]] == undefined) {
                loopArr[xs[i][key]] = xs[i][value];
            } else {
                loopArr[xs[i][key]] = Number(loopArr[xs[i][key]]) + Number(xs[i][value]);
            }
        }
        return loopArr;
    },
    
    ArrayToObject: function (arr) {
        var ret = [];
        for (var i = 1; i < arr.length; i++) {
            ret.push(arr[i].reduce(function(a,b,c,d){a[arr[0][c]] = b;return a;},{}))
        }
        return ret;
    },

    ToJavaScriptDate: function (value, complete) {
        var dt;
        if (new Date(value) == 'Invalid Date') {
            var pattern = /Date\(([^)]+)\)/;
            var results = pattern.exec(value);
            dt = new Date(parseFloat(results[1]));
        } else {
            dt = new Date(value);
        }
        if (complete) {
            return dt;
        } else {
            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
        }

    },

    StopIdle: function () {
        $(document).unbind("idle");
        localStorage.removeItem('idleTimerLastActivity');
        $("body").off(".idle");
    },

    isLocalStorageNameSupported: function () {
        var testKey = 'test',
            storage = window.localStorage;
        try {
            storage.setItem(testKey, '1');
            storage.removeItem(testKey);
            return true;
        } catch (error) {
            return false;
        }
    },

    moveUp: function ($item) {
        $before = $item.prev();
        $item.insertBefore($before);
    },

    moveDown: function ($item) {
        $after = $item.next();
        $item.insertAfter($after);
    },

    CustomLoop: function (start, len, work, callback) {
        var index = start;
        setTimeout(function () {
            doWork(index);
        }, 10);

        function doWork(index) {

            if (index < len) {
                work(index);
                index++;
                setTimeout(function () {
                    doWork(index);
                }, 10);
            } else {
                callback(); // Done
            }
        }
    }, //Functions.CustomLoop(0,10,function(i){setTimeout(console.log(i), 100);},function(){alert('finish');})

    ProcessArray: function (start, data, handler, callback) {
        var maxtime = 100; // chunk processing time
        var delay = 20; // delay between processes
        var queue = data.concat(); // clone original array
        queue.splice(0, start);

        setTimeout(function () {

            var endtime = +new Date() + maxtime;

            do {
                handler(queue.shift());
            } while (queue.length > 0 && endtime > +new Date());
            if (queue.length > 0) {
                setTimeout(arguments.callee, delay);
            } else {
                if (callback) callback();
            }

        }, delay);
    }, // end of ProcessArray function

    RemoveURLParam: function (key, sourceURL) {
        if (!sourceURL) {
            sourceURL = window.location.href;
        }

        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }
            rtn = rtn + "?" + params_arr.join("&");
        }
        return rtn;
    },

    Modal: function (innerText, callback) {
        $('#SingleModal').html('<h2 id="ModalText"></h2><div style=""><img src="imagen\\loading_spinner.gif" style="/* position: relative; */width: 100%;/* left: 50px; *//* top: 80px; */"></div>');
        if (innerText != undefined) {
            $('#ModalText').html(innerText);
            $("#backscreen").addClass("modalBack2");
            $("#SingleModal").addClass("modalDialog3");
            $("#SingleModal").show('slow', function () {
                if (callback != undefined) {
                    callback();
                }
            });
        } else {
            $('#ModalText').html('');
            $("#backscreen").removeClass("modalBack2");
            $("#SingleModal").removeClass("modalDialog3");
            $("#SingleModal").hide();
        }
    },

    sleep: function (miliseconds) {
        var currentTime = new Date().getTime();

        while (currentTime + miliseconds >= new Date().getTime()) {}
    },

    ShuffleArray: function (array) {
        var currentIndex = array.length,
            temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    },

    isNullOrWhitespace: function (input) {

        if (input == null) return true;

        return input.toString().replace(/\s/gi, '').length < 1;
        //return !input || (Functions.isNumeric(input) ? false : input.trim());
    },
    
    isTrue: function (value) {
        var ret = false;
        switch (value) {
            case 1:
            case "1":
            case "yes":
            case "Yes":
            case "YES":
            case "true":
            case "True":
            case "TRUE":
            case "OK":
            case "Ok":
            case "ok":
            case true:
                ret = true;
                break;	
            default: 
                break;
        }
        return ret;
    },

    javascript_abort: function (a, b) {
        handleAlerts.Simple(a);
        if (b == undefined) {
            b = a;
        }
        throw new Error(b);

    },

    OnlineStatus: function () {
        var ret;
        $.ajax({
            type: "POST",
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/TestConnect",

            cache: false,
            async: false,
            success: function () {
                ret = true;
            },
            error: function () {
                ret = false;
            }
        });
        return ret;
    },

    Connected: function () {
        //$.ajax({
        //    type: "POST",
        //    dataType: "xml",
        //    url: DUrl + "WebServiceOsiris.asmx/TestConnect",
        //    
        //    cache: false,
        //    async: false,
        //    success: function (data) {
        //        console.log('Connected');
        //    },
        //    error: function(data) {
        //        Functions.javascript_abort('No connection detected.  Please try again later.','No Connection.');
        //    }
        //});
    },

    LoopCache: function () {
        for (var index in $.cache) {
            try {
                if ($.cache[index].handle != undefined) {
                    if ($.cache[index].handle.elem != undefined) {
                        if ($.cache[index].handle.elem.id != undefined) {
                            console.log(index + ' | ' + $.cache[index].handle.elem.id);
                        }
                    }
                }
            } catch (e) {
                //debugger;
            }
        }
    },

    None: function () {
        return "";
    },

    AleatoryCode: function (char) {
        var RetValue = '';
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "CharLength=" + char,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/TestSalt",

            cache: false,
            async: false,
            success: function (data) {

                RetValue = $(data).find('string').first().text();
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

        return RetValue;
    },

    VerifyAlerts: function () {
        var AlertJSON = JSON.parse(GetData.localStorage("Alerts"));
        if (!AlertJSON) {
            return;
        }
        Functions.sortArray(AlertJSON, "PriorityOrder", true, false);

        for (var i = 0; i < AlertJSON.length; i++) {
            var PageSplit = AlertJSON[i].Page.split(',');
            for (var j = 0; j < PageSplit.length; j++) {
                if (GetData.LocalStorageSingleJSONData('Sidebar', 'id_Sidebar', PageSplit[j], 'Name') == Functions.OpenForm()) {
                    if (eval(AlertJSON[i].Condition)) {
                        if (AlertJSON[i].Color != null) {
                            $('#alertCond').remove();
                            $("<style type='text/css' id='alertCond'> .alertCond{ background-color: " + AlertJSON[i].Color + " !important;} </style>").appendTo("head");
                            $(".page-content").addClass('alertCond');
                        }
                        handleAlerts.Simple(AlertJSON[i].Message);
                    }
                }
            }
        }
    },

    Feedback: function () {

        handleAlerts.CustomDialog({
            message: '<div class="row">  ' +
                '<div class="col-md-12"> ' +
                '<form class="form-horizontal"> ' +
                '<div class="form-group"> ' +
                '<label class="col-md-3 control-label" for="name">' + Functions.LanguageSelectItem(267) + '</label> ' +
                '<div class="col-md-8"> ' +
                '<input id="name" name="name" type="text" class="form-control input-lg" value=" ' + GetData.localStorage("EmpName") + '"> ' +
                '</div> ' +
                '</div> ' +
                '<div class="form-group"> ' +
                '<label class="col-md-3 control-label" for="comments">' + Functions.LanguageSelectItem(39) + '</label> ' +
                '<div class="col-md-8"> ' +
                '<textarea id="comments" class="form-control input-lg" rows="4" style="resize:vertical;"></textarea> ' +
                '</div> ' +
                '</div> ' +
                '</form> </div>  </div>',
            title: 'Feedback',
            buttons: {
                success: {
                    label: "Save",
                    className: "btn-success",
                    callback: function () {
                        var name = $('#name').val();
                        var comments = $("#comments").val();

                        Functions.Connected();
                        $.ajax({
                            type: "POST",
                            data: "StringJSON=Osiris Feedback|" + escape(GetData.localStorage("UserId") + "@monsanto.com|" + GetData.localStorage("EmpName") + "|vtorr@monsanto.com|From: " + name + ":bbrrbbrr" + comments),
                            dataType: "xml",
                            url: DUrl + "WebServiceOsiris.asmx/EmailMessage",

                            cache: false,
                            async: true,
                            success: function (data) {

                                var title = $(data).find('string').first().text();

                                if (title == 'Done') {
                                    handleAlerts.Simple("Thanks " + name + ". Your feedback/comment <b>" + comments + "</b> is successfully submitted.");
                                } else {
                                    handleAlerts.Simple("There were some errors saving the feedback.");
                                }
                            },
                            error: function (a, b, c) {
                                if (GetData.localStorage("onScreenError") == "true") {
                                    handleAlerts.Simple(a.responseText);
                                } else {
                                    handleAlerts.Simple("There were some errors saving the feedback.");
                                    console.log(a.responseText);
                                }
                            }
                        });

                    }
                }
            }
        });
        setTimeout(function () {
            $('#comments').focus();
        }, 500);
    },

    SendEmail: function (Subject, From, FromName, To, Message) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + Subject + "|" + From + "|" + FromName + "|" + To + "|" + Message.replace(/<b>/g, '(b)').replace(/<\/b>/g, '(/b)').replace(/<br\/>/g, '(br/)').replace(/<hr>/g, '(hr)'),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/EmailMessage",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == 'Done') {
                    RET = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    SendTaskItem: function (title, status, duedate, assign, type, mainTask) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + title + "|" + status + "|" + duedate + "|" + assign + "|" + type + "|" + mainTask,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Send_Task_Item",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                RET = JSON.parse(title)[0].Identity;
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    UpdateTaskItem: function (idTaskItem, title, status, duedate, assign, type, mainTask, active) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + idTaskItem + "|" + title + "|" + status + "|" + duedate + "|" + assign + "|" + type + "|" + mainTask + "|" + active,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Update_Task_Item",

            cache: false,
            async: false,
            success: function (data) {

                RET = true;
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },
    
    SendSP: function (sp, parm, callback) {
        $.ajax({
            type: "POST",
            data: "StringJSON=#" + sp + "|" + parm,
            dataType: "xml",
            async: false,
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables2",
            cache: false,
            success: function(data) {
                if (callback != undefined) {
                    callback(data);
                }
            },
            error: function(a, b, c) {
                handleAlerts.Simple("There were some errors saving the Training. <br/> Error: " + a);
            }
        });
    },

    DeleteTaskItem: function (idTaskItem) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + idTaskItem,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Delete_Task_Item",

            cache: false,
            async: false,
            success: function (data) {

                RET = true;
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    SendTaskData: function (calId, dateTime, action, description) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + calId + "|" + dateTime + "|" + action + "|" + description,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Send_Task_Data",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == 'Done') {
                    RET = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    UpdateTaskData: function (idTaskData, calId, dateTime, action, description, active) {
        var RET = false;
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + idTaskData + "|" + calId + "|" + dateTime + "|" + action + "|" + description + "|" + active,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Update_Task_Data",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == 'Done') {
                    RET = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    DownloadFormData: function (Form) {
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + escape(Form + "|" + (GetData.localStorage("Classification") == "Juana Diaz" ? "P" : (GetData.localStorage("Classification") == "Hawaii" ? "H" : "ZZZ")) + "|" + GetData.localStorage("Season")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Answer_with_Form",

            cache: false,
            async: true,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == '[[]]') {
                    //debugger;
                } else {
                    SetData.ExportExcel(title, false, "MyReport_" + Form.replace(/_/g, " "));
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

    },

    addValue: function (obj, key, value) {
        if (obj.hasOwnProperty(key)) {
            obj[key].push(value);
        } else {
            obj[key] = [value];
        }
    },

    numberWithCommas: function (num) {
        
        return (num == undefined ? "" : num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    },

    joinWithQuoutes: function (arr, delimeter) {
        return "'" + arr.join("'" + delimeter + "'") + "'";
    },

    Logout: function () {
        localStorage.clear();
        if (PUrl != 'Lock.html') {
            SetData.localStorage('PrevPage', CUrl);
        }
        location.href = "index.html";
    },

    RemoveLast: function (text, qty) {
        return text.substr(0, text.length - qty);
    },

    ClearFields: function () {
        var TEXT = "";
        $('.page-content').removeClass().addClass('page-content');
        $('#alertCond').remove();

        if ($("#MasterIdSelect").length != 0) {
            if ($("#MasterIdSelect").val() != "") {
                TEXT = $("#MasterIdSelect").val();
                $('input.form-control:input').val('');
                $('.select2-container').select2("val", "");
                //$(".form-control-static[data-formula=' '],.form-control-static[data-formula='']").html('');
                $(".form-control-static").html('');
                $('.btn-group-circle').find('label').removeClass('active');
                $('input.form-field:checkbox').attr('checked', false);
                $('.make-switch').bootstrapSwitch('state', false, true);
                $("#MasterIdSelect").val(TEXT);
            } else {
                $('input.form-control:input').val('');
                $('.select2-container').select2("val", "");
                //$(".form-control-static[data-formula=' '],.form-control-static[data-formula='']").html('');
                $(".form-control-static").html('');
                $('.btn-group-circle').find('label').removeClass('active');
                $('input.form-field:checkbox').attr('checked', false);
                $('.make-switch').bootstrapSwitch('state', false, true);
            }
        } else {
            $('input.form-control:input').val('');
            $('.select2-container').select2("val", "");
            //$(".form-control-static[data-formula=' '],.form-control-static[data-formula='']").html('');
            $(".form-control-static").html('');
            $('.btn-group-circle').find('label').removeClass('active');
            $('input.form-field:checkbox').attr('checked', false);
            $('.make-switch').bootstrapSwitch('state', false, true);
        }
        if (typeof clearOverlaysGoHome != "undefined") {
            clearOverlaysGoHome();
        }
        for (var i = 0; i < $('.form-control').length; i++) {
            if ($('.form-control').eq(i).attr('data-default') == 'Now' && $('.form-control').eq(i).attr('id').substr(0, $('.form-control').eq(i).attr('id').indexOf('_')) == 5) {
                SetData.PageFieldValue($('.form-control').eq(i).attr('id').substr($('.form-control').eq(i).attr('id').lastIndexOf("-") + 1, 10000), DateFunctions.FormatDate(Date(), 'hh:mm T'));
            }
        }
    },

    escapeHTML: function (str) {

        var escaped = "";

        var i = 0;
        //var brEscape = document.getElementById('br').checked;
        //var tagEscape = document.getElementById('tag').checked;
        //var others = document.getElementById('other').checked;
        //var nbsp = document.getElementById('nbsp').checked;
        for (i = 0; i < str.length; i++) {
            var p = str.charAt(i);

            //if (others) p = "" + Functions.escapeCharx(p);
            //if (tagEscape) p = "" + Functions.escapeTags(p);
            //if (brEscape) p = "" + Functions.escapeBR(p);
            //if (nbsp) p = "" + Functions.escapeNBSP(p);
            p = "" + Functions.escapeCharx(p);

            escaped = escaped + p;
        }

        return escaped;
    },

    escapeBR: function (original) {
        var thechar = original.charCodeAt(0);

        switch (thechar) {
            case 10:
                return "<br/>";
                break; //newline
            case '\r':
                break;
        }
        return original;
    },

    escapeNBSP: function (original) {
        var thechar = original.charCodeAt(0);
        switch (thechar) {
            case 32:
                return "&nbsp;";
                break; //space
        }
        return original;
    },

    escapeTags: function (original) {
        var thechar = original.charCodeAt(0);
        switch (thechar) {
            case 60:
                return "&lt;";
                break; //<
            case 62:
                return "&gt;";
                break; //>
            case 34:
                return "&quot;";
                break; //"
        }
        return original;

    },

    escapeCharx: function (original) {
        var found = true;
        var thechar = original.charCodeAt(0);
        switch (thechar) {
            case 38:
                return "&amp;";
                break;
            case 198:
                return "&AElig;";
                break;
            case 193:
                return "&Aacute;";
                break;
            case 194:
                return "&Acirc;";
                break;
            case 192:
                return "&Agrave;";
                break;
            case 197:
                return "&Aring;";
                break;
            case 195:
                return "&Atilde;";
                break;
            case 196:
                return "&Auml;";
                break;
            case 199:
                return "&Ccedil;";
                break;
            case 208:
                return "&ETH;";
                break;
            case 201:
                return "&Eacute;";
                break;
            case 202:
                return "&Ecirc;";
                break;
            case 200:
                return "&Egrave;";
                break;
            case 203:
                return "&Euml;";
                break;
            case 205:
                return "&Iacute;";
                break;
            case 206:
                return "&Icirc;";
                break;
            case 204:
                return "&Igrave;";
                break;
            case 207:
                return "&Iuml;";
                break;
            case 209:
                return "&Ntilde;";
                break;
            case 211:
                return "&Oacute;";
                break;
            case 212:
                return "&Ocirc;";
                break;
            case 210:
                return "&Ograve;";
                break;
            case 216:
                return "&Oslash;";
                break;
            case 213:
                return "&Otilde;";
                break;
            case 214:
                return "&Ouml;";
                break;
            case 222:
                return "&THORN;";
                break;
            case 218:
                return "&Uacute;";
                break;
            case 219:
                return "&Ucirc;";
                break;
            case 217:
                return "&Ugrave;";
                break;
            case 220:
                return "&Uuml;";
                break;
            case 221:
                return "&Yacute;";
                break;
            case 225:
                return "&aacute;";
                break;
            case 226:
                return "&acirc;";
                break;
            case 230:
                return "&aelig;";
                break;
            case 224:
                return "&agrave;";
                break;
            case 229:
                return "&aring;";
                break;
            case 227:
                return "&atilde;";
                break;
            case 228:
                return "&auml;";
                break;
            case 231:
                return "&ccedil;";
                break;
            case 233:
                return "&eacute;";
                break;
            case 234:
                return "&ecirc;";
                break;
            case 232:
                return "&egrave;";
                break;
            case 240:
                return "&eth;";
                break;
            case 235:
                return "&euml;";
                break;
            case 237:
                return "&iacute;";
                break;
            case 238:
                return "&icirc;";
                break;
            case 236:
                return "&igrave;";
                break;
            case 239:
                return "&iuml;";
                break;
            case 241:
                return "&ntilde;";
                break;
            case 243:
                return "&oacute;";
                break;
            case 244:
                return "&ocirc;";
                break;
            case 242:
                return "&ograve;";
                break;
            case 248:
                return "&oslash;";
                break;
            case 245:
                return "&otilde;";
                break;
            case 246:
                return "&ouml;";
                break;
            case 223:
                return "&szlig;";
                break;
            case 254:
                return "&thorn;";
                break;
            case 250:
                return "&uacute;";
                break;
            case 251:
                return "&ucirc;";
                break;
            case 249:
                return "&ugrave;";
                break;
            case 252:
                return "&uuml;";
                break;
            case 253:
                return "&yacute;";
                break;
            case 255:
                return "&yuml;";
                break;
            case 162:
                return "&cent;";
                break;
            default:
                found = false;
                break;
        }
        if (!found) {
            if (thechar > 127) {
                var c = thechar;
                var a4 = c % 16;
                c = Math.floor(c / 16);
                var a3 = c % 16;
                c = Math.floor(c / 16);
                var a2 = c % 16;
                c = Math.floor(c / 16);
                var a1 = c % 16;
                //	alert(a1);
                return "&#x" + hex[a1] + hex[a2] + hex[a3] + hex[a4] + ";";
            } else {
                return original;
            }
        }
    },

    nth_occurrence: function (string, char, nth) {
        var first_index = string.indexOf(char);
        var length_up_to_first_index = first_index + 1;

        if (nth == 1) {
            return first_index;
        } else {
            var string_after_first_occurrence = string.slice(length_up_to_first_index);
            var next_occurrence = Functions.nth_occurrence(string_after_first_occurrence, char, nth - 1);

            if (next_occurrence === -1) {
                return -1;
            } else {
                return length_up_to_first_index + next_occurrence;
            }
        }
    },

    ChangeLanguage: function (lang, reload) {
        //var previousLanguage = GetData.localStorage('ActiveLanguage');
        //if (previousLanguage != lang) {
        if (lang == undefined || lang == 'undefined') {
            lang = 2
        }
        SetData.localStorage("ActiveLanguage", lang);

        if (lang == '1') {
            $("#LanguagePick").find('span').html('Español');
            $("#LanguagePick").find('img').attr('src', 'assets/global/img/flags/pr.png');
        } else {
            $("#LanguagePick").find('span').html('English');
            $("#LanguagePick").find('img').attr('src', 'assets/global/img/flags/us.png');
        }

        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + escape(GetData.localStorage("UserId") + "|" + GetData.localStorage("ActiveLanguage")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/User_Language_Change",

            cache: false,
            async: false,
            success: function (data) {

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

        if (reload) {
            location.reload();
        }
    },

    ChangeSite: function (site) {
        SetData.localStorage("Classification", site);
        location.reload();
    },

    ChangeSeason: function (season) {
        SetData.localStorage('Season', season);
        location.reload();
    },

    ChangeLabelPrinter: function (printer) {
        if (GetData.localStorage('LabelPrinter') == undefined) {
            $("#LabelPrinterPick").find('span').html(Functions.LanguageSelectItem(229));
        } else {
            $("#LabelPrinterPick").find('span').html(printer.splitret);
        }
    },

    sortArray: function (arr /* array */ , prop /* string */ , numeric /* is Numeric */ , reverse /* True or False*/ ) {

        // If reverse or numeric is null
        if (reverse == undefined) {
            reverse = false;
        }
        if (numeric == undefined) {
            numeric = false;
        }

        // Ensure there's a property
        if (!arr) {
            return arr
        }
        
        if (!prop) {
            return arr.sort();
        }

        // Set up sort function
        var sort_by = function (field, rev, primer) {

            // Return the required a,b function
            return function (a, b) {

                // Reset a, b to the field
                a = primer(a[field]), b = primer(b[field]);

                // Do actual sorting, reverse as needed
                return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
            }

        }

        // Distinguish between numeric and string to prevent 100's from coming before smaller
        // e.g.
        // 1
        // 20
        // 3
        // 4000
        // 50

        if (numeric) {

            // Do sort "in place" with sort_by function
            arr.sort(sort_by(prop, reverse, function (a) {
                if (a == null) a = 0;
                // - Force value to a string.
                // - Replace any non numeric characters.
                // - Parse as float to allow 0.02 values.
                return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));

            }));
        } else {

            // Do sort "in place" with sort_by function
            arr.sort(sort_by(prop, reverse, function (a) {
                if (a == null) a = '';
                // - Force value to string.
                return String(a).toUpperCase();

            }));
        }
    },

    specialSplit: function (str, delimeter) {
        var rgxp = new RegExp('("[^"]*")|([^' + delimeter + ']+)', "g");
        var result = [].map.call(str.replace(/,,/g, ",EMPTYSPACE,").replace(/,,/g, ",EMPTYSPACE,").match(rgxp), function (el) {
            return el.replace(/(^"|"$)|(EMPTYSPACE)/g, '');
        });
        return result;
    },

    LanguageSelect: function (espanol, english) {
        if (GetData.localStorage('ActiveLanguage') == 1) {
            return espanol;
        } else {
            return english;
        }

    },

    LanguageSelectItem: function (id, specific) {
        if (id == 0) {
            return "";
        } else {
            var Result;
            var lang = (specific != undefined ? specific : GetData.localStorage('ActiveLanguage'));

            if (lang == 1) {
                //Result = GetData.SingleSqlValue("Espanol", "OS_Languages", "id_Language = " + id);
                Result = Functions.indexOfObject(languageData, 'id_Language', id, 'Espanol');
            } else {
                //Result = GetData.SingleSqlValue("English", "OS_Languages", "id_Language = " + id);
                Result = Functions.indexOfObject(languageData, 'id_Language', id, 'English');
            }
            if (Result == undefined || Result == -1) {
                return id;
            } else {
                return Result;
            }
        }
    },

    SideBarCreation: function () {

        var SidebarJSON = JSON.parse(GetData.localStorage('Sidebar'));
        var BadgeJSON = JSON.parse(GetData.localStorage('Catalog'));

        Functions.sortArray(SidebarJSON, "OrderNumber", true, false);

        if (SidebarJSON == null) {
            SidebarJSON = [];
        }

        for (i = 0; i < SidebarJSON.length; i++) {
            //alert(SidebarJSON[i].Name);
            if (SidebarJSON[i].Name == "Divider") {
                $(".page-sidebar-menu").append('<!-- ' + Functions.LanguageSelectItem(SidebarJSON[i].Title) + ' Menu -->' +
                    '<li class="heading">' +
                    '<h3 class="uppercase">' + Functions.LanguageSelectItem(SidebarJSON[i].Title) + '</h3>' +
                    '</li>');
            } else if (SidebarJSON[i].SubMenu == 1) {

                var subMenu = '<li class="Side_' + SidebarJSON[i].Name + ' SubMenuItems">' +
                    '<a id="a_' + SidebarJSON[i].Name + '">' +
                    (SidebarJSON[i].TypeOfBadge != "" ? "<span class=\"badge " + GetData.LocalStorageSingleJSONData("Catalog", "id_Catalog", SidebarJSON[i].TypeOfBadge, "Name") + "\">" + SidebarJSON[i].Badge + "</span>" : "") +
                    '<i class="icon-' + SidebarJSON[i].Icon + '"></i>' +
                    '<span class="title">' + Functions.LanguageSelectItem(SidebarJSON[i].Title) + '</span>' +
                    '<span class="arrow"></span>' +
                    '</a>' +
                    '<ul class=\"sub-menu\"></ul>' +
                    '</li>';

                if (SidebarJSON[i].BelongTo != "" && SidebarJSON[i].BelongTo != " ") {
                    $(".Side_" + SidebarJSON[i].BelongTo).find('.sub-menu').eq(0).append(subMenu);
                } else {
                    $(".page-sidebar-menu").append(subMenu);
                }
                if (!$(".Side_" + SidebarJSON[i].Name).parent().parent().hasClass('SubMenuItems')) {
                    $(".Side_" + SidebarJSON[i].Name).addClass('whiteBorder');
                }
            } else {

                var Menu = '<li class="Side_' + SidebarJSON[i].Name + '">' +
                    '<a id="a_' + SidebarJSON[i].Name + '" onclick="' + "SetData.localStorage(\'OpenForm\', \'" + (SidebarJSON[i].BelongTo == "" || SidebarJSON[i].BelongTo == " " ? SidebarJSON[i].Name : SidebarJSON[i].Name + "|" + SidebarJSON[i].BelongTo) + "\'); window.location.href = \'" + SidebarJSON[i].Url + (SidebarJSON[i].Url == 'frm.html' ? "?Form=" + SidebarJSON[i].Name : '') + "\'; " + '">' +
                    (SidebarJSON[i].TypeOfBadge != 0 ? "<span class=\"badge " + GetData.LocalStorageSingleJSONData("Catalog", "id_Catalog", SidebarJSON[i].TypeOfBadge, "Name") + "\">" + SidebarJSON[i].Badge + "</span>" : "") +
                    '<i class="icon-' + SidebarJSON[i].Icon + '"></i>' +
                    '<span class="title">' + Functions.LanguageSelectItem(SidebarJSON[i].Title) + '</span>' +
                    '</a>' +
                    '</li>';

                if (SidebarJSON[i].BelongTo != "" && SidebarJSON[i].BelongTo != " ") {
                    $(".Side_" + SidebarJSON[i].BelongTo).find('.sub-menu').eq(0).append(Menu);
                } else {
                    $(".page-sidebar-menu").append(Menu);
                }
                if (!$(".Side_" + SidebarJSON[i].Name).parent().parent().hasClass('SubMenuItems')) {
                    $(".Side_" + SidebarJSON[i].Name).addClass('whiteBorder');
                }
            }
            if (SidebarJSON[i].Start_End == 1) {
                $(".Side_" + SidebarJSON[i].Name).addClass("start");
            } else if (SidebarJSON[i].Start_End == 2) {
                $(".Side_" + SidebarJSON[i].Name).addClass("last");
            }
        }
        $('#SearchForms').attr('placeholder', Functions.LanguageSelect('Busque una Forma...', 'Search Forms...'));
        $('#SearchForms').keyup(function () {
            var searchText = $(this).val();

            $('.page-sidebar-menu > li, .sub-menu > li').each(function () {

                var currentLiText = $(this).text(),
                    showCurrentLi = currentLiText.toLowerCase().indexOf(searchText.toLowerCase()) !== -1;

                $(this).toggle(showCurrentLi);

            });
            if (searchText == '') {
                $('.sub-menu').hide();
            } else {
                $('.sub-menu').show();
            }

        });
        $("#Sidebar_Loading").hide();
    },

    ReportSidebarCreation: function () {
        var ReportSidebarJSON;

        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "SQLString=SELECT RepName, RepId FROM OS_Reports where ([Public] = 1 and (Classification = " + escape(GetData.LocalStorageSingleJSONData('Catalog', 'Name', GetData.localStorage('Classification'), 'id_Catalog') + " OR Classification = 30) AND (Subclassification = " + GetData.LocalStorageSingleJSONData('Catalog', 'Name', GetData.localStorage('SubClassification').split(',')[0], 'id_Catalog') + " OR Subclassification = 30)) or id_Report in (SELECT val FROM dbo.f_split((SELECT Reports from OS_User where UserId = '" + GetData.localStorage('UserId') + "'), ','))"),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == '[[]]') {
                    //debugger;
                } else {
                    ReportSidebarJSON = JSON.parse(title);
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

        if (ReportSidebarJSON != undefined) {
            for (i = 0; i < ReportSidebarJSON.length; i++) {
                var Report = '<li class="Side_' + Functions.ReplaceCharAll(ReportSidebarJSON[i].RepName) + '">' +
                    '<a id="a_' + Functions.ReplaceCharAll(ReportSidebarJSON[i].RepName) + '" onclick="' + "SetData.localStorage(\'OpenForm\', \'" + Functions.ReplaceCharAll(ReportSidebarJSON[i].RepName) + "|Report_Divider\'); window.location.href = \'Report.html?RepId=" + ReportSidebarJSON[i].RepId + "\'; " + '">' +
                    '<i class="icon-bag"></i>' +
                    '<span class="title">' + ReportSidebarJSON[i].RepName + '</span>' +
                    '</a>' +
                    '</li>';

                $(".Side_Report_Divider").find('.sub-menu').eq(0).append(Report);
            }
        }
    },

    OpenForm: function () {
        return GetData.UrlParameter('Form');
    },

    FormCreation: function () {

        var FormName = Functions.OpenForm();
        var InputDat = "";

        var QuestionFormJSON = GetData.MultiSqlValue("OS_Question", "FormName = '" + FORM + "'");

        Functions.sortArray(QuestionFormJSON, "OrderNumber", true, false);

        if (QuestionFormJSON != undefined) {
            for (i = 0; i < QuestionFormJSON.length; i++) {
                if (QuestionFormJSON[i].Active == undefined || QuestionFormJSON[i].Active == true) {
                    var inputType = QuestionFormJSON[i].InputType;

                    if ((GetData.localStorage('RO') != 'undefined' && GetData.localStorage('RO').split(',').indexOf(GetData.LocalStorageSingleJSONData('Sidebar', 'Name', FORM, 'id_Sidebar')).toString() != -1) || (document.location.href.match(/[^\/]+$/)[0].substr(0, (document.location.href.match(/[^\/]+$/)[0].indexOf("?") > 0 ? document.location.href.match(/[^\/]+$/)[0].indexOf("?") : 99)) == "viewfrm.html")) {
                        //if (document.location.href.match(/[^\/]+$/)[0].substr(0, (document.location.href.match(/[^\/]+$/)[0].indexOf("?") > 0 ? document.location.href.match(/[^\/]+$/)[0].indexOf("?") : 99)) == "viewfrm.html") {
                        var toText = [16, 22, 47];
                        var toTextNoFormula = [17, 18, 19, 20, 21];
                        var toSwitch = [24];
                        var toSwitchWithComments = [54];
                        var toBlank = [32, 34];
                        var toInlineText = [57, 58, 641];
                        var toInlineTextNoFormula = [60, 61];
                        var toInlineSwitch = [59];
                        var toMultiCheckbox = [23];

                        if (toText.indexOf(inputType) != -1) {
                            inputType = 25;
                        }
                        if (toTextNoFormula.indexOf(inputType) != -1) {
                            inputType = 51;
                        }
                        if (toSwitch.indexOf(inputType) != -1) {
                            inputType = 46;
                        }
                        if (toSwitchWithComments.indexOf(inputType) != -1) {
                            inputType = 64;
                        }
                        if (toBlank.indexOf(inputType) != -1) {
                            inputType = 999;
                        }
                        if (toInlineText.indexOf(inputType) != -1) {
                            inputType = 62;
                        }
                        if (toInlineTextNoFormula.indexOf(inputType) != -1) {
                            inputType = 66;
                        }
                        if (toInlineSwitch.indexOf(inputType) != -1) {
                            inputType = 65;
                        }
                        if (toMultiCheckbox.indexOf(inputType) != -1) {
                            inputType = 88;
                        }
                    } else if (SUrl[3].indexOf('ValidationFrm.html') != -1) {
                        var toText = [16, 22, 47, 17, 18, 19, 20, 21];
                        var toSwitch = [24, 54];
                        var toBlank = [32, 34];
                        var toInlineText = [57, 58, 60, 61, 641];
                        var toMultiCheckbox = [23];

                        if (toText.indexOf(inputType) != -1) {
                            inputType = 112;
                        }
                        if (toSwitch.indexOf(inputType) != -1) {
                            inputType = 24;
                        }
                        if (toBlank.indexOf(inputType) != -1) {
                            inputType = 999;
                        }
                        if (toInlineText.indexOf(inputType) != -1) {
                            inputType = 111;
                        }
                        if (toMultiCheckbox.indexOf(inputType) != -1) {
                            inputType = 25;
                        }
                    }


                    if (QuestionFormJSON[i].FormName == FormName) {
                        InputDat = Functions.FieldCreation(QuestionFormJSON[i].Name, QuestionFormJSON[i].Icon, QuestionFormJSON[i].Title, QuestionFormJSON[i].BelongTo, QuestionFormJSON[i].PlaceHolder, QuestionFormJSON[i].Help, inputType, QuestionFormJSON[i].DefaultData, QuestionFormJSON[i].IsRequired, QuestionFormJSON[i].Formula, QuestionFormJSON[i].DataPull, QuestionFormJSON[i].DataValidation);
                        if (QuestionFormJSON[i].BelongTo != "" && QuestionFormJSON[i].BelongTo != " ") {
                            if (inputType == 57 || inputType == 58 || inputType == 59 || inputType == 60 || inputType == 61 || inputType == 62 || inputType == 65 || inputType == 69 || inputType == 73 || inputType == 111 || inputType == 641) {
                                $("#17_form_control-" + QuestionFormJSON[i].BelongTo).append(InputDat);
                            } else if (inputType == 67 || inputType == 68) {
                                $('.divForm').append(InputDat);
                            } else {
                                $("#" + QuestionFormJSON[i].BelongTo).append(InputDat);
                            }
                        } else {
                            $('.divForm').append(InputDat);
                        }
                        if (SUrl[3].indexOf('ValidationFrm.html') != -1) {
                            //$('[name$="' + QuestionFormJSON[i].Name + '"]').parent().html('<input type="checkbox" name="vehicle" value="Bike" style="position: absolute; margin-top: 9px;">' + $('[name$="' + QuestionFormJSON[i].Name + '"]').parent().html());
                            //$('label[for$="' + QuestionFormJSON[i].Name + '"]').after('<input type="checkbox" name="vehicle" value="Bike" style="position: absolute; margin-top: 9px;">');
                            $('[name$="' + QuestionFormJSON[i].Name + '"]').before('<div style="float: left;width: 20px;"><input type="checkbox" name="' + 'ValCheck_' + QuestionFormJSON[i].Name + '" style="margin-top: 9px;"></div>').wrap('<div style="float: left;width: calc(100% - 20px);"></div>');
                            $('[name$="' + QuestionFormJSON[i].Name + '"]').parent().parent().find('.help-block').css('float', 'left');
                        }
                    }
                }
            }
        }
        DataDefault();
    },

    FieldCreation: function (name, icon, title, belongTo, placeHolder, help, inputType, defaultData, isRequired, formula, dataPull, dataValidation, saving) {
        var INPUT_DAT = "";
        if (inputType == 67) {
            INPUT_DAT = '<div class="portlet box green">' +
                '    <div class="portlet-title">' +
                '        <div class="caption">' +
                '            <i class="fa fa-' + icon + '"></i>' + Functions.LanguageSelectItem(title) +
                '        </div>' +
                '        <div class="tools">' +
                '            <a href="javascript:;" class="collapse" data-original-title="" title="">' +
                '            </a>' +
                '        </div>' +
                '    </div>' +
                '    <div class="portlet-body form">' +
                '        <!-- BEGIN FORM-->' +
                '            <div class="form-body" id="' + belongTo + '" name="' + belongTo + '">' +
                '            </div>' +
                '        <!-- END FORM-->' +
                '    </div>' +
                '</div>';
        } else if (inputType == 68) {
            if ($('#TabbedDiv').length == 0) {
                $('.divForm').append('<div class="tabbable-custom nav-justified" id="TabbedDiv">' +
                    '<ul class="nav nav-tabs nav-justified" id="ulTabbed">' +
                    '</ul>' +
                    '<div class="tab-content" id="TabbedContent">' +
                    '</div>' +
                    '</div>');
            }
            if ($('#ulTabbed li').length == 0) {
                $('#ulTabbed').append('<li class="active"><a href="#' + belongTo + '" data-toggle="tab">' + Functions.LanguageSelectItem(title) + '</a></li>');
                $('#TabbedContent').append('<div class="tab-pane active" id="' + belongTo + '"></div>');
            } else {
                $('#ulTabbed').append('<li><a href="#' + belongTo + '" data-toggle="tab">' + Functions.LanguageSelectItem(title) + '</a></li>');
                $('#TabbedContent').append('<div class="tab-pane" id="' + belongTo + '"></div>');
            }

        } else {
            if (inputType == 507) {

                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_22_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="22_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input id="pac-input" class="controls" type="text" placeholder="Search Box" name="GoogleSearchbox"><div id="map"></div>' +
                    '<textarea style="display: none" class="form-control form-field" data-Saving="' + saving + '" id="22_form_control-' + name + '" name="' + name + '" type="text"></textarea><div><button type="button" class="btn btn-primary" id="StartEditing" onclick="ToogleEdit();">Start Editing</button><button type="button" class="btn btn-default" id="EndEditing" onclick="ToogleEdit();" disabled>End Editing</button><button type="button" class="btn btn-success" id="Freeze_Map" onclick="FreezeMap();">Freeze Map</button><button type="button" class="btn btn-danger" id="EndEditing" onclick="clearOverlays();" style="float: right;">Clear</button></div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>';

            } else if (inputType == 16) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input type="text" class="form-control form-field" id="1_form_control-' + name + '" name="' + name + '" data-IType="Input" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Saving="' + saving + '" data-Pull="' + dataPull + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-default="' + defaultData + '">' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 112) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input type="text" class="form-control form-field" id="1_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-IType="Input" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '">' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 99) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-3 input-icon">' +
                    '<input type="text" class="form-control form-field" id="19_form_control-' + name + '_get" name="get_' + name + '" data-IType="Input" data-IsRequired="' + isRequired + '"/>' +
                    '<input type="text" class="form-control form-field" id="1_form_control-' + name + '" name="' + name + '" data-itype="Input" data-isrequired="' + isRequired + '" style="display: none;"/>' + // style="display: none;"/>
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '<div class="col-md-3 input-icon">' +
                    '<img id="1_form_control-' + name + '_img" src="" style="float:left; height: 100px;">' +
                    '<span id="1_form_control-' + name + '_x" style="float: left; margin-left: -16px; margin-top: -5px; font-size: x-large; color: red; cursor: pointer; display: none;" onclick="$(\'#1_form_control-' + name + '\').val(\'\');' +
                    '$(\'#19_form_control-' + name + '_get\').attr(\'placeholder\',\'\');' +
                    '$(\'#1_form_control-' + name + '_img\').attr(\'src\',\'\');' +
                    '$(\'#1_form_control-' + name + '_img\').css(\'height\',\'0px\');' +
                    '$(\'#1_form_control-' + name + '_x\').hide();">X</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 1375) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-3 input-icon">' +
                    '<input type="text" class="form-control form-field" id="23_form_control-' + name + '_get" name="get_' + name + '" data-IType="Input" data-IsRequired="' + isRequired + '"/>' +
                    '<input type="text" class="form-control form-field" id="1_form_control-' + name + '" name="' + name + '" data-itype="Input" data-isrequired="' + isRequired + '" style="display: none;"/>' + // style="display: none;"/>
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '<div class="col-md-3 input-icon">' +
                    '<button type="button" class="btn btn-success" id="23_form_control-' + name + '_getBtn" onclick="GetData.geoLocation(this);"> Get Location </button>' +
                    '<button type="button" class="btn btn-primary" id="23_form_control-' + name + '_viewBtn" onclick="Functions.viewGeoLocation($(\'#1_form_control-' + name + '\').val());" style="display: none;"> View Location </button>' +
                    '<span id="1_form_control-' + name + '_x" style="float: left; margin-left: -50px; margin-top: 6px; font-size: medium; color: red; cursor: pointer; display: none;" onclick="$(\'#1_form_control-' + name + '\').val(\'\');' +
                    '$(\'#23_form_control-' + name + '_get\').attr(\'placeholder\',\'\');' +
                    '$(\'#23_form_control-' + name + '_viewBtn\').hide();' +
                    '$(\'#1_form_control-' + name + '_x\').hide();">X</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 115) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-3 input-icon">' +
                    '<input type="text" class="form-control form-field" id="20_form_control-' + name + '_get" name="get_' + name + '" data-IType="Input" data-IsRequired="' + isRequired + '" readonly/>' +
                    '<input type="text" class="form-control form-field" id="1_form_control-' + name + '" name="' + name + '" data-itype="Input" data-isrequired="' + isRequired + '" style="display: none;"/>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '<div class="col-md-3">' +
                    '<button type="button" class="btn btn-success" id="21_form_control-' + name + '_Select" onclick="$(\'#21_form_control-' + name + '_file\').trigger(\'click\')"> Select file </button>' +
                    '<button type="button" class="btn btn-warning" id="21_form_control-' + name + '_Change" onclick="$(\'#21_form_control-' + name + '_file\').trigger(\'click\')" style="display:none;"> Change </button>' +
                    '<button type="button" class="btn btn-danger" id="21_form_control-' + name + '_Remove" onclick="Functions.handleFileRemove(\'' + name + '\')" style="display:none;"> Remove </button>' +
                    '<button type="button" class="btn btn-primary" id="21_form_control-' + name + '_Download" onclick="Functions.handleFileDownload(\'' + name + '\')" style="display:none;"> Download </button>' +
                    '<input type="file" id="21_form_control-' + name + '_file" onchange="Functions.handleFileSelect(\'' + name + '\')" style="position:fixed;top: -100px;" name="...">' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 75) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input type="text" class="form-control" id="1_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-IType="Input" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-default="' + defaultData + '">' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 56) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_17_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div id="17_form_control-' + name + '" class="form-field" style="width: 100%; display: table; table-layout: fixed; border-spacing: 10px;" data-IType="17" data-Validation="' + dataValidation + '"></div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 70) {
                INPUT_DAT = '<div class="form-group form-md-line-input" style="margin-bottom: 0;padding-top: 0;" id="div_17_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div id="17_form_control-' + name + '" class="form-field" style="width: 100%; display: table; table-layout: fixed; border-spacing: 10px;" data-IType="17" data-Validation="' + dataValidation + '"></div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 57) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_1_form_control-' + name + '"><input type="text" class="form-control inlineTextbox form-field" data-IType="Input" id="1_form_control-' + name + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-default="' + defaultData + '">' +
                    '</div>';
            } else if (inputType == 111) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_1_form_control-' + name + '"><input type="text" class="form-control form-field" data-IType="Input" id="1_form_control-' + name + '" name="' + name + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '">' +
                    '</div>';
            } else if (inputType == 58) {
                var DropD = "";
                var Options = "";
                if (placeHolder.substr(0, 1) == "^") {
                    var values = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, "")));
                    Options = (values == undefined ? [] : Object.keys(values).map(function (key) {
                        return values[key].Column1;
                    }));
                } else if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
                    if (defaultData == Options[e]) {
                        DropD += '<option value="' + Options[e] + '" selected>' + Options[e] + '</option>';
                    } else {
                        DropD += '<option value="' + Options[e] + '">' + Options[e] + '</option>';
                    }
                }
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_7_form_control-' + name + '"><select class="form-control form-field inlineSelect select2me select2-allow-clear" data-IType="Select" id="7_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-default="' + defaultData + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" data-placeholder="Select...">' +
                    '<option value=""></option>' +
                    DropD +
                    '</select>' +
                    '</div>';
            } else if (inputType == 641) {
                var DropD = "";
                var Options = "";
                var cascade = false;

                if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else if (placeHolder.substr(0, 1) == "~") {
                    cascade = true;
                    Options = placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, "").replace(/ /g, "_").replace(/\(/g, "|Option_").replace(/[,€]+/g, " Option_").replace(/\)/g, "").split(";");
                    for (var e = 0; e < Options.length; e++) {
                        Options[e] = Options[e].split("|")[1] + '|' + Options[e].split("|")[0];
                    }
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
                    var sOptions = Options[e].split("|");
                    if (defaultData == Options[e]) {
                        DropD += '<option class="' + (cascade ? sOptions[0] : 'Option_' + sOptions[0].replace(/\ /g, '_')) + '" value="' + sOptions[1] + '" selected>' + sOptions[1] + '</option>';
                    } else {
                        DropD += '<option class="' + (cascade ? sOptions[0] : 'Option_' + sOptions[0].replace(/\ /g, '_')) + '" value="' + sOptions[1] + '">' + sOptions[1] + '</option>';
                    }
                }
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_7_form_control-' + name + '"><select class="form-control form-field select2me select2-allow-clear" data-IType="Select" id="7_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-default="' + defaultData + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" data-placeholder="Select...">' +
                    '<option value=""></option>' +
                    DropD +
                    '</select>' +
                    '</div>';
            } else if (inputType == 59) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_15_form_control-' + name + '"><input type="checkbox" data-IType="Switch" id="15_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + '></div>' +
                    '</div>';
            } else if (inputType == 65) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_9_form_control-' + name + '"><input type="checkbox" data-IType="Switch" id="9_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + ' readonly></div>' +
                    '</div>';
            } else if (inputType == 60) {
                INPUT_DAT = '<div class="inlineField" style="display: table-cell;vertical-align: top;" id="div_2_form_control-' + name + '"><div class="input-group input-icon date datepiker" style="border-spacing: 10px 0px;" data-date-format="mm/dd/yyyy" data-date="+0d">' +
                    '<input type="text" id="2_form_control-' + name + '" data-IType="Input" name="' + name + '" data-Saving="' + saving + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field inlineTextbox date-picker" readonly="" data-default="' + (defaultData == "" || defaultData == " " ? "" : (defaultData == "Now" ? DateFunctions.FormatDate(Date(), 'MM/dd/yyyy') : DateFunctions.FormatDate(defaultData, 'MM/dd/yyyy'))) + '">' +
                    '<span class="input-group-btn">' +
                    '<button class="btn clearDateBtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(\'\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').val(\'\'); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-times"></i></button>' +
                    '<button class="btn datepikerbtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').focus(); $(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-calendar"></i> Today</button>' +
                    '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 73) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_13_form_control-' + name + '"><button type="button" id="13_form_control-' + name + '" data-IType="13" style="width: 100%;" name="' + name + '" data-Formula="" data-Validation="' + dataValidation + '" onclick="' + Functions.ReplaceChar(formula, '"', "'") + '" class="btn btn-primary form-field">' + Functions.LanguageSelectItem(title) + '</button>' +
                    '</div>';
            } else if (inputType == 61) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_5_form_control-' + name + '"><div>' +
                    '<input type="text" id="5_form_control-' + name + '" data-IType="Input" data-Saving="' + saving + '" name="' + name + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field timepicker inlineTextbox timepicker-no-seconds" data-default="' + defaultData + '">' +
//                    '<span class="input-group-btn">' +
//                    '<button class="btn" onclick="$(\'#5_form_control-' + name + '\').val(\'\')" type="button"><i class="fa fa-times"></i></button>' +
//                    '<button class="btn" onclick="$(\'#5_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'hh:mm T\'))" type="button"><i class="fa fa-clock-o"></i> Set Current Time</button>' +
//                    '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 62) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_11_form_control-' + name + '"><div class="form-control form-control-static form-field" style="padding-left: 5px !important;background-color: transparent;border: 0;text-align: center;" data-IType="HTML" id="11_form_control-' + name + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-Pull="' + dataPull + '" data-default="' + defaultData + '"></div>' +
                    '</div>';
            } else if (inputType == 69) {
                INPUT_DAT = '<div id="div_h4_form_control-' + name + '" style="display: table-cell;vertical-align: top;text-align: center;color: #888888;"><h4 class="form-field" id="h4_form_control-' + name + '" data-Validation="' + dataValidation + '" style="margin: 0;">' + (defaultData != null && defaultData.length > 0 && defaultData.substr(0, 1) == "*" ? Functions.LanguageSelect(defaultData.substr(1, defaultData.indexOf("^") - 1), defaultData.substr(defaultData.indexOf("^") + 1)) : (defaultData == null || defaultData == 'null' ? '' : defaultData)) + '</h4></div>' +
                    '</div>';
            } else if (inputType == 66) {
                INPUT_DAT = '<div style="display: table-cell;vertical-align: top;" id="div_11_form_control-' + name + '"><div class="form-control form-control-static form-field" style="padding-left: 5px !important;background-color: transparent;border: 0;" data-IType="HTML" id="11_form_control-' + name + '" name="' + name + '" data-Pull="' + dataPull + '"></div>' +
                    '</div>';
            } else if (inputType == 63) {
                INPUT_DAT = '<div id="div_19_form_control-' + name + '" style="text-align: center;border-bottom-color: #888888;border-bottom-width: 1px;border-bottom-style: dashed; border-radius: 0px !important;"><span class="inputLabel">' + Functions.LanguageSelectItem(title) + '</span></div>';
            } else if (inputType == 32) {
                INPUT_DAT = '<div class="form-group form-md-line-input hidden" id="div_10_form_control-' + name + '" >' +
                    '<label class="col-md-3 inputLabel control-label" for="10_form_control-' + name + 'Val">' + Functions.LanguageSelectItem(title) + ' (val):</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input type="text" class="form-control form-field MasterID" data-IType="Input" data-Saving="' + saving + '" id="10_form_control-' + name + 'Val" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-Pull="' + dataPull + '" placeholder="' + placeHolder + '" data-MasterID="' + defaultData + '">' +
                    '<span class="help-block"></span>' +
                    '<i></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 35) {
                INPUT_DAT = '<div class="form-group form-md-line-input hidden" id="div_14_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="14_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="form-control form-field" data-IType="HTML" id="14_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '"><div>' +
                    '<span class="help-block"></span>' +
                    '<i></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 33) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_12_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="form-control form-control-static form-field" data-IType="HTML" id="12_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '"></div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 34) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_13_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<button type="button" data-IType="13" id="13_form_control-' + name + '" name="' + name + '" data-Formula="" data-Validation="' + dataValidation + '" onclick="' + Functions.ReplaceChar(formula, '"', "'") + '" class="btn btn-primary form-field">' + Functions.LanguageSelectItem(title) + '</button>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 17) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_2_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="2_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="input-group input-icon date datepiker" data-date-format="mm/dd/yyyy" data-date="+0d">' +
                    '<input type="text" data-IType="Input" id="2_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field date-picker" data-default="' + (defaultData == "" || defaultData == " " ? "" : (defaultData == "Now" ? DateFunctions.FormatDate(Date(), 'MM/dd/yyyy') : DateFunctions.FormatDate(defaultData, 'MM/dd/yyyy'))) + '">' +
                    '<span class="input-group-btn">' +
                    '<button class="btn clearDateBtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(\'\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').val(\'\'); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-times"></i></button>' +
                    '<button class="btn datepikerbtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').focus(); $(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-calendar"></i> Today</button>' +
                    '</span>' +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 18) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_3_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="3_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="input-group input-icon date datepiker" data-date-format="mm/dd/yyyy">' +
                    '<input type="text" data-IType="Input" id="3_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field date-picker" readonly="" data-default="' + (defaultData == "" || defaultData == " " ? "" : (defaultData == "Now" ? DateFunctions.FormatDate(Date(), 'MM/dd/yyyy') : DateFunctions.FormatDate(defaultData, 'MM/dd/yyyy'))) + '">' +
                    '<span class="input-group-btn">' +
                    '<button class="btn clearDateBtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(\'\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').val(\'\'); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-times"></i></button>' +
                    '<button class="btn datepikerbtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').focus(); $(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-calendar"></i> Today</button>' +
                    '</span>' +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 19) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_4_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="4_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="input-group date input-icon form_datetime" data-date="+0d">' +
                    '<input type="text" size="16" data-IType="Input" id="4_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field" readonly="" data-default="' + (defaultData == "" || defaultData == " " ? "" : (defaultData == "Now" ? DateFunctions.FormatDate(Date(), 'MM/dd/yyyy hh:mm T') : DateFunctions.FormatDate(defaultData, 'MM/dd/yyyy hh:mm T'))) + '">' +
                    '<span class="input-group-btn input-group-addon-span">' +
                    '<button class="btn clearDateBtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(\'\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').val(\'\'); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-times"></i></button>' +
                    '<button class="btn datepikerbtn" onclick="' + (Functions.isMobile('iOS') ? '$(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'MMMM dd, yyyy - hh:mm T\')); onFormFieldChange($(\'#2_form_control-' + name + '\'));' : '$(\'#2_form_control-' + name + '\').focus(); $(\'#2_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'yyyy-MM-dd\')); $(\'#2_form_control-' + name + '\').datepicker(\'update\'); onFormFieldChange($(\'#2_form_control-' + name + '\'));') + '" type="button"><i class="fa fa-calendar"></i> Today</button>' +
                    '</span>' +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 20) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_5_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="5_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="input-group input-icon">' +
                    '<input type="text" data-IType="Input" id="5_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field timepicker timepicker-no-seconds" data-default="' + defaultData + '">' +
                    '<span class="input-group-btn">' +
                    '<button class="btn clearTimeBtn" onclick="$(\'#5_form_control-' + name + '\').val(\'\')" type="button"><i class="fa fa-times"></i></button>' +
                    '<button class="btn timepikerbtn" onclick="$(\'#5_form_control-' + name + '\').val(DateFunctions.FormatDate(Date(), \'hh:mm T\'))" type="button"><i class="fa fa-clock-o"></i> Set Current Time</button>' +
                    '</span>' +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 21) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_6_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="6_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="input-group input-icon">' +
                    '<input type="text" data-IType="Input" id="6_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '"  placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" class="form-control form-field defaultrange" data-default="' + defaultData + '">' +
                    '<span class="input-group-btn">' +
                    '<button class="btn default date-range-toggle" type="button"><i class="fa fa-calendar"></i></button>' +
                    '</span>' +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 22) {
                var DropD = "";
                var Options = "";
                if (placeHolder.substr(0, 1) == "^") {
                    var values = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, "")));
                    Options = (values == undefined ? [] : Object.keys(values).map(function (key) {
                        return values[key].Column1;
                    }));
                } else if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else if (placeHolder.substr(0, 1) == ";") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(";");
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
                    if (defaultData == Options[e]) {
                        DropD += '<option value="' + Options[e] + '" selected>' + Options[e] + '</option>';
                    } else {
                        DropD += '<option value="' + Options[e] + '">' + Options[e] + '</option>';
                    }
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_7_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="7_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<select class="form-control form-field select2me select2-allow-clear" data-IType="Select" id="7_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-default="' + defaultData + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" data-placeholder="Select...">' +
                    '<option value=""></option>' +
                    DropD +
                    '</select>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 114) {
                var DropD = "";
                var Options = "";
                if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
                    var sOptions = Options[e].split("|");
                    if (defaultData == Options[e]) {
                        DropD += '<option class="Option_' + sOptions[0].replace(/\ /g, '_') + '" value="' + sOptions[1] + '" selected>' + sOptions[1] + '</option>';
                    } else {
                        DropD += '<option class="Option_' + sOptions[0].replace(/\ /g, '_') + '" value="' + sOptions[1] + '">' + sOptions[1] + '</option>';
                    }
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_7_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="7_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<select class="form-control form-field select2me select2-allow-clear" data-IType="Select" id="7_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-default="' + defaultData + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" data-placeholder="Select...">' +
                    '<option value=""></option>' +
                    DropD +
                    '</select>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 71) {
                var DropD = "";
                var Options = "";
                if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
//                    DropD += '<input class="text-nicelabel" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" data-nicelabel=\'{"position_class": "text_radio", "checked_text": "' + Options[e] + '", "unchecked_text": "' + Options[e] + '"}\' ' + (defaultData == Options[e] ? 'checked' : '') + ' type="radio" />';
                    if (defaultData == Options[e]) {
                        DropD += '<label class="btn green border-gray active"><input type="radio" class="toggle" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" value="' + Options[e] + '"/> ' + Options[e] + ' </label>';
                    } else {
                        DropD += '<label class="btn border-gray green"><input type="radio" class="toggle" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" value="' + Options[e] + '"/> ' + Options[e] + ' </label>';
                    }
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_18_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="18_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="btn-group form-control form-field btn-group-circle" data-IType="Radio" id="18_form_control-' + name + '" data-Saving="' + saving + '" data-Formula="' + 
//                    '<div class="form-control form-field" data-IType="Radio" id="18_form_control-' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '">' +
                    '" data-Validation="' + dataValidation + '" data-toggle="buttons">' +
                    DropD +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 642) {
                var DropD = "";
                var Options = "";
                if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }
                for (var e = 0; e < Options.length; e++) {
                    if (defaultData == Options[e]) {
                        DropD += '<label class="btn green border-gray active"><input type="radio" class="toggle" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" value="' + Options[e] + '"/> ' + Options[e] + ' </label>';
                    } else {
                        DropD += '<label class="btn border-gray green"><input type="radio" class="toggle" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" value="' + Options[e] + '"/> ' + Options[e] + ' </label>';
                    }
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_18_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="18_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="btn-group-justified form-control btn-group-circle" data-IType="Radio" id="18_form_control-' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-toggle="buttons">' +
                    DropD +
                    '</div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 47) {
                var DropD = "";
                var Options = "";

                Functions.Connected();
                $.ajax({
                    type: "POST",
                    data: "SQLString=SELECT DISTINCT Answer FROM OS_Answer WHERE Question_Id = '" + name + "' and GR_Season = '" + GetData.localStorage('Season') + "'",
                    dataType: "xml",
                    url: DUrl + "WebServiceOsiris.asmx/GetDataTable2",

                    cache: false,
                    async: false,
                    success: function (data) {

                        var title = $(data).find('string').first().text();

                        if (title == '[[]]') {
                            //debugger;
                        } else {
                            if (title != 'No rows found') {
                                Options = title.replace(/(\r\n|\n|\r)/gm, "").split('^');
                            }
                        }
                    },
                    error: function (a, b, c) {
                        if (GetData.localStorage("onScreenError") == "true") {
                            handleAlerts.Simple(a.responseText);
                        } else {
                            console.log(a.responseText);
                        }
                    }
                });
                for (var e = 0; e < Options.length; e++) {
                    DropD += '<option value="' + Options[e] + '">' + Options[e] + '</option>';
                }
                DropD += '<option value="New">New</option>';
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_7_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="7_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + (isRequired == 1 ? '<span class="required">*</span>' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<select class="form-control form-field select2me select2-allow-clear" data-IType="Select" id="7_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-default="' + defaultData + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" data-placeholder="Select...">' +
                    '<option value=""></option>' +
                    DropD +
                    '</select>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="form-group form-md-line-input hidden" id="7_form_control-' + name + '_New">' +
                    '<label class="col-md-3 inputLabel control-label" for="1_form_control-' + name + '">New: </label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<input type="text" class="form-control form-field" data-IType="Input" id="1_form_control_New-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-IsRequired="' + isRequired + '">' +
                    '<span class="help-block"></span>' +
                    '<i></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 23) {
                var DropD = "";
                var SelectAll = "";
                var UnSelectAll = "";
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    var Opt = Options[e].replace(/\(COMMA?\)|\/|["'%&,. \-()]/g, "_");
                    DropD += '<div class="md-checkbox">' +
                        '<input type="checkbox" data-IType="Check" id="8_checkbox-' + name + '_' + Opt + '" data-Saving="' + saving + '" name="' + name + '_' + Opt + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" class="md-check form-field">' +
                        '<label for="8_checkbox-' + name + '_' + Opt + '">' +
                        '<span></span>' +
                        '<span class="check"></span>' +
                        '<span class="box"></span>' +
                        Options[e].replace(/\(COMMA?\)/g, ',') + '</label>' +
                        '</div>';
                    SelectAll += '$(\'#8_checkbox-' + name + '_' + Opt + '\').attr(\'checked\', \'checked\');';
                    UnSelectAll += '$(\'#8_checkbox-' + name + '_' + Opt + '\').removeAttr(\'checked\');';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_8_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="md-checkbox-list">' +
                    '<div class="checkboxList">' + DropD + '</div>' +
                    '<button type="button" onclick="' + SelectAll + '" class="btn btn-success">' + Functions.LanguageSelectItem(27) + '</button><button type="button" onclick="' + UnSelectAll + '" class="btn btn-danger">' + Functions.LanguageSelectItem(28) + '</button>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 117) {
                var DropD = "";
                var SelectAll = "";
                var UnSelectAll = "";
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {

                    var sOptions = Options[e].split("|");
                    DropD += '<div class="md-checkbox">' +
                        '<input type="checkbox" data-IType="Check" id="8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" name="' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '" class="md-check form-field Option_' + sOptions[0].replace(/\ /g, '_') + '">' +
                        '<label for="8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '">' +
                        '<span></span>' +
                        '<span class="check"></span>' +
                        '<span class="box"></span>' +
                        sOptions[1] + '</label>' +
                        '</div>';
                    SelectAll += 'if($(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '\').parent().is(\':visible\')) {$(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '\').attr(\'checked\', \'checked\');}';
                    UnSelectAll += 'if($(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '\').parent().is(\':visible\')) {$(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(sOptions[1], " ", "_") + '\').removeAttr(\'checked\');}';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_8_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="md-checkbox-list">' +
                    DropD +
                    '<button type="button" onclick="' + SelectAll + '" class="btn btn-success">' + Functions.LanguageSelectItem(27) + '</button><button type="button" onclick="' + UnSelectAll + '" class="btn btn-danger">' + Functions.LanguageSelectItem(28) + '</button>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 88) {
                var DropD = "";
                var SelectAll = "";
                var UnSelectAll = "";
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD += '<div class="md-checkbox">' +
                        '<input type="checkbox" data-IType="Check" id="8_checkbox-' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" data-Saving="' + saving + '" name="' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '" class="md-check form-field" disabled>' +
                        '<label for="8_checkbox-' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '">' +
                        '<span></span>' +
                        '<span class="check"></span>' +
                        '<span class="box"></span>' +
                        Options[e] + '</label>' +
                        '</div>';
                    SelectAll += '$(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '\').attr(\'checked\', \'checked\');';
                    UnSelectAll += '$(\'#8_checkbox-' + name + '_' + Functions.ReplaceChar(Options[e], " ", "_") + '\').removeAttr(\'checked\');';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_8_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="md-checkbox-list">' +
                    DropD +
                    '<button type="button" onclick="' + SelectAll + '" class="btn btn-success">' + Functions.LanguageSelectItem(27) + '</button><button type="button" onclick="' + UnSelectAll + '" class="btn btn-danger">' + Functions.LanguageSelectItem(28) + '</button>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 24) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_9_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="9_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9 input-icon">' +
                    '<div class="col-md-12"><input type="checkbox" data-IType="Switch" id="9_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + '></div>' +
                    '<span class="help-block" style="display:block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '<i class="fa fa-' + icon + '"></i>' +
                    '<div class="form-control-focus">' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 54) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_9_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="9_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="col-md-12"><div style="float: left;"><input type="checkbox" data-IType="Switch" id="9_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + '></div>' +
                    '<div class="col-md-9" style="float: left;"><input type="text" class="form-control form-field" data-IType="Input" id="1_form_control-' + name + '_Comments" name="' + name + '_Comments" placeholder="' + Functions.LanguageSelectItem(39) + '"/>' +
                    '</div></div>' +
                    '<span class="help-block">' + Functions.LanguageSelectItem(help) + '</span>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 64) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_15_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<input type="checkbox" data-IType="Switch" id="15_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + ' readonly>' +
                    '<div style="margin-left: 160px;width: auto;"><div class="form-control form-control-static form-field" id="11_form_control-' + name + '_Comments" name="' + name + '_Comments"></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 46) {
                var DropD;
                var Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                for (var e = 0; e < Options.length; e++) {
                    DropD = 'data-on-text="' + Options[0] + '" data-off-text="' + Options[1] + '"';
                }
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_15_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<input type="checkbox" data-IType="Switch" id="15_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-IsRequired="' + isRequired + '" data-Validation="' + dataValidation + '" data-size="large" class="make-switch form-field" ' + defaultData + ' ' + DropD + ' readonly>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 25) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_11_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="form-control form-control-static form-field" data-IType="HTML" id="11_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-Pull="' + dataPull + '" data-default="' + defaultData + '"></div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 608) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_11_form_control-' + name + '" style="padding: 0; margin: 0;">' +
                    '<div class="col-md-9">' +
                    '<div class="form-control form-control-static form-field" data-IType="HTML"  style="padding: 0; margin: 0;" id="11_form_control-' + name + '" name="' + name + '" >' + Functions.LanguageSelectItem(title) + '</div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 80) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_1_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<input type="text" class="form-control form-field" data-IType="Input" id="1_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '" data-Validation="' + dataValidation + '" data-IsRequired="' + isRequired + '" data-Pull="' + dataPull + '" placeholder="' + Functions.LanguageSelectItem(placeHolder) + '" data-default="' + defaultData + '" readonly>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 51) {
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_11_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<div class="form-control form-control-static form-field" data-IType="HTML" id="11_form_control-' + name + '" name="' + name + '" data-Saving="' + saving + '" data-Pull="' + dataPull + '"></div>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 52) {
                var DropD = "";
                var tag = {};

                var Options = "";
                
                if (placeHolder.substr(0, 1) == "@") {
                    Options = (eval(placeHolder.substr(1).replace(/(\r\n|\n|\r)/gm, ""))).split(/[,€]+/);
                } else if (placeHolder.substr(0, 1) == "^") {
                    Options = (placeHolder.substr(1)).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                } else {
                    Options = (placeHolder).replace(/(\r\n|\n|\r)/gm, "").split(/[,€]+/);
                }

                if (placeHolder.substr(0, 1) == "^") { 
                    for (var o = 0; o < Options.length; o++) {
                        DropD = DropD + '<option value="' + Options[o] + '">' + Options[o] + '</option>';
                    }
                } else {
                    for (var j = 0; j < Options.length; j++) {
                        var KeyVal = Options[j].replace(/(\r\n|\n|\r)/gm, "").split('|');

                        Functions.addValue(tag, KeyVal[0], KeyVal[1]);
                    }

                    for (var key in tag) {
                        var obj = tag[key];
                        DropD = DropD + '<optgroup label="' + key + '">';
                        for (var o = 0; o < tag[key].length; o++) {
                            DropD = DropD + '<option value="' + tag[key][o] + '">' + tag[key][o] + '</option>';
                        }
                        DropD = DropD + '</optgroup>';
                    }
                }
                
                INPUT_DAT = '<div class="form-group form-md-line-input" id="div_16_form_control-' + name + '">' +
                    '<label class="col-md-3 inputLabel control-label" for="16_form_control-' + name + '">' + Functions.LanguageSelectItem(title) + (title != 0 ? ':' : '') + '</label>' +
                    '<div class="col-md-9">' +
                    '<select multiple="multiple" class="multi-select form-field" data-IType="MultiSelect" id="16_form_control-' + name + '" data-Saving="' + saving + '" name="' + name + '">' + DropD + '</select>' +
                    '</div>' +
                    '</div>';
            } else if (inputType == 31) {

                if (formula != undefined && formula != "" && formula != " ") {
                    var DataTable;
                    Functions.Connected();
                    $.ajax({
                        type: "POST",
                        data: "SQLString=" + escape(formula.replace(/\+/g, "(PLUS)").replace(/\*SelectID\*/g, "''").replace(/\bGETPAGEDATA\('\w+'\)/g, "''")),
                        dataType: "text",
                        url: DUrl + "WebServiceOsiris.asmx/GetDataTable",

                        cache: false,
                        async: false,
                        success: function (data) {

                            var xml = data,
                                xmlDoc = $.parseXML(xml),
                                $xml = $(xmlDoc),
                                $title = $xml.find("string");

                            DataTable = JSON.parse($title.text());

                        },
                        error: function (a, b, c) {
                            if (GetData.localStorage("onScreenError") == "true") {
                                handleAlerts.Simple(a.responseText);
                            } else {
                                console.log(a.responseText);
                            }
                        }
                    });
                    
                    if (DataTable.length > 0) {
                        INPUT_DAT = '<table class="table table-striped table-hover table-bordered" name="sample_editable_1" data-Pull="' + dataPull + '" data-Formula="' + Functions.ReplaceChar(formula, '"', "'") + '">' +
                            '<thead><tr>';
                        var b;
                        var QuestionFormJSON = GetData.MultiSqlValue("OS_Question", "FormName = '" + FORM + "'");
                        for (b = 0; b < DataTable[0].length; b++) {
                            INPUT_DAT += '<th' + (DataTable[0][b].substr(0, 1) == '!' ? ' style="width: 60px;"' : '') + '>' + (DataTable[0][b].substr(0, 1) == '@' || DataTable[0][b].substr(0, 1) == '!' ? DataTable[0][b].substr(1).replace(/[_]/g, " ") : ((Functions.LanguageSelectItem(Functions.indexOfObject(QuestionFormJSON, 'Name', DataTable[0][b], 'Title')) == undefined) || (Functions.LanguageSelectItem(Functions.indexOfObject(QuestionFormJSON, 'Name', DataTable[0][b], 'Title')) == -1) ? DataTable[0][b].replace(/[_]/g, " ") : Functions.LanguageSelectItem(Functions.indexOfObject(QuestionFormJSON, 'Name', DataTable[0][b], 'Title')))) + '</th>';
                        }
                        //INPUT_DAT += '<th>Edit</th><th>Delete</th></tr></thead>' +
                        //INPUT_DAT += '<th>Delete</th>';
                        INPUT_DAT += '</tr></thead><tbody>';
                        for (b = 1; b < DataTable.length; b++) {
                            INPUT_DAT += '<tr>';
                            for (var e = 0; e < DataTable[b].length; e++) {
                                if (DataTable[0][e].substr(0, 1) == '!') {
                                    INPUT_DAT += '<td style="text-align: center;"><a href="javascript:void(0)" onclick="' + DataTable[b][e].replace(/\(PLBUS\)/g, '(PLUS)').replace(/\(%%\)/g, '(PERCENT)') + ' Functions.FillDataTable(function() {onFormFieldChange();});"><i class="icon-trash"></i></a></td>';
                                } else if (DataTable[b][e].substr(0, 1) == '~') {
                                    INPUT_DAT += '<td><a href="/frm.html?Form=' + FORM + '&MasterId=' + DataTable[b][e].substr(1) + '">' + DataTable[b][e].substr(1) + '</a></td>';
                                } else {
                                    INPUT_DAT += '<td>' + DataTable[b][e] + '</td>';
                                }
                            }
                            //InputDat += '<td><a class="edit" href="javascript:;">Edit </a></td><td><a class="delete" href="javascript:;">Delete </a></td></tr>';
                            //INPUT_DAT += '<td><a class="delete" href="javascript:;">Delete </a></td>';
                            INPUT_DAT += '</tr>';
                        }
                        INPUT_DAT += '</tbody>' +
                            '</table>';
                    }
                }
            }
        }
        return INPUT_DAT;
    },

    FillDataTable: function (callback) {
        if ($('[name="sample_editable_1"]').length > 0) {
            for (var q = 0; q < $('[name="sample_editable_1"]').length; q++) {
                var whereClause = ($($('[name="sample_editable_1"]')[q]).attr('data-Pull') == '' || $($('[name="sample_editable_1"]')[q]).attr('data-Pull') == ' ' ? $('#MasterIdSelect').val() : GetData.PageFieldValue($($('[name="sample_editable_1"]')[q]).attr('data-Pull')));
            
                try {
                    var t = $($('[name="sample_editable_1"]')[q]).DataTable();
                    t.clear().draw();
                    FTable = $($('[name="sample_editable_1"]')[q]).attr('data-Formula').replace(/\*SelectID\*/g, "'" + whereClause + "'").replace(/\[SEASON\]/g, GetData.localStorage('Season')).replace(/\+/g, '(PLUS)');

                    var STRINGSEARCH = "GETPAGEDATA",
                        LOOP_COUNT = 0;
                    LOOP_COUNT = FTable.split(STRINGSEARCH).length - 1;

                    for (var i = 0; i < LOOP_COUNT; i++) {
                        var startStr = FTable.indexOf(STRINGSEARCH);
                        var endStr = FTable.indexOf("')", startStr + 13) + 2;
                        var fieldName = eval("GetData.PageFieldValue('" + FTable.substr(startStr + 13, FTable.indexOf("')", startStr + 13) - (startStr + 13)) + "')");

                        FTable = FTable.substr(0, startStr) + fieldName + FTable.substr(endStr);
                    }

                    FTable = escape(FTable);

                    var DTable;
                    Functions.Connected();
                    $.ajax({
                        type: "POST",
                        data: "SQLString=" + FTable,
                        dataType: "text",
                        url: DUrl + "WebServiceOsiris.asmx/GetDataTable",

                        cache: false,
                        async: false,
                        success: function (data) {

                            var xml = data,
                                xmlDoc = $.parseXML(xml),
                                $xml = $(xmlDoc),
                                $title = $xml.find("string");

                            DTable = JSON.parse($title.text());

                            for (b = 1; b < DTable.length; b++) {
                                //DTable[b].push("<a class=\"edit\" href=\"javascript:;\">Edit </a>");
                                //DTable[b].push("<a class=\"delete\" href=\"javascript:;\">Delete </a>");
                                if (DTable[0][0].substr(0, 1) == '!') {
                                    DTable[b][0] = '<a href="javascript:void(0)" onclick="' + DTable[b][0].replace(/\(PLBUS\)/g, '(PLUS)').replace(/\(%%\)/g, '(PERCENT)') + ' Functions.FillDataTable(function() {onFormFieldChange();});"><i class="icon-trash"></i></a>';
                                    var deleteCell = t.row.add(DTable[b]).draw().node();
                                    $('td:first', deleteCell).css('text-align', 'center');
                                } else if (DTable[b][0].substr(0, 1) == '~') {
                                    DTable[b][0] = '<a href="/frm.html?Form=' + FORM + '&MasterId=' + DTable[b][0].substr(1) + '">' + DTable[b][0].substr(1) + '</a>';
                                    t.row.add(DTable[b]).draw();
                                } else {
                                    t.row.add(DTable[b]).draw();
                                }
                            }
                            if (callback != undefined) {
                                callback();
                            }
                        },
                        error: function (a, b, c) {
                            if (GetData.localStorage("onScreenError") == "true") {
                                handleAlerts.Simple(a.responseText);
                            } else {
                                console.log(a.responseText);
                            }
                        }
                    });
                } catch (err) {

                }
            }
        }
    },

    Login: function (username, password) {

        //Aljax Call
        if (username == 'vtorr' && password == 'test') {
            SetData.localStorage('AccessLevel', '1');
            SetData.localStorage('ActiveLanguage', 'Español');
            SetData.localStorage('Clasification', '1');
            SetData.localStorage('EmpName', 'Victor Torres Rubio');
            SetData.localStorage('NickName', 'Kalehm');
            SetData.localStorage('Picture', 'data:image/jpg;base64, ');
            SetData.localStorage('SubClasification', '0');
            SetData.localStorage('Title', 'Programmer');
            SetData.localStorage('UserId', 'vtorr');
            location.href = "Dashboard.html";
        } else {
            $(".wrong-password").show();
        }
    },

    isMobile: function (device) {
        var MOBILE = {
            Android: function () {
                return navigator.userAgent.match(/Android/i);
            },
            BlackBerry: function () {
                return navigator.userAgent.match(/BlackBerry/i);
            },
            iOS: function () {
                return navigator.userAgent.match(/iPhone|iPad|iPod/i);
            },
            Opera: function () {
                return navigator.userAgent.match(/Opera Mini/i);
            },
            Windows: function () {
                return navigator.userAgent.match(/IEMobile/i);
            },
            any: function () {
                return (MOBILE.Android() || MOBILE.BlackBerry() || MOBILE.iOS() || MOBILE.Opera() || MOBILE.Windows());
            }
        };

        try {
            if (MOBILE[device]()) {
                return true;
            } else {
                return false;
            }
        } catch (E) {

            alert("(" + device + "): Is not a valid Device.  \n\nPlease use Android, BlackBerry, iOS, Opera, Windows or any");

            return false;
        }

    },

    hideOnMobile: function (e) {
        if (Functions.isMobile('any')) {
            $(e).hide();
        }
    },

    PhoneNumber: function (phone) {
        phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        return phone;
    },

    LeadZero: function (num, size) {
        var s = num + "";
        while (s.length < size) s = "0" + s;
        return s;
    },

    AddOrUpdateLocalStorage: function (keyName, jsonFieldId, arrString) {
        if (GetData.localStorage(keyName) == undefined) {
            SetData.localStorage(keyName, "[]");
        }
        if (arrString != undefined && arrString.length != 0) {
            var DATA = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key

            for (var j = 0; j < arrString.length; j++) {
                var found = false;

                for (var i = 0; i < DATA.length; i++) {
                    if (DATA[i][jsonFieldId] == arrString[j][jsonFieldId]) {
                        DATA.splice(i, 1, arrString[j]);
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    DATA.push(arrString[j]);
                }
            }
            SetData.localStorage(keyName, JSON.stringify(DATA));
        }
    },

    decimalPlaces: function (num) {
        var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
        if (!match) {
            return 0;
        }
        return Math.max(
            0,
            // Number of digits right of decimal point.
            (match[1] ? match[1].length : 0)
            // Adjust for scientific notation.
            -
            (match[2] ? +match[2] : 0));
    },

    RemoveExtraDecimalPlaces: function (from, size) {
        if (Functions.decimalPlaces(from) >= size) {
            return Number(from.toString().slice(0, size * -1));
        } else {
            return Number(from);
        }
    },

    RemoveCharacterInPosition: function (str, position, end) {
        if (end == undefined) {
            str = str.slice(0, position) + str.slice(position + 1);
        } else {
            str = str.slice(0, position) + str.slice(end + 1);
        }
        return str;
    },

    AddCharacterInPosition: function (str, text, position) {
        str = str.slice(0, position - 1) + text + str.slice(position - 1);
        return str;
    },
    
    validateString: function (string, format/*^[A-Z]{2}[0-9]{4}-[0-9]{5}$ ej. FL0301-12345*/) {
        var regex = new RegExp(format, "i");
        if (!regex.test(string)) {
            return false;
        } else {
            return true;
        }        
    },

    PrintZebra: function (data, printerIP, qty) {

        var startBracket = 0;
        var endBracket = 0;
        var dataBracket = '';
        var loopTime = data.split('{').length - 1;

        for (var i = 0; i < loopTime; i++) {
            if (data.substr(data.indexOf('{', 0) - 1, 1) == "*") {
                startBracket = data.indexOf('{', 0) + 1;
                endBracket = data.indexOf('}', 0);
                dataBracket = data.substr(startBracket, endBracket - startBracket);

                data = Functions.RemoveCharacterInPosition(data, startBracket - 1, endBracket);
                data = Functions.AddCharacterInPosition(data, "└" + dataBracket + "┘", startBracket);
            } else {
                startBracket = data.indexOf('{', 0) + 1;
                endBracket = data.indexOf('}', 0);
                dataBracket = GetData.PageFieldValue(data.substr(startBracket, endBracket - startBracket));

                data = Functions.RemoveCharacterInPosition(data, startBracket - 1, endBracket);
                data = Functions.AddCharacterInPosition(data, dataBracket, startBracket);
            }
        }

        data = data.replace(/\└/g, "{").replace(/\┘/g, "}");

        if (printerIP == undefined || printerIP == '') {
            if (GetData.localStorage('LabelPrinter') == null) {
                handleAlerts.Simple('Please select a printer before sending data');
                return;
            } else {
                printerIP = GetData.localStorage('LabelPrinter').split('|')[1];
            }
        }
        var url = "http://" + printerIP + "/pstprnt";

        if (qty == undefined) {
            qty = 1;
        }
        while (--qty + 1) {
            $.ajax({
                type: "POST",
                dataType: "xml",
                url: url,
                data: data,

                async: true
            });
        }
    },

    CalibratePrinter: function () {
        if (GetData.localStorage('LabelPrinter') == null) {
            handleAlerts.Simple('Please select a printer before calibrating');
        } else {
            var url = "http://" + GetData.localStorage('LabelPrinter').split('|')[1] + "/pstprnt";
            var data = '^~jc^xa^jus^xz';
            $.ajax({
                type: "POST",
                dataType: "xml",
                url: url,
                data: data,

                async: true
            });
        }
    },

    ExternalCapture: function (data) {
        if (data.substr(0, 1) == '@') {
            window.location.href = data.substr(1);
        } else if (data.substr(0, 1) == '*') {
            window.location.href = data.substr(2, data.length - 3);
        } else {
            //alert(data);
            //alert(prevFocus.attr("id"));
            if (typeof prevFocus !== 'undefined') {
                //if (prevFocus[0].nodeName == "SELECT") {
                //    prevFocus.val(data).trigger('change');
                //} else
                if (prevFocus.attr("id").substr(0, 2) == "19") {
                    $('#1_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1)).val(data);
                    $('#19_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1) + '_get').attr('placeholder', 'Signature Captured');
                    $('#1_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1) + '_img').attr('src', 'data:image/png;base64,' + $('#1_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1)).val());
                    $('#1_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1) + '_x').show();
                    $('#1_form_control-' + prevFocus.attr("id").substr(0, prevFocus.attr("id").length - 4).substr(prevFocus.attr("id").indexOf("-") + 1) + '_img').css('height', '100px');
                } else if (prevFocus.attr("id") == "SearchField") {
                    Functions.Search(data, $('#7_form_control_Search').val());
                } else {
                    prevFocus.val(data);
                    prevFocus.val(data).trigger('change');
                }
                //if (prevFocus.attr("id") == "MasterIdSelect") {
                //    prevFocus.trigger("click");
                //    $("#MasterIdSelect").change();
                //}
                if (typeof onFormFieldChange == "function") {
                    onFormFieldChange();
                    DataDefault();
                }
            } else {
                handleAlerts.Simple('Please select a field before Scanning or adding a Signature');
            }
        }
    },

    Search: function (term, for_term) {
        if (for_term == 'Profile') {
            var SearchTerm = GetData.SingleSqlValue("UserId", "OS_User", "Name LIKE '%" + term + "%' or Email LIKE '" + term + "%' or WorkExt LIKE '%" + term + "%' or NickName LIKE '%" + term + "%' or EmpId LIKE '%" + term + "%' or UserId LIKE '" + term + "'", true);
            if (SearchTerm != undefined && SearchTerm.length == 1) {
                window.location.href = "SearchProfile.html?userId=" + SearchTerm[0].UserId;
            } else if (SearchTerm == undefined) {
                handleAlerts.Simple("Couldn't find the profile based on that term.  Please try again with some other data.  Thanks");
            } else {
                handleAlerts.Simple("There are more than one user with the same term that you wrote.  Please try again with some other data.  Thanks");
                debugger;
            }
        } else {
            if (SUrl[3].substr(0, 8) == "viewfrm." || SUrl[3].substr(0, 4) == "frm.") {
                GetData.SqlValue("Select '" + FORM + "' (PLUS) '|' (PLUS) SUBSTRING(Form_Id,CHARINDEX('|',Form_Id) (PLUS) 1,10000) Form_Id INTO #T1 From dbo.OS_Answer WHERE Answer LIKE '(PERCENT)" + term + "(PERCENT)' and [Site] = '" + GetData.localStorage('Classification') + "' and GR_Season = '" + GetData.localStorage('Season') + "' SELECT DISTINCT Form_Id FROM dbo.OS_Answer WHERE Form_Id IN (SELECT * FROM #T1) DROP TABLE #T1",true,false,function(data) {
                    if (data.length == 1) {
                        window.location.href = (SUrl[3].substr(0, 4) == "frm." ? "frm.html" : "viewfrm.html") + "?Form=" + FORM + "&MasterId=" + data[0].Form_Id.substr(data[0].Form_Id.indexOf("|") + 1);
                    } else {
                        window.location.href = "Search.html?Term=" + term;
                    }
                });
            } else {
                window.location.href = "Search.html?Term=" + term;
            }
        }
//            
//            
//            
//            var Findings = GetData.SingleSqlValue("Select '" + FORM + "' + '|' + SUBSTRING(Form_Id,CHARINDEX('|',Form_Id) + 1,10000) Form_Id INTO #T1 From dbo.OS_Answer WHERE Answer LIKE '%C010%' and [Site] = 'Juana Diaz' and GR_Season = '2018' SELECT DISTINCT Form_Id FROM dbo.OS_Answer WHERE Form_Id IN (SELECT * FROM #T1) DROP TABLE #T1");
//            if (MasterId.length == 1) {
//                var SearchTerm = GetData.SingleSqlValue("Form_Id", "OS_Answer", "Answer like '(PERCENT)" + term + "(PERCENT)' and [Site] = '" + GetData.localStorage('Classification') + "' and GR_Season = '" + GetData.localStorage('Season') + "' AND Question_Id <> 'DContainer_Batch'", true);
//                if (SearchTerm != undefined && SearchTerm.length == 1 && SUrl[3].substr(0, 4) == "frm.") {
//                    window.location.href = "frm.html?Form=" + FORM + "&MasterId=" + SearchTerm[0].Form_Id.substr(SearchTerm[0].Form_Id.indexOf("|") + 1);
//                } else {
//                    window.location.href = "Search.html?Term=" + term;// + "&For=" + for_term;
//                    debugger;
//                }
//            } else if (MasterId.length == 0) {
//                handleAlerts.Simple(Functions.LanguageSelect('No se encontro nada con ese texto. Gracias', 'We could''t find anything with that text.  Thanks'));
//            } else {
//                window.location.href = "Search.html?Term=" + term;
//            }
//            
//        }
    },

    ReplaceAll: function (str, find, replace) {
        return str.replace(new RegExp(find, 'g'), replace);
    },

    ReplaceCharAll: function (str) {

        if (typeof str != "number") {
            str = str.toString().replace(/[^a-zA-Z0-9.-]/g, '_');
        }

        return str;

    },

    ReplaceChar: function (str, from /* |./ ^a-zA-Z0-9.- */ , to) {

        var REP_STRING = new RegExp('[' + from + ']', 'g');

        if (str != null && typeof str != "number") {
            str = str.toString().replace(REP_STRING, to);
        }

        return str;

    },

    SendAnswers: function (FORM_DATA /*{userid}ÿ{Form}ÿ{Depend}ÿ{MasterID}ÿ{SiteID}ÿ{Season}*{Question}|{Answer}¥{Question}|{Answer}*/, callback ) {
        handleAlerts.BlockElement({
            MESSAGE: 'Saving Data.  Please Wait.',
            ELEMENT: $('body'),
            OPACITY: .7
        });
        $.ajax({
            type: "POST",
            data: "StringJSON=" + FORM_DATA,
            dataType: "text",
            url: DUrl + "WebServiceOsiris.asmx/Send_Answer",
//            cache: false,
            async: true,
            success: function (data) {

//                var xml = data,
//                    xmlDoc = $.parseXML(xml),
//                    $xml = $(xmlDoc),
//                    $title = $xml.find("string");

                if (callback != undefined) {
                    callback();
                    handleAlerts.UnblockElement();
                }
            },
            error: function (a, b, c) {
                handleAlerts.UnblockElement();
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    DeleteAnswerByFormId: function (FormId) {
        var Ret = false;
        $.ajax({
            type: "POST",
            data: "StringJSON=" + FormId,
            dataType: "text",
            url: DUrl + "WebServiceOsiris.asmx/Answer_Delete_By_FormId",

            cache: false,
            async: false,
            success: function (data) {

                var xml = data,
                    xmlDoc = $.parseXML(xml),
                    $xml = $(xmlDoc),
                    $title = $xml.find("string");

                if ($title.text() != '[]') {
                    Ret = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return Ret;
    },


    DeleteAnswers: function (id) {
        Functions.Connected();
        var Ret = false;
        $.ajax({
            type: "POST",
            data: "StringJSON=" + id,
            dataType: "text",
            url: DUrl + "WebServiceOsiris.asmx/Answer_Delete",

            cache: false,
            async: false,
            success: function (data) {

                var xml = data,
                    xmlDoc = $.parseXML(xml),
                    $xml = $(xmlDoc),
                    $title = $xml.find("string");

                if ($title.text() == '[]') {
                    Ret = false;

                } else {
                    Ret = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
                Ret = false;
            }
        });
        return Ret;
    },

    SendGroupAnswers: function (FORM_DATA) {
        Functions.Connected();
        var Ret = false;
        $.ajax({
            type: "POST",
            data: "StringJSON=" + FORM_DATA,
            dataType: "text",
            url: DUrl + "WebServiceOsiris.asmx/Send_Group_Answer",

            cache: false,
            async: false,
            success: function (data) {

                var xml = data,
                    xmlDoc = $.parseXML(xml),
                    $xml = $(xmlDoc),
                    $title = $xml.find("string");

                if ($title.text() == '[]') {
                    Ret = false;

                } else {
                    Ret = true;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
                Ret = false;
            }
        });
        return Ret;
    },

    isNumeric: function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    },

    isOdd: function (num) {
        return num % 2;
    },

    DropdownCascade: function (dropdown, cascade) {
        $("#7_form_control-" + cascade).find(".Option_" + dropdown.replace(/\ /g, '_')).prop('disabled', '');
        $("#7_form_control-" + cascade).find("option").not(".Option_" + dropdown.replace(/\ /g, '_')).prop('disabled', 'disabled');
        $('input:checkbox.Option_' + dropdown.replace(/\ /g, '_')).parent().show();
        $('input:checkbox[class^="Option_"],input:checkbox[class*=" Option_"]').filter(':not(.Option_' + dropdown.replace(/\ /g, '_') + ')').parent().hide();
        //$('select').select2({
        //    placeholder: "Select...",
        //    allowClear: true
        //});
    },

    handleFileDownload: function (field) {

    },

    handleFileRemove: function (field) {
        filesUpload[field] = null;
        $('#21_form_control-' + field + '_file').val('');
        SetData.PageFieldValue('get_' + field, '');
        SetData.PageFieldValue(field, '');
        $('#21_form_control-' + field + '_Change').hide();
        $('#21_form_control-' + field + '_Select').show();
        $('#21_form_control-' + field + '_Remove').hide();
        $('#21_form_control-' + field + '_Download').hide();
    },

    handleFileSelect: function (field) {
        var x = $('#21_form_control-' + field + '_file')[0];
        var txt = "";

        if ('files' in x) {
            if (x.files.length == 0) {
                txt = "";
                filesUpload[field] = null;
                SetData.PageFieldValue(field, '');
                $('#21_form_control-' + field + '_Change').hide();
                $('#21_form_control-' + field + '_Select').show();
                $('#21_form_control-' + field + '_Remove').hide();
                $('#21_form_control-' + field + '_Download').hide();
            } else {
                for (var i = 0; i < x.files.length; i++) {
                    var data = new FormData();

                    var file = x.files[i];
                    var filesize = ((file.size / 1024) / 1024).toFixed(4); // MB

                    if (filesize <= 10) {
                        var newName = Functions.AleatoryCode(15);
                        data.append(newName + file.name.slice(file.name.lastIndexOf('.')), file);
                        filesUpload[field] = data;
                        SetData.PageFieldValue(field, file.name + '|' + newName);
                        $('#21_form_control-' + field + '_Change').show();
                        $('#21_form_control-' + field + '_Select').hide();
                        $('#21_form_control-' + field + '_Remove').show();
                        $('#21_form_control-' + field + '_Download').hide();
                        if (i > 0) {
                            txt += file.name + ",";
                        } else {
                            txt += file.name;
                        }
                    } else {
                        txt += "Select file with less than 10Mb.";
                    }
                }
            }
        } else {
            txt += "Select one or more files.";
        }
        SetData.PageFieldValue('get_' + field, txt);
    },

    moveLiUp: function ($item) {
        $before = $item.prev();
        $item.insertBefore($before);
    },

    moveLiDown: function ($item) {
        $after = $item.next();
        $item.insertAfter($after);
    },

    objectToArray: function (object, single) {
        if (object == undefined) {
            return false;
        } else {
            var DATA_SET = [];

            for (var i = 0; i < object.length; i++) {
                var ARRAY;
                if (single) {
                    ARRAY = $.map(object[i], function (value, index) {
                        return [value];
                    })[0];
                } else {
                    ARRAY = $.map(object[i], function (value, index) {
                        return [value];
                    });
                }
                DATA_SET.push(ARRAY);
            }
            return DATA_SET;
        }
    },

    findObjectElement: function (arr, propName, propValue, retId, anyCol) {

        if (propName == 'Array') {
            for (var i = 0; i < arr.length; i++) {
                if (anyCol == -1) {
                    for (var j = 0; j < arr[i].length; j++) {
                        if (arr[i][j] == propValue) {
                            if (retId) {
                                return i;
                            } else {
                                return arr[i][j];
                            }
                        }
                    }
                } else {
                    if (arr[i][anyCol] == propValue) {
                        if (retId) {
                            return i;
                        } else {
                            return arr[i][j];
                        }
                    }
                }
            }
        } else {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i][propName] == propValue) {
                    if (retId) {
                        return i;
                    } else {
                        return arr[i];
                    }
                }
            }
        }
        return undefined;
    },

    getColorForPercentage: function (pct, green, yellow, red) {
        var percentColors = [
            {
                pct: green,
                color: {
                    r: 0xff,
                    g: 0x00,
                    b: 0
                }
            },
            {
                pct: yellow,
                color: {
                    r: 0xff,
                    g: 0xff,
                    b: 0
                }
            },
            {
                pct: red,
                color: {
                    r: 0x00,
                    g: 0xff,
                    b: 0
                }
            }
        ];

        pct = 1 - pct;

        for (var i = 1; i < percentColors.length - 1; i++) {
            if (pct < percentColors[i].pct) {
                break;
            }
        }
        var lower = percentColors[i - 1];
        var upper = percentColors[i];
        var range = upper.pct - lower.pct;
        var rangePct = (pct - lower.pct) / range;
        var pctLower = 1 - rangePct;
        var pctUpper = rangePct;
        var color = {
            r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
            g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
            b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
        };
        return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
        // or output as hex if preferred
    },

    lightenDarkenColor: function (col, amt) {

        var usePound = false;

        if (col[0] == "#") {
            col = col.slice(1);
            usePound = true;
        }

        var num = parseInt(col, 16);

        var r = (num >> 16) + amt;

        if (r > 255) r = 255;
        else if (r < 0) r = 0;

        var b = ((num >> 8) & 0x00FF) + amt;

        if (b > 255) b = 255;
        else if (b < 0) b = 0;

        var g = (num & 0x0000FF) + amt;

        if (g > 255) g = 255;
        else if (g < 0) g = 0;

        return (usePound ? "#" : "") + String("000000" + (g | (b << 8) | (r << 16)).toString(16)).slice(-6);

    },

    dropdownCascadeAfterCode: function () {
        var codes = afterCode.split(',');
        for (var i = 0; i < codes.length; i++) {
            $('#' + codes[i].split('|')[0]).select2('val', codes[i].split('|')[1]);
        }
        afterCode = "";
    },

    maxNumberOnArray: function (array, col, single) {
        var maxN = 0;
        if (single) {
            for (var ar = 0; ar < array.length; ar++) {
                if (maxN < parseFloat(array[ar])) {
                    maxN = parseFloat(array[ar]);
                }
            }
        } else {
            for (var ar = 0; ar < array.length; ar++) {
                if (maxN < array[ar][col]) {
                    maxN = array[ar][col];
                }
            }
        }
        return maxN;
    },

    sortByColumn: function (a, colIndex) {

        a.sort(sortFunction);

        function sortFunction(a, b) {
            if (a[colIndex] === b[colIndex]) {
                return 0;
            } else {
                return (a[colIndex] < b[colIndex]) ? -1 : 1;
            }
        }

        return a;
    },

    copyToClipboard: function (elem) {
        // create hidden text element, if it doesn't already exist
        var targetId = "_hiddenCopyText_";
        var isInput = false; //elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
        var origSelectionStart, origSelectionEnd;
        if (isInput) {
            // can just use the original source element for the selection and copy
            target = elem;
            origSelectionStart = elem.selectionStart;
            origSelectionEnd = elem.selectionEnd;
        } else {
            // must use a temporary form element for the selection and copy
            target = document.getElementById(targetId);
            if (!target) {
                var target = document.createElement("textarea");
                target.style.position = "absolute";
                target.style.left = "-9999px";
                target.style.top = "0";
                target.id = targetId;
                document.body.appendChild(target);
            }
            target.textContent = "'" + $(elem).val().replace(/\r?\n|\r/g, '').trim().replace(/  /g, '') + "'";
        }
        // select the content
        var currentFocus = document.activeElement;
        target.focus();
        target.setSelectionRange(0, target.value.length);

        // copy the selection
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch (e) {
            succeed = false;
        }
        // restore original focus
        if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
        }

        if (isInput) {
            // restore prior selection
            elem.setSelectionRange(origSelectionStart, origSelectionEnd);
        } else {
            // clear temporary content
            target.textContent = "";
        }
        return succeed;
    },

    copyToClipboardMsg: function (elem, msgElem) {
        var succeed = copyToClipboard(elem);
        var msg;
        if (!succeed) {
            msg = "Copy not supported or blocked.  Press Ctrl+c to copy."
        } else {
            msg = "Text copied to the clipboard."
        }
        if (typeof msgElem === "string") {
            msgElem = document.getElementById(msgElem);
        }
        msgElem.innerHTML = msg;
        setTimeout(function () {
            msgElem.innerHTML = "";
        }, 2000);
    },

    verifyAccessLevel: function (accessLevel) {

        if (GetData.localStorage('AccessLevel').split(',').indexOf(accessLevel) == -1) {
            return false;
        } else {
            return true;
        }
    },

    viewGeoLocation: function (position) {
        window.open('https://maps.apple.com/?q=' + position,
            '_blank' // <- This is what makes it open in a new window.
        );
    },

    select2UserList: function (all, placeHolder) {
        var userList = [];

        var UserJSON = GetData.SingleSqlValue("UserId, Name", "OS_User", "Active = 1 " + (all == true ? "" : " and Classification like '(PERCENT)" + GetData.localStorage('Classification') + "(PERCENT)'"), true);
        Functions.sortArray(UserJSON, 'Name');

        if (typeof UserJSON != "undefined") {
            for (var i = 0; i < UserJSON.length; i++) {
                userList.push({
                    id: UserJSON[i].Name,
                    text: UserJSON[i].Name
                });
            }
        }

        return {
            allowClear: true,
            initSelection: function (element, callback) {
                var selection = userList.find(function (metric) {
                    return metric.id === element.val();
                });
                callback(selection);
            },
            query: function (options) {
                var pageSize = 100;
                var startIndex = (options.page - 1) * pageSize;
                var filteredData = userList;

                if (options.term && options.term.length > 0) {
                    if (!options.context) {
                        var term = options.term.toLowerCase();
                        options.context = userList.filter(function (metric) {
                            return (metric.text.toLowerCase().indexOf(term) !== -1);
                        });
                    }
                    filteredData = options.context;
                }

                options.callback({
                    context: filteredData,
                    results: filteredData.slice(startIndex, startIndex + pageSize),
                    more: (startIndex + pageSize) < filteredData.length
                });
            },
            placeholder: (placeHolder == undefined ? "Please Select" : placeHolder)
        }
    },

    popupMainDueDateChanged: function (ele, id) {
        Functions.popupUpdateChanges(id, 'Duedate', ($(ele).val().trim() == '' ? '' : $(ele).val().trim()));
    },

    popupMainStatusChanged: function (ele, id) {
        Functions.popupUpdateChanges(id, 'Status', $(ele).val());
    },

    popupSaveChanges: function (currentEle) {
        var NEW_VALUE;
        var ROW_ID = $('.tdVal').parent().parent().attr('data-rowid');
        var COL_NAME = $('.tdVal[data-fieldid]').attr('data-fieldid');
        if ($('.tdVal.select2-container').length > 0) {
            $('.select2-drop').hide();
            if ($('.tdVal').select2('val').trim() == '') {
                NEW_VALUE = '';
            } else {
                NEW_VALUE = Functions.indexOfObject(allUserJSON, 'Name', Functions.ReplaceChar($('.tdVal').select2('val').trim(), '\'"', '\''), 'id_User');
            }
            $(currentEle).html(Functions.ReplaceChar($('.tdVal').select2('val').trim(), '\'"', '\''));
        } else {
            if ($('.tdVal').val().trim() == '') {
                NEW_VALUE = '';
            } else {
                if (COL_NAME == 'Duedate') {
                    NEW_VALUE = DateFunctions.FormatDate(new Date(new Date(Functions.ReplaceChar($(".tdVal").val().trim(), '\'"', '\'')).getTime() + new Date(Functions.ReplaceChar($(".tdVal").val().trim(), '\'"', '\'')).getTimezoneOffset() * 60000), 'MM/dd/yyyy');
                } else {
                    NEW_VALUE = Functions.ReplaceChar($(".tdVal").val().trim(), '\'"', '\'');
                }
            }
            $(currentEle).html(NEW_VALUE);
        }

        Functions.popupUpdateChanges(ROW_ID, COL_NAME, NEW_VALUE);
    },

    popupUpdateChanges: function (id, column, text) {
        var previousValue = GetData.SingleSqlValue(column, 'OS_TaskItems', 'id_TaskItem = ' + id);
        var toText = text;
        if (column == 'Assign') {
            previousValue = Functions.indexOfObject(allUserJSON, 'id_User', previousValue, 'Name');
            toText = Functions.indexOfObject(allUserJSON, 'id_User', toText, 'Name');
            
            Functions.SendEmail('Osiris Sub Inspection Follow Up', GetData.localStorage('UserId') + '@monsanto.com', GetData.localStorage('EmpName'), GetData.SingleSqlValue('UserId', 'OS_User', 'id_User = ' + Functions.indexOfObject(allUserJSON, 'Name', Functions.ReplaceChar(toText.trim(), '\'"', '\''), 'id_User')) + '@monsanto.com', '<div style="background-color: #364150;color:white;"><span style="font-size: 100px; color: #d4ff47; font-family: serif; text-shadow: black 3px 3px;">OSIRIS</span><span style="font-family:Arial Rounded MT Bold;font-size: 50px; color:red; text-shadow: black 3px 3px;font-style: italic;">Web 2.0</span>(br/)</div>(br/)' + (GetData.SingleSqlValue('MainTask', 'OS_TaskItems', 'id_TaskItem = ' + id) > 0 ? '<p style="text-size: 14px">(b)Main Inspection Follow Up: ' + GetData.SingleSqlValue('Title', 'OS_TaskItems', 'id_TaskItem = ' + GetData.SingleSqlValue('MainTask', 'OS_TaskItems', 'id_TaskItem = ' + id)) + '(/b)</p>' : '') + '(b)Action Log:(/b) ' + GetData.SingleSqlValue('Title', 'OS_TaskItems', 'id_TaskItem = ' + id) + '(br/) (br/)' + "<div style='padding-bottom:10px'><p> This Action Log is now assign to you.  Please log in into Osiris to kept track or follow up this item." + "</p></div><br><hr>");
        }

        Functions.popupSubmitData(id, 'Change in field', (previousValue == '' || previousValue == ' ' || previousValue == -1 ? '(empty)' : previousValue) + ' changed to ' + toText + ' in the ' + column + ' column by ' + Functions.indexOfObject(allUserJSON, 'id_User', GetData.localStorage('ID'), 'Name') + '.');

        $.ajax({
            type: "POST",
            data: "StringJSON=OS_TaskItemsß" + id + "ß" + column + "ß" + text,
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Update_Data",

            cache: false,
            success: function (data) {
                if($.notific8 == undefined) {
                    handleAlerts.Simple('Saved successfully.');
                } else {
                    $.notific8('Saved successfully.', {
                        life: 5000,
                        theme: 'lime',
                        horizontalEdge: 'bottom',
                        zindex: 1000000000000
                    });
                }
                Functions.popupUpdatesTable();
                if (FROM == 'cal' && typeof initCAL != "undefined") {
                    initCAL();
                    Corrective_Actions_Log_Selected();
                } else if (FROM == 'task' && typeof initTask != "undefined") {
                    initTask();
                    Task_Selected();
                }
            },
            error: function (a, b, c) {
                debugger;
                if($.notific8 == undefined) {
                    handleAlerts.Simple('There were some errors on saving.');
                } else {
                    $.notific8('There were some errors on saving.', {
                        life: 5000,
                        theme: 'ruby',
                        horizontalEdge: 'bottom',
                        zindex: 1000000000000
                    });
                }
            }
        });
    },

    popupComments: function () {

        bootbox.dialog({
            message: "<div class='row'><div class='col-md-12'><textarea id='CalComment' rows='10' style='width:100%'></textarea></div></div>",
            title: 'Comments',
            buttons: {
                danger: {
                    label: "Cancel",
                    className: "red pull-right",
                    callback: function () {}
                },
                main: {
                    label: "Ok",
                    className: "blue pull-right",
                    callback: function () {
                        Functions.popupSubmitData(calID, 'Comments', $('#CalComment').val());
                    }
                }
            },
            onEscape: {},
            backdrop: "true",
            size: "large"
        });
    },

    popupSubmitData: function (id, title, text) {
        if (text != "" && text != " ") {
            Functions.SendTaskData(id, DateFunctions.FormatDate(null, 'MM/dd/yyyy hh:mm T'), title, text);
        }
        Functions.popupUpdatesTable();
    },

    popupSubtask: function () {

        handleAlerts.CustomDialog({
            destroy: true,
            message: "<div style='padding-bottom:10px'><p>Task<span style='color: #e02222;'>*</span></p><input type='text' name='calTask' value='' style='height:24px;width:100%'></div><div style='padding-bottom:10px'><p>Assign To</p><input name='calAssignTo' style='color: black;width:100%;' data-fieldId='Assign'/></div><div style='padding-bottom:10px'><p>Due Date</p><input type='date' name='taskduedate' style='height:24px;width:100%'></div><div><p style='font-size:14px'>Comments<p><textarea name='calComments' rows='5' style='width:100%'></textarea></div>",
            title: 'New Subtask',
            onEsc: {},
            buttons: {
                danger: {
                    label: "Cancel",
                    className: "red pull-right",
                    callback: function () {}
                },
                main: {
                    label: "Ok",
                    className: "blue pull-right",
                    callback: function () {
                        Functions.popupSubmitTask();
                    }
                }
            },
            modalClose: "true",
            size: "large",
            init: function () {
                $("[name='calAssignTo']").select2(Functions.select2UserList(false, "Select an Employee"));
                $("[name='taskduedate']").datepicker({
                    //rtl: Metronic.isRTL(),
                    //orientation: "right",
                    autoclose: true,
                    forceParse: false,
                    todayHighlight: true,
                    assumeNearbyYear: true,
                    todayBtn: true,
                    clearBtn: true
                });
            }
        });
    },

    popupSubmitTask: function () {
        var cal2ID = Functions.SendTaskItem($('[name="calTask"]').val(), 'New', ($('[name="taskduedate"]').val() == '' ? '' : DateFunctions.FormatDate(new Date(new Date(Functions.ReplaceChar($('[name="taskduedate"]').val(), '\'"', '\'')).getTime() + new Date(Functions.ReplaceChar($('[name="taskduedate"]').val(), '\'"', '\'')).getTimezoneOffset() * 60000), 'MM/dd/yyyy')), Functions.indexOfObject(allUserJSON, 'Name', Functions.ReplaceChar($('[name="calAssignTo"]').select2('val').trim(), '\'"', '\''), 'id_User'), 'SubCal', calID);

        Functions.popupSubmitData(cal2ID, 'New', 'Sub CAL created from: ' + GetData.SingleSqlValue('Title', 'OS_TaskItems', 'id_TaskItem = ' + calID));
        Functions.popupSubmitData(cal2ID, 'Comments', $('[name="calComments"]').val());
        
        Functions.SendEmail('Osiris Sub Inspection Follow Up', GetData.localStorage('UserId') + '@monsanto.com', GetData.localStorage('EmpName'), GetData.SingleSqlValue('UserId', 'OS_User', 'id_User = ' + Functions.indexOfObject(allUserJSON, 'Name', Functions.ReplaceChar($('[name="calAssignTo"]').select2('val').trim(), '\'"', '\''), 'id_User')) + '@monsanto.com', '<div style="background-color: #364150;color:white;"><span style="font-size: 100px; color: #d4ff47; font-family: serif; text-shadow: black 3px 3px;">OSIRIS</span><span style="font-family:Arial Rounded MT Bold;font-size: 50px; color:red; text-shadow: black 3px 3px;font-style: italic;">Web 2.0</span>(br/)</div>(br/)(b)Action Log: ' + $('[name="calTask"]').val() + '(/b) (br/) (br/)' + "<div style='padding-bottom:10px'><p> This Action Log was created and you was assing to it.  Please log in into Osiris to kept track or follow up this item." + "</p></div><p>Comments:</p><p>" + $('[name="calComments"]').val() + "</p><br><hr>");
    },

    popupUpdatesTable: function () {

        var tabReturn = "<div class='row,col-md-12' style='background-color: #eee;border: 3px solid;height: 250px;'><table id='subTask'><thead><tr><th>Task</th><th>Assigned To</th><th>Due Date</th><th>Status</th></tr></thead><tbody>";

        getTaskInfo = GetData.MultiSqlValue("OS_TaskItems", "MainTask = '" + calID + "'");
        subTaskDataTableInfo = "";
        for (var i = 0; i < getTaskInfo.length; i++) {
            subTaskDataTableInfo += "<tr data-rowid='" + getTaskInfo[i].id_TaskItem + "'><td class='hoverTd' style='cursor:pointer;' onclick='mainTask = " + calID + ";subTask = true;handleAlerts.HideAlerts();setTimeout(function(){Functions.popupTodo(" + getTaskInfo[i].id_TaskItem + ", \"" + FROM + "\");}, 500);'>" + getTaskInfo[i].Title + "</td><td style='cursor:pointer;' title='" + Functions.LanguageSelect("Haga un doble click para asignar o reasignar esta tarea.", "Please double click to assign or reassign this task.") + "'>" + (Functions.indexOfObject(allUserJSON, 'id_User', getTaskInfo[i].Assign, 'Name') == -1 ? '' : Functions.indexOfObject(allUserJSON, 'id_User', getTaskInfo[i].Assign, 'Name')) + "</td><td style='cursor:pointer;' title='" + Functions.LanguageSelect("Haga un doble click para añadir una fecha limite a esta tarea.", "Please double click to add a due date to this task.") + "'>" + getTaskInfo[i].Duedate + "</td><td>" + getTaskInfo[i].Status + "</td></tr>";
        }

        tabReturn += subTaskDataTableInfo;
        tabReturn += "</tbody></table></div><div class='row,col-md-12' style='background-color: #eee;border: 3px solid;margin-top: 30px;height: 250px;'><table id='TaskData' style='width:100%'><thead><tr><th>Datetime</th><th>Action</th><th>Description</th></thead><tbody>";

        getTaskData = GetData.MultiSqlValue("OS_TaskData", "Cal_Id = '" + calID + "'"); //comments
        TaskDataTableInfo = "";
        for (var i = 0; i < getTaskData.length; i++) {
            var DataDate = DateFunctions.FormatDate(Functions.ToJavaScriptDate(getTaskData[i].DateTime, true), "MM/dd/yy hh:mm T");
            TaskDataTableInfo += "<tr><td>" + DataDate + "</td><td>" + getTaskData[i].Action + "</td><td>" + getTaskData[i].Description + "</td></tr>";
        }

        tabReturn += TaskDataTableInfo;

        tabReturn += "</tbody></table></div></div>";

        $('#TableArea').html(tabReturn);

        $('#subTask').DataTable({
            scrollY: "115",
            ScrollCollapse: true,
            destroy: true,
            searching: false,
            pageLength: -1,
            columnDefs: [
                {
                    width: 200,
                    targets: 1
                },
                {
                    width: 100,
                    targets: 2
                },
                {
                    width: 90,
                    targets: 3
                }
            ]
        });
        $('#TaskData').DataTable({
            scrollY: "115",
            ScrollCollapse: true,
            destroy: true,
            searching: false,
            pageLength: -1,
            columnDefs: [
                {
                    width: 100,
                    targets: 0
                },
                {
                    width: 130,
                    targets: 1
                }
            ]
        });
        $('.dataTables_length').hide();
        if (subTask) {
            subTask = false;
        }
        setTimeout(function () {
            $('#subTask').DataTable().columns.adjust().draw();
            $('#TaskData').DataTable().columns.adjust().draw();

            $('#subTask tr.odd,#subTask tr.even').hover(function () {
                $(this).addClass('tdHover');
            }, function () {
                $(this).removeClass('tdHover');
            });
        }, 500);

        $("#subTask tbody td").off('dblclick').on('dblclick', function (e) {
            //if (!($(this).children(0).hasClass("tdVal"))) {
            if (($("#subTask thead tr th").eq($(this)[0].cellIndex).children().html() == 'Task') || ($("#subTask thead tr th").eq($(this)[0].cellIndex).children().html() == 'Status')) {
                e.stopPropagation(); //<-------stop the bubbling of the event here
            } else if ($("#subTask thead tr th").eq($(this)[0].cellIndex).children().html() == 'Assigned To') {
                e.stopPropagation(); //<-------stop the bubbling of the event here
                currentEle = $(this);
                value = $(this).html();
                Functions.popupUpdateValDropdown(currentEle, value);
            } else {
                e.stopPropagation(); //<-------stop the bubbling of the event here
                currentEle = $(this);
                value = $(this).html();
                Functions.popupUpdateVal(currentEle, value);
            }
        });
        $('[name="maintaskduedate"]').off('changeDate').on('changeDate', function (e) {
            if (!dateInit) {
                Functions.popupMainDueDateChanged(this, calID);
            }
        });
    },

    popupTodo: function (idCal, from) {
        FROM = from;
        calID = idCal;
        mainCalData = GetData.MultiSqlValue("OS_TaskItems", "id_TaskItem = '" + calID + "'");

        //Fill Main Task actions
        if (mainCalData[0].Duedate != " ") {
            var MainDueDate = "value='" + mainCalData[0].Duedate + "'";

        } else {
            var MainDueDate = " ";
        }

        var mainTaskStatus = mainCalData[0].Status;
        //var mainTaskStatus = "Completed";

        var selectedCompleted = "";
        var selectedInProgress = "";
        var selectedNew = "";

        switch (mainTaskStatus) {
            case "Completed":
                var selectedCompleted = "selected";
                break;
            case "In Progress":
                var selectedInProgress = "selected";
                break;
            default:
                selectedNew = "selected";
        }

        var messageBox = "<div>" +
            "<div class='row' style='padding-bottom:15px;'>" +
            "<div class='col-md-1' style='padding-bottom:8px;'><a class='btn btn-default " + (subTask == true ? "" : "hidden") + "' href='#' onclick='mainTask = 0;handleAlerts.HideAlerts();setTimeout(function(){Functions.popupTodo(" + mainTask + ");}, 500);' role='button' id='backBtn'>Back</a></div>" +
            "<div  class='col-md-3' style='padding-bottom:8px;'><div class='mainTaskTitle'>Status</div><div class='mainTaskField'><select id='calStatus' name='calStatus' class='selectpicker' style='height:34px;width:100%' onchange='Functions.popupMainStatusChanged(this, " + calID + ");'><option value='New'" + selectedNew + ">New</option><option  value='In Progress'" + selectedInProgress + ">In Progress</option><option value='Completed'" + selectedCompleted + ">Completed</option></select></div></div>" +
            "<div class='col-md-3 dDate' style='padding-bottom:8px;'><div class='mainTaskTitle'>Due Date</div><div class='mainTaskField'><input type='text' name='maintaskduedate' class='form-control form-field date-picker' " + MainDueDate + "/></div></div>" +
            //"<div class='col-md-3' style='padding-bottom:8px;'><div class='mainTaskTitle'>Due Date</div><div class='mainTaskField'><input type='date' name='maintaskduedate' style='width:100%; height: 34px;' " + MainDueDate + " onblur='Functions.popupMainDueDateChanged(this, " + calID + ");'/></div></div>" +
            "<div class='col-md-3' style='padding-bottom:8px;'><a class='btn btn-default' style='width:100%' href='#' role='button' onclick='Functions.popupSubtask();'>Create Subtask</a></div>" +
            "<div class='col-md-2' style='padding-bottom:8px;'><a class='btn btn-default' href='#' style='width:100%' onclick='Functions.popupComments();' role='button'>Comments</a></div></div>" +
            "<div id='TableArea'>";
        messageBox += "</div></div>";

        handleAlerts.CustomDialog({
            destroy: true,
            message: messageBox,
            title: mainCalData[0].Title,
            onEsc: "true",
            modalClose: "true",
            //position: "center",
            size: "large",
            init: function () {
                Functions.popupUpdatesTable();
                dateInit = true;
                $('.date-picker').datepicker({
                    container: $('.dDate'),
                    rtl: Metronic.isRTL(),
                    orientation: "right",
                    autoclose: true,
                    forceParse: false,
                    todayHighlight: true,
                    assumeNearbyYear: true,
                    todayBtn: true,
                    clearBtn: true
                });
                dateInit = false;
                if (FROM == 'task') {
                    $('.modal-header').append('<div id="RemoveTask" style="position: absolute;top: 13px;right: 100px;cursor: pointer;height: 30px;width: 100px;background-color: gray;text-align: center;" onclick="Functions.popupRemoveTask();"><span style="font-size: 16px;color: white;"> Delete </span><i class="fa fa-trash" style="color: white;font-size: 15px;line-height: 30px;"></i></div>');
                }
            }
        });

    },

    popupRemoveTask: function () {
        handleAlerts.CustomDialog({
            destroy: true,
            title: "Delete Task",
            onEsc: "true",
            modalClose: "true",
            //position: "center",
            message: Functions.LanguageSelect('Esta seguro de eliminar esta tarea?', 'Are you sure you want to delete this task?'),
            buttons: {
                success: {
                    label: "Ok",
                    className: "blue pull-left",
                    callback: function () {
                        var re = Functions.DeleteTaskItem(calID);
                        if (re) {
                            handleAlerts.HideAlerts();
                            initTask();
                            Task_Selected();
                        }
                    }
                },
                danger: {
                    label: "Cancel",
                    className: "red pull-right",
                    callback: function () {}
                }
            }
        });
    },

    popupUpdateVal: function (currentEle3, value) {
        //$(currentEle3).html('<input type='text' name='maintaskduedate' class='form-control form-field date-picker' " + MainDueDate + "/>');
        //$(currentEle3).html("<input class='tdVal' type='date' name='updateTaskDueDate' data-fieldId='Duedate' style='width:100%;' value='" + DateFunctions.FormatDate(value, "yyyy-MM-dd") + "'>");
        $(currentEle3).html("<input class='tdVal' type='text' name='updateTaskDueDate' data-fieldId='Duedate' class='form-control form-field date-picker' style='width:100%;' value='" + value + "'>");
        $(".tdVal").datepicker({
            //container: $('.dDate'),
            //rtl: Metronic.isRTL(),
            //orientation: "right",
            autoclose: true,
            forceParse: false,
            todayHighlight: true,
            assumeNearbyYear: true,
            todayBtn: true,
            clearBtn: true
        });
        $(".tdVal").focus();
        $(".tdVal").keyup(function (event) {
            if (event.keyCode == 13) {
                Functions.popupSaveChanges(currentEle3);
            }
        });
    },

    popupUpdateValDropdown: function (currentEle2, value) {
        $(currentEle2).html('<input class="tdVal" style="color: black;width:100%;" data-fieldId="Assign" value="' + value + '"/>');
        $(".tdVal").select2(Functions.select2UserList(false, "Select an Employee"));
        setTimeout(function () {
            $(".tdVal").on("change", function (e) {
                Functions.popupSaveChanges(currentEle2);
            });
        }, 500);
    },

    createTableFromArray: function (arr, getOpt) {

        var options = {
            retRowNum: {
                def: false,
                help: 'true, false'
            },
            textAlign: {
                def: 'left',
                help: 'left, center, right'
            },
            style: {
                def: '',
                help: 'Enter style for the table in CSS style'
            }
        }

        //if (typeof getOpt == "undefined") return options;

        options = Functions.compareObjectArray(options, getOpt);


        var html = '<table style="' + options.textAlign + '; ' + options.style + '">';
        html += '<tr>';
        if (options.retRowNum) {
            html += '<th>#</th>';
        }
        for (var j in arr[0]) {
            html += '<th>' + j + '</th>';
        }
        html += '</tr>';
        for (var i = 0; i < arr.length; i++) {
            html += '<tr>';
            if (options.retRowNum) {
                html += '<td>' + (i + 1) + '</td>';
            }
            for (var j in arr[i]) {
                html += '<td>' + arr[i][j] + '</td>';
            }
        }
        html += '</table>';

        return html;
    }
}

var SetData = {

    PageFieldValueDataPull: function (fieldId, value) {
        //8_checkbox_Ejemplo8_AL
        //Ejemplo1

        var FieldId;
        if ($('[data-Pull*=' + fieldId + ']').length > 0) {
            if ($('[data-Pull*=' + fieldId + ']').length > 1) {
                if ($('[data-Pull=' + fieldId + ']').val() == '') {
                    if ($('[data-Pull=' + fieldId + ']').attr('data-Pull').substr(0, 1) == '@') {
                        value = $('[data-Pull=' + fieldId + ']').attr('data-Pull').substr(1, $('[data-Pull=' + fieldId + ']').attr('data-Pull').indexOf('_') - 1).split('-')[value];
                    }
                    FieldId = $('[data-Pull=' + fieldId + ']');
                } else {
                    FieldId = "Bad";
                }
            } else {
                if ($('[data-Pull*=' + fieldId + ']').val() == '') {
                    if ($('[data-Pull*=' + fieldId + ']').attr('data-Pull').substr(0, 1) == '@') {
                        value = $('[data-Pull*=' + fieldId + ']').attr('data-Pull').substr(1, $('[data-Pull*=' + fieldId + ']').attr('data-Pull').indexOf('_') - 1).split('-')[value];
                    }
                    FieldId = $('[data-Pull*=' + fieldId + ']');
                } else {
                    FieldId = "Bad";
                }
            }
        } else if ($('[id*=form_control-' + fieldId + ']').length > 0) {
            FieldId = $('[id$=form_control-' + fieldId + ']').last();
        } else if ($('[id*=checkbox-' + fieldId + ']').length > 0) {
            FieldId = $('[id*=checkbox-' + fieldId + ']');
        } else {
            FieldId = "Bad";
        }
        if (FieldId != "Bad") {
            if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) <= 6 || FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 10 || FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 22) {
                FieldId.val(value);
                if ($('#19_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').length > 0 && value.length > 100) {
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1)).val(value.replace(/[ ]/g, '+'));
                    $('#19_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').attr('placeholder', 'Signature Captured');
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_img').attr('src', 'data:image/png;base64,' + $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1)).val());
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_x').show();
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_img').css('height', '100px');
                } else if ($('#23_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').length > 0 && value.length > 5) {
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1)).val(value);
                    $('#23_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').attr('placeholder', 'Coordinates Taken');
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_x').show();
                    $('#23_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_viewBtn').show();
                } else if ($('#20_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').length > 0 && value.length > 100) {
                    var FileData = value.split('|');
                    $('#1_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1)).val(value.replace(/[ ]/g, '+'));
                    $('#20_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_get').attr('placeholder', FileData[0]);
                    $('#21_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_success').hide();
                    $('#21_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_primary').show();
                    $('#21_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_warning').show();
                    $('#21_form_control-' + FieldId.attr('id').substr(FieldId.attr('id').indexOf('-') + 1) + '_danger').show();

                }

            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 'ms-16') {
                $('#' + FieldId.attr('id').substr(3, FieldId.attr('id').length)).multiSelect('select',value.split(','));
            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 's2id' || FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 7) {
                if (FieldId.attr('id').indexOf('_New') + 4 == FieldId.attr('id').length) {
                    FieldId = $("#" + FieldId.attr('id').substr(0, FieldId.attr('id').length - 4));
                }
                if ($(FieldId).attr('data-formula').substr(0, 1) == '~') {
                    afterCode += FieldId.attr('id') + '|' + value + ',';
                } else {
                    $(FieldId).val(value);
                    FieldId.select2("val", value);
                }
            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 8) {
                if (value == 1) {
                    FieldId.attr('checked', 'checked');
                } else {
                    FieldId.removeAttr('checked');
                }
            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 9 || FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 15) {
                if (value == 0) {
                    FieldId.bootstrapSwitch('state', false, true);
                } else {
                    FieldId.bootstrapSwitch('state', true, true);
                }
            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 11 || FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 14) {
                FieldId.html(value);
            } else if (FieldId.attr('id').substr(0, FieldId.attr('id').indexOf('_')) == 18) {
                $('#' + FieldId.attr('id') + ' :input[value="' + value + '"]').parent().addClass('active');
            }
        }
    },

    PageFieldValue: function (fieldId, value) {
        //8_checkbox_Ejemplo8_AL
        //Ejemplo1
        try {
            if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Input') {
                if ($('[name=' + fieldId + '][data-IType]').attr('id').substr(0, $('[name=' + fieldId + '][data-IType]').attr('id').indexOf('_')) == 2) {
                    value = DateFunctions.FormatDate(value, 'MM/dd/yyyy');
                } else if ($('[name=' + fieldId + '][data-IType]').attr('id').substr(0, $('[name=' + fieldId + '][data-IType]').attr('id').indexOf('_')) == 3) {
                    value = DateFunctions.FormatDate(value, 'MM/dd/yyyy');
                } else if ($('[name=' + fieldId + '][data-IType]').attr('id').substr(0, $('[name=' + fieldId + '][data-IType]').attr('id').indexOf('_')) == 4) {
                    value = DateFunctions.FormatDate(value, 'MMMM dd, yyyy - hh:mm T');
                } else if ($('[name=' + fieldId + '][data-IType]').attr('id').substr(0, $('[name=' + fieldId + '][data-IType]').attr('id').indexOf('_')) == 5) {
                    value = DateFunctions.FormatTime(value, 'hh:mm T');
                }
                $('[name=' + fieldId + '][data-IType=Input]').val(value);
            } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Select') {
                if ($('[name=' + fieldId + '][data-IType] option[value=\'' + value + '\']').length > 0) {
                    $('[name=' + fieldId + '][data-IType=Select]').val(value);
                    $('[name=' + fieldId + '][data-IType=Select]').select2("val", value);
                } else {
                    var option = new Option(value, value);
                    option.selected = true;

                    $('[name=' + fieldId + '][data-IType=Select]').append(option);
                    $('[name=' + fieldId + '][data-IType=Select]').trigger("change");
                    $('[name=' + fieldId + '][data-IType=Select]').val(value);
                }
            } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Check') {
                if (value == 1 || value == "true") {
                    $('[name=' + fieldId + '][data-IType=Check]').attr('checked', 'checked');
                } else {
                    $('[name=' + fieldId + '][data-IType=Check]').removeAttr('checked');
                }
            } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Switch') {
                var readOnly = false;
                if ($('[name=' + fieldId + '][data-IType=Switch]').attr('readonly') != undefined) {
                    $('[name=' + fieldId + '][data-IType=Switch]').bootstrapSwitch('readonly', false); // Remove disabled.
                    readOnly = true;
                }
                if (value == 0) {
                    $('[name=' + fieldId + '][data-IType=Switch]').prop('checked', false);
                    $('[name=' + fieldId + '][data-IType=Switch]').bootstrapSwitch('state', false);
                } else {
                    $('[name=' + fieldId + '][data-IType=Switch]').prop('checked', true);
                    $('[name=' + fieldId + '][data-IType=Switch]').bootstrapSwitch('state', true);
                }
                if (readOnly) {
                    $('[name=' + fieldId + '][data-IType=Switch]').bootstrapSwitch('readonly', true); // Apply disabled.
                }
            } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'HTML') {
                $('[name=' + fieldId + '][data-IType=HTML]').html(value);
            } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'MultiSelect') {
                debugger;
            }
        } catch (e) {}
    },

    SyncDates: function (table) {
        var Dates = JSON.parse(GetData.localStorage("Dates"));
        Dates[0][table] = DateFunctions.FormatDate(Date(), 'MM/dd/yyyy');
        SetData.localStorage('Dates', JSON.stringify(Dates));
    },

    StartSyncDates: function () {

        if (Object.keys((GetData.localStorage("Dates") == undefined ? {} : JSON.parse(GetData.localStorage("Dates"))[0])).length != 10) {
            SetData.localStorage('Dates', '[{"FTS_Changes": "' + DateFunctions.FormatDate(Date(), 'MM/dd/yyyy') + '", "Alerts": "1/1/1900", "Sync": "1/1/1900", "Sidebar": "1/1/1900", "Languages": "1/1/1900", "Catalog_Category": "1/1/1900", "Catalog": "1/1/1900", "Events": "1/1/1900", "MasterTable": "1/1/1900", "Question": "1/1/1900"}]');
        }

    },

    ExportExcel: function (JSONData, ShowLabel, ReportTitle, ShowTitle) {
        //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

        var CSV = '';

        //Set Report title in first row or line
        if (ShowTitle != undefined && ShowTitle != false) {
            CSV += ReportTitle + '\r\n\n';
        }

        //This condition will generate the Label/Header
        if (ShowLabel) {
            var row = "";

            //This loop will extract the label from 1st index of on array
            for (var index in arrData[0]) {

                //Now convert each value to string and comma-seprated
                row += index + ',';
            }

            row = row.slice(0, -1);

            //append Label row with line break
            CSV += row + '\r\n';
        }

        //1st loop is to extract each row
        for (var i = 0; i < arrData.length; i++) {
            var row = "";

            //2nd loop will extract each column and convert it in string comma-seprated
            for (var index in arrData[i]) {
                row += '"' + arrData[i][index] + '",';
            }

            row.slice(0, row.length - 1);

            //add a line break after each row
            CSV += row + '\r\n';
        }

        if (CSV == '') {
            alert("Invalid data");
            return;
        }

        //Generate a file name
        var fileName = "";
        //this will remove the blank-spaces from the title and replace it with an underscore
        if (ReportTitle != undefined) {
            fileName += ReportTitle.replace(/ /g, "_");
        } else {
            fileName = "CSV_File";
        }

        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

        // Now the little tricky part.
        // you can use either>> window.open(uri);
        // but this will not work in some browsers
        // or you will not get the correct file extension    

        //this trick will generate a temp <a /> tag
        var link = document.createElement("a");
        link.href = uri;

        //set the visibility hidden so it will not effect on your web-layout
        link.style = "visibility:hidden";
        link.download = fileName + ".csv";

        //this part will append the anchor tag and remove it after automatic click
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    },

    localStorage: function (key, value) {
        if (!Functions.isLocalStorageNameSupported()) {
            handleAlerts.Simple("Can't store data locally.");
            throw new Error("Can't access localstorage.");
        } else {
            localStorage.setItem(key, value);
        }
    },
    
    insertSQL: function (table, columns, values) {
        var RET;
        $.ajax({
            type: "POST",
            data: "SQLString=Insert INTO " + table + " (" + columns + ") VALUES " + escape(values.replace(/\(%\)|%/g, "(PERCENT)") + " SELECT @@IDENTITY AS 'Identity';"),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != "[]") {
                    RET = title;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }

            }
        });
        return RET;
    },
    
    updateSQL: function (table, set, where) {
        var RET;
        $.ajax({
            type: "POST",
            data: "SQLString=Update " + table + " SET " + set + " WHERE " + escape(where.replace(/\(%\)|%/g, "(PERCENT)")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != "[]") {
                    RET = title;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }

            }
        });
        return RET;
    },
    
    deleteSQL: function (table, where) {
        var RET;
        $.ajax({
            type: "POST",
            data: "SQLString=Delete FROM " + table + " WHERE " + escape(where.replace(/\(%\)|%/g, "(PERCENT)")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != "[]") {
                    RET = title;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }

            }
        });
        return RET;
    },
    
    UrlParameter: function (sParam, value,refresh) {
        var hostName = location.host;
        var pathName = location.pathname;
        var urlParameters = location.search.substring(1).split('&').map(function (value) { return value.split('=');});
        
        if (GetData.UrlParameter(sParam) == undefined) {
            if (value == "{DELETE}") {
                window.history.replaceState({}, document.title, location.pathname + location.search);
            } else if (location.search == "") {
                window.history.replaceState({}, document.title, location.pathname + '?' + sParam + '=' + value);
            } else {
                window.history.replaceState({}, document.title, location.pathname + location.search + '&' + sParam + '=' + value);
            }
        } else {
            for (var i = 0; i < urlParameters.length; i++) {
                if (urlParameters[i][0] == sParam) {
                    if (value == "{DELETE}") {
                        urlParameters.splice(i,1);
                    } else {
                        urlParameters[i][1] = value;
                    }
                    break;
                }
            }
            urlParameters = urlParameters.map(function(a){return a[0] + '=' + a[1];}).join('&');
            window.history.replaceState({}, document.title, location.pathname + (urlParameters == "" ? "" : '?' + urlParameters));
        }
        if (refresh) {
            location.reload();
        }
    }   
}

var GetData = {

    PageFieldValue: function (fieldId) {
        if (fieldId != undefined) {
            if (fieldId == 'MasterIdSelect') {
                return $('#MasterIdSelect').val();
            } else {
                if (fieldId.substr(fieldId.length - 1) == "*" && fieldId.substr(0, 1) == '*') {
                    if ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Input' || $('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Select') { // 1,2,3,4,5,6,7,10
                        return $.trim($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').val());
                    } else if ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Check') { // 8
                        return ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').is(":checked") == true ? 1 : 0);
                    } else if ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Switch') { // 9,15
                        try {
                            return ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').bootstrapSwitch('state') == true ? 1 : 0);
                        } catch (err) {
                            return 0;
                        };
                    } else if ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'HTML') { // 11,12,14
                        return $.trim($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').text());
                    } else if ($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Radio') { //18
                        return $.trim($('[name*=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').find("label.active").find("input").attr("value"));
                    }
                } else if (fieldId.substr(0, 1) == '*') {
                    if ($('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'Input' || $('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'Select') { // 1,2,3,4,5,6,7,10
                        return $.trim($('[name$=' + fieldId.substr(1) + '][data-IType]').val());
                    } else if ($('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'Check') { // 8
                        return ($('[name$=' + fieldId.substr(1) + '][data-IType]').is(":checked") == true ? 1 : 0);
                    } else if ($('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'Switch') { // 9,15
                        try {
                            return ($('[name$=' + fieldId.substr(1) + '][data-IType]').bootstrapSwitch('state') == true ? 1 : 0);
                        } catch (err) {
                            return 0;
                        };
                    } else if ($('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'HTML') { // 11,12,14
                        return $.trim($('[name$=' + fieldId.substr(1) + '][data-IType]').text());
                    } else if ($('[name$=' + fieldId.substr(1) + '][data-IType]').attr('data-IType') == 'Radio') { //18
                        return $.trim($('[name$=' + fieldId.substr(1) + '][data-IType]').find("label.active").find("input").attr("value"));
                    }
                } else if (fieldId.substr(fieldId.length - 1) == '*') {
                    if ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Input' || $('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Select') { // 1,2,3,4,5,6,7,10
                        return $.trim($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').val());
                    } else if ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Check') { // 8
                        return ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').is(":checked") == true ? 1 : 0);
                    } else if ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Switch') { // 9,15
                        try {
                            return ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').bootstrapSwitch('state') == true ? 1 : 0);
                        } catch (err) {
                            return 0;
                        };
                    } else if ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'HTML') { // 11,12,14
                        return $.trim($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').text());
                    } else if ($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').attr('data-IType') == 'Radio') { //18
                        return $.trim($('[name^=' + fieldId.substr(0, fieldId.length - 1) + '][data-IType]').find("label.active").find("input").attr("value"));
                    }
                } else {
                    if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Input' || $('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Select') { // 1,2,3,4,5,6,7,10
                        return $.trim($('[name=' + fieldId + '][data-IType]').val());
                    } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Check') { // 8
                        return ($('[name=' + fieldId + '][data-IType]').is(":checked") == true ? 1 : 0);
                    } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Switch') { // 9,15
                        try {
                            return ($('[name=' + fieldId + '][data-IType]').bootstrapSwitch('state') == true ? 1 : 0);
                        } catch (err) {
                            return 0;
                        };
                    } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'HTML') { // 11,12,14
                        return $.trim($('[name=' + fieldId + '][data-IType]').text());
                    } else if ($('[name=' + fieldId + '][data-IType]').attr('data-IType') == 'Radio') { //18
                        return $.trim($('[name=' + fieldId + '][data-IType]').find("label.active").find("input").attr("value"));
                    }
                }
            }
        }
        return '';
    },

    PageFieldValueDataPull: function (fieldId) {
        if (fieldId == 'MasterIdSelect') {
            return $('#MasterIdSelect').val();
        } else {
            if ($('[data-pull=' + fieldId + '][data-IType]').attr('data-IType') == 'Input') { // 1,2,3,4,5,6,7,10
                return $.trim($('[data-pull=' + fieldId + '][data-IType]').not(".select2-container").val());
            } else if ($('[data-pull=' + fieldId + '][data-IType]').attr('data-IType') == 'Check') { // 8
                return ($('[data-pull=' + fieldId + '][data-IType]').is(":checked") == true ? 1 : 0);
            } else if ($('[data-pull=' + fieldId + '][data-IType]').attr('data-IType') == 'Switch') { // 9,15
                return ($('[data-pull=' + fieldId + '][data-IType]').bootstrapSwitch('state') == true ? 1 : 0);
            } else if ($('[data-pull=' + fieldId + '][data-IType]').attr('data-IType') == 'HTML') { // 11,12,14
                return $.trim($('[data-pull=' + fieldId + '][data-IType]').text());
            } else if ($('[data-pull=' + fieldId + '][data-IType]').attr('data-IType') == 'Radio') { //18
                return $.trim($('[data-pull=' + fieldId + '][data-IType]').find("label.active").find("input").attr("value"));
            }
        }
        return '';
    },

    SingleSqlValue: function (SQLsearchColumn, SQLtable, SQLwhere, SQLretAll, async, callback) {
        Functions.Connected();
        var RET;
        var async2 = false;
        
        if (async) {
            async2 = true;
        }
        $.ajax({
            type: "POST",
            data: "SQLString=SELECT DISTINCT " + escape(SQLsearchColumn) + " FROM " + escape(SQLtable) + " WHERE " + escape(SQLwhere.replace(/\(%\)|%/g, "(PERCENT)")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: async2,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != "[]") {
                    if (SQLretAll) {
                        RET = JSON.parse(title);
                    } else {
                        RET = JSON.parse(title)[0][SQLsearchColumn];
                    }
                }
                
                if (callback != undefined) {
                    callback(RET);
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }

            }
        });
        return RET;
    },

    MultiSqlValue: function (SQLtable, SQLwhere, async, callback) {
        Functions.Connected();
        var RET;
        var async2 = false;
        
        if (async) {
            async2 = true;
        }
        
        $.ajax({
            type: "POST",
            data: "SQLString=SELECT * FROM " + SQLtable + " WHERE " + escape(SQLwhere.replace(/\(%\)|%/g, "(PERCENT)")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable3",

            cache: false,
            async: async2,
            success: function (data) {

                var title = $(data).find('string').first().text();
                RET = JSON.parse(title);
                
                if (callback != undefined) {
                    callback(RET);
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    SqlValue: function (SQLString, async, retHeaders, callback) {
        Functions.Connected();
        var RET;
        var async2 = false;
        var retHeaders2 = "3";

        if (async) {
            async2 = true;
        }

        if (retHeaders) {
            retHeaders2 = "";
        }
        
        $.ajax({
            type: "POST",
            data: "SQLString=" + escape(SQLString.replace(/\(%\)|%/g, "(PERCENT)")),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetDataTable" + retHeaders2,

            cache: false,
            async: async2,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title == '[]') {
                    RET = true;
                } else {
                    RET = JSON.parse(title);
                }
                
                if (callback != undefined) {
                    callback(RET);
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
                callback({"error": a.responseText});
                RET = false;
            }
        });
        return RET;
    },
    
    MaxAnswerBasedOnColumnValue: function(columnSearch, valueSearch, columnGet) {
        var answer = GetData.SingleSqlValue('Answer', 'OS_Answer', 'Form_Id = (SELECT TOP(1) Form_Id FROM dbo.OS_Answer WHERE Question_Id = \'' + columnSearch + '\' and Answer = \'' + valueSearch + '\' order BY Created_Date DESC) and Question_Id = \'' + columnGet + '\'');
        return (answer == undefined ? "" : answer);
    },

    MaxNumberfromDatabase: function (tableId, columnId, filterText) {
        var MaxNum = "";
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + escape(tableId + "|" + columnId + "|" + filterText),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Max_Number",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title == '[[]]') {
                    //debugger;
                } else {
                    MaxNum = title;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return MaxNum;
    },

    UrlParameter: function (sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    },

    AllUrlParameter: function () {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i,
            Parm = {};

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            Parm[sParameterName[0]] = (sParameterName[1] === undefined ? "" : sParameterName[1]);
        }
        return Parm;
    },

    ReportData: function (reportId) {
        var RepQuery = '';
        Functions.Connected();

        $.ajax({
            type: "POST",
            data: "RepId=" + escape(reportId),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetSingleReport",

            cache: false,
            async: false,
            success: function (data) {

                RepQuery = $(data).find('string').first().text();
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RepQuery;
    },

    ReportTable: function (repQuery) {
        var RetDataTable = '';

        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "SQLString=" + escape((JSON.parse(repQuery)[0].Script.replace(/\(\^\)/g, "(NOTDIVIDER)")).replace(/\[SEASON\]/g, GetData.localStorage("Season")).replace(/\[SITE\]/g, GetData.localStorage("Classification"))),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetReport",

            cache: false,
            async: false,
            success: function (data) {

                RetDataTable = $(data).find('string').first().text();
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RetDataTable;
    },

    Position: function (str, m, i) {
        return str.split(m, i).join(m).length;
    },

    LocalStorageJSONData: function (keyName, jsonFieldId, jsonId, orderBy, seperation, fieldName, optionalSecondFieldName, optionalThirdFieldName) {
        var data = [];

        if (typeof keyName == "string") {
            data = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key
        } else if (typeof keyName == "object") {
            data = keyName;
        }

        var returnData = "";

        if (orderBy != "") {
            Functions.sortArray(data, orderBy, true, false);
        }


        if (data == null) {
            data = [];
        }

        for (var i = 0; i < data.length; i++) {
            if (data[i][jsonFieldId] == jsonId || (jsonId == 'NULL' && data[i][jsonFieldId] > 0)) {
                if (optionalThirdFieldName != undefined) {
                    returnData += data[i][fieldName] + "|" + data[i][optionalSecondFieldName] + "|" + data[i][optionalThirdFieldName] + seperation;
                } else if (optionalSecondFieldName != undefined) {
                    returnData += data[i][fieldName] + "|" + data[i][optionalSecondFieldName] + seperation;
                } else {
                    returnData += data[i][fieldName] + seperation;
                }
            }
        }

        if (returnData.length == 0) {
            return returnData;
        } else {
            return returnData.substr(0, returnData.length - 1);
        }
    },

    LocalStorageAllJSONData: function (keyName, jsonFieldId, jsonId) {
        var data = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key
        var returnData = [];

        for (var i = 0; i < data.length; i++) {
            if (data[i][jsonFieldId] == jsonId) {
                returnData.push(data[i]);
            }
        }
        return returnData;
    },

    LocalStorageSingleJSONData: function (keyName, jsonFieldId, jsonId, fieldName) {
        var data = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key

        if (data == null) {
            data = [];
        }

        for (var i = 0; i < data.length; i++) {
            if (data[i][jsonFieldId] == jsonId) {
                return data[i][fieldName];
            }
        }
        return undefined;
    },

    LocalStorageJSON: function (keyName, jsonFieldId, jsonId) {
        var data = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key
        for (var i = 0; i < data.length; i++) {
            if (data[i][jsonFieldId] == jsonId) {
                return data[i];
            }
        }
        return undefined;
    },

    ArraySingleData: function (arrayJSON, tableId, tablefieldId, returnfieldId, insensitive) {

        try {
            for (var i = 0; i < arrayJSON.length; i++) {
                if (!insensitive) {
                    if (arrayJSON[i][tablefieldId] == tableId) {
                        return arrayJSON[i][returnfieldId];
                    }
                } else {
                    if (!arrayJSON[i][tablefieldId]) {
                        if (arrayJSON[i][tablefieldId] == tableId) {
                            return arrayJSON[i][returnfieldId];
                        }
                    } else {
                        if (arrayJSON[i][tablefieldId].toUpperCase() == tableId.toUpperCase()) {
                            return arrayJSON[i][returnfieldId];
                        }
                    }
                }
            }
        } catch (err) {
            return undefined;
        }
        return undefined;
    },

    MaxID: function (keyName, FieldIdGetMax, FilterId, FilterText) {

        var TableCount = [];
        var data = JSON.parse(GetData.localStorage(keyName)); //Get Data from Key
        var datal = (data == null ? 0 : data.length);
        for (var i = 0; i < datal; i++) {
            if (FilterId != null) {
                if (data[i][FilterId] == "All" || data[i][FilterId] == FilterText) {
                    TableCount.push(data[i][FieldIdGetMax]);
                }
            }
        }
        if (TableCount.length > 0) {
            return Math.max.apply(Math, TableCount);
        } else {
            return 0;
        }

    },

    MaxIDServer: function (tableName, FieldIdGetMax, FilterId, FilterText) {

        var TableCount = [];
        var data = GetData.MultiSqlValue(tableName, FilterId + " = '" + FilterText + "'"); //Get Data from Key
        var datal = (data == null ? 0 : data.length);
        for (var i = 0; i < datal; i++) {
            TableCount.push(data[i][FieldIdGetMax]);
        }
        if (TableCount.length > 0) {
            return Math.max.apply(Math, TableCount);
        } else {
            return 0;
        }

    },

    ImportExcel: function (files, callback) {
        Functions.Modal('Processing Files...');
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            //var output = document.getElementById("fileOutput");
            var texto = e.target.result;

            var lines = texto.split("\n");
            var result = [];
            var headers;
            for (var i = 0; i < lines.length; i++) {
                headers = lines[i].split("\n");
            }
            var cont = 0;
            for (var i = 0; i < lines.length; i++) {

                var obj = {};
                var currentline = lines[i].split("\n");
                for (var j = 0; j < headers.length; j++) {
                    obj[cont] = currentline[j];
                }
                cont++;
                result.push(obj);
            }

            callback(result); //JSON
            Functions.Modal();
        };
        if (file != undefined) {
            reader.readAsText(file);
        } else {
            callback(null);
            Functions.Modal();
            handleAlerts.HideAlerts();

        }
    },

    getNthOccurrence: function (str, nth, divisor) {
        var arrStr = "";
        if (str != undefined && typeof str == "string") {
            arrStr = str.split(divisor);
        }
        return arrStr[nth];
    },

    localStorage: function (key) {
        if (!Functions.isLocalStorageNameSupported()) {
            handleAlerts.Simple("Can't store data locally.");
            throw new Error("Can't access localstorage.");
        } else {
//            if (key == 'Season') {
//                var season = (GetData.SingleSqlValue('Season', 'OS_App_Data', '1 = 1') == undefined ? ['2019'] : GetData.SingleSqlValue('Season', 'OS_App_Data', '1 = 1').split(','));
//                if (localStorage.getItem('Season') == undefined) {
//                    SetData.localStorage('Season', season.slice(-1)[0]);
//                }
//                return localStorage.getItem("Season");
//            } else {
            return localStorage.getItem(key);
//            }
        }
    },

    storedProdReport: function (sp) {
        var RET;
        $.ajax({
            type: "POST",
            data: "StringJSON=" + escape(sp + '|' + GetData.localStorage('Season')),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Data_Report",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    RET = title;
                } else {
                    RET = false;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        return RET;
    },

    multiArrayIndex: function (arr, key, value) {

        var findVal = value.join('^');

        var index = arr.map(function (mapArr) {

            var ret = '';

            for (var i = 0; i < key.length; i++) {
                ret += mapArr[key[i]] + '^';
            }

            ret = ret.substr(0, ret.length - 1);

            return ret;

        }).indexOf(findVal);

        return index;
    },

    geoLocation: function (ele) {
        var thisField = ele;
        var pos;

        var apiGeolocationSuccess = function (position) {
            console.log("API geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
            $('#23' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_get').attr('placeholder', 'Coordinates Taken');
            $('#1' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9)).val(position.coords.latitude + ',' + position.coords.longitude);
            $('#1' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_x').show();
            $('#23' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_viewBtn').show();
        };

        var tryAPIGeolocation = function () {
            jQuery.post("https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDPw2m-OOoKy5QiD5PkCKBcELlpYqdc2R4", function (success) {
                    apiGeolocationSuccess({
                        coords: {
                            latitude: success.location.lat,
                            longitude: success.location.lng
                        }
                    });
                })
                .fail(function (err) {
                    debugger;
                    console.log("API Geolocation error! \n\n" + err);
                });
        };

        var browserGeolocationSuccess = function (position) {
            console.log("Browser geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
            $('#23' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_get').attr('placeholder', 'Coordinates Taken');
            $('#1' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9)).val(position.coords.latitude + ',' + position.coords.longitude);
            $('#1' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_x').show();
            $('#23' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_viewBtn').show();
        };

        var browserGeolocationFail = function (error) {
            switch (error.code) {
                case error.TIMEOUT:
                    console.log("Browser geolocation error !\n\nTimeout.");
                    break;
                case error.PERMISSION_DENIED:
                    if (error.message.indexOf("Only secure origins are allowed") == 0) {
                        tryAPIGeolocation();
                    }
                    break;
                case error.POSITION_UNAVAILABLE:
                    console.log("Browser geolocation error !\n\nPosition unavailable.");
                    break;
            }
        };

        var tryGeolocation = function () {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    browserGeolocationSuccess,
                    browserGeolocationFail, {
                        maximumAge: 50000,
                        timeout: 20000,
                        enableHighAccuracy: true
                    });
            }
        };

        if (navigator.geolocation) {
            tryGeolocation();
        } else {
            $('#23' + $(thisField).attr('id').substr(2, $(thisField).attr('id').length - 9) + '_get').attr('placeholder', "Geolocation is not supported");
        }
    },
    
    getBearer: function() {
        var asmxtoken = '';

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'https://test.amp.monsanto.com/as/token.oauth2',
                contentType: 'application/x-www-form-urlencoded',
                data: { 'grant_type': 'client_credentials', 'client_secret': 'JWlWz31DavUl1Hwgs6gif9yYfQXcdqDCoL9sZn0ICGzDzt1maH', 'client_id': 'GSC-OSIRIS-SVC' },
                async: false,
                success: function(data) {
                    asmxtoken = "Bearer " + data["access_token"];
                },
                error: function(a, b, c) {
                    //debugger;
                }
            });
        return asmxtoken;
    },
    
    UserData: function(options, callback){
//        Possible Options:
//        SubDivisionDescriptionLong
//        EmployeeID
//        PreferredFirstName
//        AccountType
//        PreferredLastName
//        CostCenter
//        CountryCode3
//        CountryCode2
//        actualdn
//        DepartmentDescriptionLong
//        entrydn
//        SiteLocationCode
//        ManagerDisplayName
//        city
//        DepartmentCode
//        PartyID
//        CompanyCode
//        SiteLocationName
//        cacheModifiersName
//        DivisionCode
//        DivisionDescriptionLong
//        cn
//        cacheModifyTimestamp
//        SubDivisionDescriptionShort
//        Level3DescriptionShort
//        OnLegalHold
//        ManagerEmployeeID
//        DepartmentDescriptionShort
//        WorldArea
//        LegalFirstName
//        DisplayName
//        Country
//        EmployeeType
//        JobTitle
//        DivisionDescriptionShort
//        Brand
//        Level3DescriptionLong
//        ExtranetMail
//        FunctionalArea
//        Level3Code
//        JobCode
//        LegalLastName
//        BusinessArea
//        cacheCreatorsName
//        SubDivisionCode
//        employeeStatus
//        Region
//        cacheCreateTimestamp
        
        var asmxtoken = GetData.getBearer();
       
        var headOptions = [];
        var tableHTML = "";
        var tableData = [];

//            headOptions = $('#SelectFields option:selected');

        options = "filter=(%26" + options + ")";
        
        $.ajax({
            url: 'https://api-t.monsanto.com/vds-identity-d?' + options,
            type: 'GET',
            dataType: 'json',
            async: true,
            beforeSend: function (xhr) {
                //alert(asmxtoken);
                xhr.setRequestHeader('Authorization', asmxtoken);
//                    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
            },
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                console.dir(data);
                callback(data.resources);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            },
        });
    }

}

var SyncTables = {

    Sidebar: function () {
        console.log('Start Sync Sidebar');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=" + GetData.localStorage('UserId') + "|" + GetData.localStorage('Classification'),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/GetSidebar",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    localStorage.removeItem('Sidebar');
                    Functions.AddOrUpdateLocalStorage('Sidebar', 'id_Sidebar', JSON.parse(title));
                    SetData.SyncDates('Sidebar');
                }
                console.log('End Sync Sidebar');
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    Catalog: function () {
        console.log('Start Sync Catalog');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Catalog" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].Catalog),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    title = JSON.parse(title);
                    var dat = Functions.filterArray(title, {
                        Site: function (value) {
                            return value == null || value == GetData.localStorage('Classification');
                        }
                    });
                    Functions.AddOrUpdateLocalStorage('Catalog', 'id_Catalog', dat);
                    SetData.SyncDates('Catalog');
                }
                console.log('End Sync Catalog');

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    Catalog_Category: function () {
        console.log('Start Sync Category');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Catalog_Category" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].Catalog_Category),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    Functions.AddOrUpdateLocalStorage('Catalog_Category', 'id_Catalog_Category', JSON.parse(title));
                    SetData.SyncDates('Catalog_Category');
                }
                console.log('End Sync Category');
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    Languages: function () {
        console.log('Start Sync Language');
        languageData = GetData.MultiSqlValue('OS_Languages', "1=1");
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Languages" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].Languages),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    Functions.AddOrUpdateLocalStorage('Languages', 'id_Language', JSON.parse(title));
                    SetData.SyncDates('Languages');
                }
                console.log('End Sync Language');

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    Alerts: function () {
        console.log('Start Sync Alerts');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Alerts" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].Alerts),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    Functions.AddOrUpdateLocalStorage('Alerts', 'id_Alert', JSON.parse(title));
                    SetData.SyncDates('Alerts');
                }
                console.log('End Sync Alerts');

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    Events: function () {
        console.log('Start Sync Events');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Events" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].Events),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    Functions.AddOrUpdateLocalStorage('Events', 'id_Event', JSON.parse(title));
                    SetData.SyncDates('Events');
                }
                console.log('End Sync Events');

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    },

    MasterTable: function () {
        console.log('Start Sync Master Table');
        Functions.Connected();
        $.ajax({
            type: "POST",
            data: "StringJSON=sp_OS_Get_Master_Table" + "|" + (JSON.parse(GetData.localStorage("Dates")) == null ? '1/1/1900' : JSON.parse(GetData.localStorage("Dates"))[0].MasterTable),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();
                if (title != '[]') {
                    Functions.AddOrUpdateLocalStorage('MasterTable', 'id_Master_Table', JSON.parse(title));
                    SetData.SyncDates('MasterTable');
                }
                console.log('End Sync Master Table');

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

    },

    RO: function () {

        $.ajax({
            type: "POST",
            data: "StringJSON=" + GetData.localStorage('UserId'),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_RO",

            cache: false,
            async: false,
            success: function (data) {

                var title = $(data).find('string').first().text();

                SetData.localStorage('RO', title);

            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });

    },

    Question: function () {
        localStorage.removeItem("Question");
        //console.log('Start Sync Question');
        //Functions.Connected();
        //var Qst = [];
        //$.ajax({
        //    type: "POST",
        //    data: "StringJSON=sp_OS_Get_Question" + "|" + JSON.parse(GetData.localStorage("Dates"))[0].Question,
        //    dataType: "xml",
        //    url: DUrl + "WebServiceOsiris.asmx/Get_Tables",
        //    
        //    cache: false,
        //    async: false,
        //    success: function(data) {

        //        var TITLE = JSON.parse($(data).find('string').first().text());
        //        if (TITLE != '[]') {
        //            for (var i = 0; i < TITLE.length; i++) {
        //                if ( GetData.LocalStorageSingleJSONData("Sidebar", "Name", TITLE[i].FormName, "Name") != undefined) {
        //                    Qst.push(TITLE[i]);
        //                }
        //            }
        //            Functions.AddOrUpdateLocalStorage('Question', 'id_Question', Qst);
        //            SetData.SyncDates('Question');
        //        }
        //    },
        //    error: function(a, b, c) {
        //        //debugger;
        //    }
        //});

    },

    FTSData: function () {

        handleAlerts.ShowLoading();
        SyncTables.FTSSync();

        //        $(document).unbind("idle");
        //        $("#DownloadSync").html('<div id="DownloadInfoDiv" style="width: 350px; height: 440px; float: left; overflow-y: auto;overflow-x: hidden; overflow-wrap: break-word;">' +
        //    '<div id="DownloadInfo"></div>' +
        //    '</div>' +
        //    '<div style="width: 280px; height: 440px; float: right;">' +
        //    '<div id="topLoader" style="top: 75px; left: 40px; position: relative;"></div><img src="imagen\\loading_spinner.gif" style="  position: relative;width: 200px;left: 50px;top: 80px;"></div>');
        //
        //        var FinishDownload_1 = 0;
        //        var QtyCat_1 = 0;
        //        var QtyProcess_1;
        //        var $topLoader_1;
        //        var Steps_1 = 0;
        //        var TotalSteps_1 = 2;
        //
        //        function animateFunc_1() {
        //            $('#DownloadInfoDiv').scrollTop($('#DownloadInfoDiv')[0].scrollHeight);
        //            Steps_1 += 1;
        //            $topLoader_1.setProgress(Steps_1 / TotalSteps_1);
        //            $topLoader_1.setValue('Steps' + Steps_1);
        //            $('#DownloadInfoDiv').scrollTop = $('#DownloadInfoDiv').scrollHeight;
        //        }
        //
        //        function DownloadlData_1() {
        //            if (FinishDownload_1 === 0) {
        //                $('#DownloadInfo').html($('#DownloadInfo').html() + '<br/> Start FTS Sync...');
        //                animateFunc_1();
        //                TestSync1();
        //                //test();
        //                FinishDownload_1 += 1;
        //                //LoopSync2();
        //            } else if (FinishDownload_1 === 1) {
        //                (QtyCat_1 === 99999 ? $('#DownloadInfo').html($('#DownloadInfo').html() + '<br /> Error Sync.') : $('#DownloadInfo').html($('#DownloadInfo').html() + '<br /> End Sync.'));
        //                QtyProcess_1 = 0;
        //                animateFunc_1();
        //                FinishDownload_1 += 1;
        //                LoopSync2();
        //                //    } else if (FinishDownload === 20) {
        //                //        $('#DownloadInfo').html($('#DownloadInfo').html() + '<br/> Downloading Attachemnt Names...');
        //                //        animateFunc();
        //                //        AttachmentNameDownload();
        //                //    } else if (FinishDownload === 21) {
        //                //        (QtyCat === 99999 ? $('#DownloadInfo').html($('#DownloadInfo').html() + '<br /> There were some error downloading the Attachemnt Names.') : $('#DownloadInfo').html($('#DownloadInfo').html() + '<br /> Download Completed.  ' + QtyProcess + ' out of ' + QtyCat + ' Attachemnt names downloaded.'));
        //                //        QtyProcess = 0;
        //                //        animateFunc();
        //                //        FinishDownload += 1;
        //                //        DownloadlData();
        //            } else {
        //                FinishDownload_1 = 0;
        //                animateFunc_1();
        //
        //                var dataString = GetData.localStorage("UserId");
        //                Functions.Connected();
        //
        //                $.ajax({
        //                    type: "POST",
        //                    data: "StringArr=" + escape(dataString),
        //                    dataType: "xml",
        //                    url: DUrl + "WebServiceOsiris.asmx/Sync",
        //
        //                    cache: false,
        //                    async: false,
        //                    success: function (data) {
        //
        //                        var $title = $(data).find('string').first().text();
        //                        if ($title == "Done") {
        //                            $("#DownloadSync").html('').removeClass("modalDialog2");
        //                            $("#backscreen").removeClass("modalBack2");
        //                            window.location.href = "Dashboard.html";
        //                        } else {
        //                            alert($title);
        //                            //debugger;
        //                        }
        //                    },
        //                    error: function (a, b, c) {
        //                        if (GetData.localStorage("onScreenError") == "true") {
        //                            handleAlerts.Simple(a.responseText);
        //                        } else {
        //                            console.log(a.responseText);
        //                        }
        //                    }
        //                });
        //            }
        //        }
        //
        //        //$("#SyncDiv").html("<div id=\"backscreen\" class=\"\">" +
        //        //    "</div>" +
        //        //    "<div id=\"DownloadSync\" class=\"rounded-corners\">" +
        //        //    "<h2>Synchronizing Data...</h2>" +
        //        //    "<div id=\"DownloadInfoDiv\" style=\"width: 350px; height: 440px; float: left; overflow-y: auto;overflow-x: hidden; overflow-wrap: break-word;\">" +
        //        //    "<div id=\"DownloadInfo\">" +
        //        //    "</div>" +
        //        //    "</div>" +
        //        //    "<div style=\"width: 280px; height: 440px; float: right;\">" +
        //        //    "<div id=\"topLoader\" style=\"top: 75px; left: 40px; position: relative;\">" +
        //        //    "</div>" +
        //        //    "<img src=\"imagen\\loading_spinner.gif\" style=\"  position: relative;width: 200px;left: 50px;top: 80px;\">" +
        //        //    "</div>" +
        //        //    "</div>");
        //
        //
        //        $topLoader_1 = $("#topLoader").percentageLoader({
        //            width: 220,
        //            height: 220,
        //            controllable: true,
        //            progress: 0.0,
        //            onProgressUpdate: function (val) {
        //                $topLoader_1.setValue(Math.round(val * 100.0));
        //            }
        //        });
        //
        //        $("#backscreen").addClass("modalBack2");
        //        $("#DownloadSync").addClass("modalDialog2");
        //
        //        function LoopSync2() {
        //            myVar_1 = setInterval(function () {
        //                clearTimeout(myVar_1);
        //                //FinishDownload += 1;
        //                DownloadlData_1();
        //            }, 10);
        //        }
        //
        //        LoopSync2();
        //
        //        function TestSync1() {
        //            var asmxtoken = "";
        //            Functions.Connected();
        //
        //            $.ajax({
        //                type: "POST",
        //                dataType: "json",
        //                url: "http://techit-tst.monsanto.com/dataapi/api/wam/",
        //                data: { "userid": "NA7080APP-OSIRISAPP", "password": "Monsanto@1" },
        //                //password = 2Dx8O6@
        //                async: true,
        //                success: function (data) {
        //                    console.dir(data);
        //                    asmxtoken = data.split("=")[1];
        //                    console.dir(asmxtoken);
        //                    TestSync2(asmxtoken);
        //                },
        //                error: function (a, b, c) {
        //                    if (GetData.localStorage("onScreenError") == "true") {
        //                        handleAlerts.Simple(a.responseText);
        //                    } else {
        //                        console.log(a.responseText);
        //                    }
        //                }
        //            });
        //        }
        //
        //        function TestSync2(asmxtoken) {
        //            Functions.Connected();
        //            $.ajax({
        //                url: 'http://techit.monsanto.com/DataAPI/api/sim_staging?season=2016:05&user=NA7080APP-OSIRISAPP',
        //                type: "GET",
        //                dataType: "json",
        //                async: true,
        //                beforeSend: function (xhr) {
        //                    //alert(asmxtoken);
        //                    xhr.setRequestHeader("Authorization", asmxtoken);
        //                },
        //                contentType: "application/json; charset=utf-8",
        //                success: function (data) {
        //                    TestSync3(data);
        //                    //console.log(JSON.stringify(data));
        //                },
        //                error: function (xhr, ajaxOptions, thrownError) {
        //                    alert(xhr.status);
        //                    alert(thrownError);
        //                },
        //            });
        //
        //        }
        //
        //        function TestSync3(data) {
        //
        //            var SEND_DATA = "";
        //            var test = 1;
        //            for (var i = 0; i < data.length; i++) {
        //                var FORM_DATA = "";
        //                if (data[i].ZY_INVBID != null) {
        //                    for (var key in data[i]) {
        //                        var obj = data[i][key];
        //                        FORM_DATA += key + "|" + obj + "¥";
        //                    }
        //
        //                    //console.log(test);
        //                    test += 1;
        //                    SEND_DATA += GetData.localStorage('UserId') + 'ÿStartÿ0ÿNEWMASTER' + '~' + data[i].ZY_INVBID + '~' + data[i].ZY_INVBID + 'ÿ' + GetData.localStorage('Classification') + 'ÿ' + GetData.localStorage('Season') + '*' + FORM_DATA.substr(0, FORM_DATA.length - 1) + 'æ';
        //
        //                }
        //            }
        //            //$("#Test").html(JSON.stringify(data));
        //            console.log('send data');
        //            SendAns(SEND_DATA);
        //        }
        //
        //        function SendAns(formData) {
        //            Functions.Connected();
        //            $.ajax({
        //                type: "POST",
        //                data: "StringJSON=" + escape(formData),
        //                dataType: "text",
        //                url: DUrl + "WebServiceOsiris.asmx/Send_Answer",
        //                async: true,
        //                success: function (data) {
        //
        //                    var xml = data,
        //                        xmlDoc = $.parseXML(xml),
        //                        $xml = $(xmlDoc),
        //                        $title = $xml.find("string");
        //
        //                    if ($title.text() == '[]') {
        //                        //don't Pass
        //                        //debugger;
        //                    } else {
        //                        //Pass
        //                        console.log('Pass');
        //                        FinishDownload += 1;
        //                        DownloadlData_1();
        //                    }
        //                },
        //                error: function (a, b, c) {
        //                    if (GetData.localStorage("onScreenError") == "true") {
        //                        handleAlerts.Simple(a.responseText);
        //                    } else {
        //                        console.log(a.responseText);
        //                    }
        //                }
        //            });
        //        }
    },
    
    FTSSync: function () {
        var asmxtoken = '';

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://techit-tst.monsanto.com/dataapi/api/wam/',
            data: {
                'userid': 'NA7080APP-OSIRISAPP',
                'password': 'Monsanto@1'
            },
            //password = 2Dx8O6@
            async: true,
            success: function (data) {
                console.dir(data);
                asmxtoken = data.split('=')[1];
                console.dir(asmxtoken);
                SyncTables.FTSSync2(asmxtoken);
            },
            error: function (a, b, c) {
                //debugger;
            }
        });
    },

    FTSSync2: function (asmxtoken) {
        $.ajax({
            url: 'http://techit.monsanto.com/DataAPI/api/sim_staging?season=2017:05&user=NA7080APP-OSIRISAPP',
            type: 'GET',
            dataType: 'json',
            async: true,
            beforeSend: function (xhr) {
                //alert(asmxtoken);
                xhr.setRequestHeader('Authorization', asmxtoken);
            },
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                SyncTables.FTSSync3(data);
                //console.log(JSON.stringify(data));
            },
            error: function (xhr, ajaxOptions, thrownError) {
                handleAlerts.Simple(xhr.status);
                handleAlerts.Simple(thrownError);
            },
        });

    },

    FTSSync3: function (data) {

        var SEND_DATA = '';
        var test = 1;
        for (var i = 0; i < data.length; i++) {
            var FORM_DATA = '';
            if (data[i].ZY_INVBID != null) {
                for (var key in data[i]) {
                    var obj = data[i][key];
                    FORM_DATA += key + '|' + obj + '¥';
                }

                console.log(FORM_DATA);
                test += 1;
                SEND_DATA += localStorage.getItem('UserId') + 'ÿStartÿ0ÿNEWMASTER' + '~' + data[i].ZY_INVBID + '~' + data[i].ZY_INVBID + 'ÿ' + localStorage.getItem('Classification') + 'ÿ' + localStorage.getItem('Season') + '*' + FORM_DATA.substr(0, FORM_DATA.length - 1) + 'æ';

            }
        }
        //$('#Test').html(JSON.stringify(data));
        console.log('send data');
        SyncTables.FTSSendAns(SEND_DATA);
    },

    FTSSendAns: function (formData) {
        $.ajax({
            type: 'POST',
            data: 'StringJSON=' + formData,
            dataType: 'text',
            url: 'http://osiris.monsanto.com/WebServiceOsiris.asmx/Send_Answer',
            async: true,
            success: function (data) {

                var xml = data,
                    xmlDoc = $.parseXML(xml),
                    $xml = $(xmlDoc),
                    $title = $xml.find('string');

                if ($title.text() == '[]') {
                    handleAlerts.HideAlerts();
                    //debugger;
                } else {
                    //Pass
                    console.log('Pass');
                    handleAlerts.Callback('FTS Sync Completed',function() {handleAlerts.HideAlerts();});
                }
            },
            error: function (a, b, c) {
                //don't Pass
                //debugger;
            }
        });
    }
}

var handleAlerts = {
    Simple: function (message, position) {
        if (message != "" && message != null) {
            handleAlerts.Position(position);
            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.alert(message);
            }
        }
    }, //handleAlerts.Simple('Esto es una prueba')

    SimpleColor: function (message, color, position) {
        if (message != "" && message != null) {
            handleAlerts.Position(position);
            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.alert(message);
                $('.modal-backdrop.fade.in').attr('style', 'background-color: ' + color + ' !important');
            }
        }
    }, //handleAlerts.Simple('Esto es una prueba')

    Callback: function (message, callbackFunc, position) {
        if (message != "" && message != null) {
            handleAlerts.Position(position);
            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.alert(message, function () {
                    callbackFunc();
                });
            }
        }
    }, //handleAlerts.Callback('Esto es una prueba',  function() {alert("Hola");})

    OkCancel: function (message, callbackFuncOk, callbackFuncCancel, position) {
        if (message != "" && message != null) {
            handleAlerts.Position(position);
            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.confirm(message, function (result) {
                    if (result == false) {
                        callbackFuncCancel();
                    } else {
                        callbackFuncOk();
                    }
                });
            }
        }
    }, //handleAlerts.OkCancel('Esto es una prueba',  function() {alert("Ok");},  function() {alert("Cancel");})

    Prompt: function (message, callbackFuncOk, callbackFuncCancel, position) {
        if (message != "" && message != null) {
            handleAlerts.Position(position);
            if (typeof bootbox == "undefined") {
                alert(message);
            } else {
                bootbox.prompt(message, function (result) {
                    if (result === null) {
                        callbackFuncCancel();
                    } else {
                        callbackFuncOk(result);
                    }
                });
            }
        }
    }, //handleAlerts.Prompt('Esto es una prueba', function(result) {alert(result);}, function() {alert("Cancel");})

    CustomDialog: function (getOpt) {

        var options = {
            message: {
                def: ' ',
                help: 'Any text'
            },
            title: {
                def: '',
                help: 'Any text'
            },
            buttons: {
                def: null,
                help: '{buttonName : {label: \'Your button text\',className: "some-class",callback: function() {}}}'
            },
            onEsc: {
                def: null,
                help: 'null, true, false'
            },
            position: {
                def: null,
                help: 'null, center, bottom'
            },
            size: {
                def: null,
                help: 'null, large, small'
            },
            modalClose: {
                def: undefined,
                help: 'undefined, true, false (true if onEsc is true)'
            },
            closeButton: {
                def: true,
                help: 'false, true'
            },
            init: {
                def: function () {},
                help: 'add a function to be called when the dialog gets initialized.'
            }
        }
        
        Object.keys(options).map(function (key, index) { options[key] = options[key]["def"];})

        if (typeof getOpt == "undefined") return options;

        options = Functions.compareObjectArray(options, getOpt);

        handleAlerts.Position(options.position);

        if (typeof bootbox == "undefined") {
            alert(message);
        } else {
            var dialogBootbox = bootbox.dialog({
                message: options.message,
                title: options.title,
                buttons: options.buttons,
                onEscape: options.onEscape,
                backdrop: options.modalClose,
                size: options.size,
                closeButton: options.closeButton
            });
            dialogBootbox.on("shown.bs.modal", function() {
                options.init();
            });
            dialogBootbox.modal('show');
        }
    }, //handleAlerts.CustomDialog('Esto es una prueba', 'Titulo', {success: {label: "Success!",className: "green pull-left",callback: function() {alert("great success");}},danger: {label: "Danger!",className: "red pull-right",callback: function() {alert("uh oh, look out!");}},main: {label: "Click ME!",className: "blue pull-right",callback: function() {alert("Primary button");}}})

    ShowLoading: function (text, size) {
        if (typeof bootbox != "undefined") {
            if (text == undefined) {
                text = 'Please wait...';
            }
            if (size == undefined) {
                size = 'small';
            }
            handleAlerts.Position('center');

            if (bootboxLoading != undefined) {
                bootboxLoading.find('.bootbox-body').html('<p class="text-center"><i class="fa fa-spin fa-spinner"></i> <span id="loadingText">' + text + '</span></p>');
            } else {
                bootboxLoading = new bootbox.dialog({
                    message: '<p class="text-center"><i class="fa fa-spin fa-spinner"></i> <span id="loadingText">' + text + '</span></p>',
                    closeButton: false,
                    size: size
                });
            }
        }
    },

    HideAlerts: function () {
        if (typeof bootbox != "undefined") {
            if (GetData.localStorage("onScreenError") != "true") {
                bootbox.hideAll();
                bootboxLoading = void 0;
            } else {
                if (bootboxLoading != undefined) {
                    bootboxLoading.modal('hide');
                    bootboxLoading = void 0;
                }
            }
        }
    },

    Position: function (position) {
        $("body").off("show.bs.modal");
        if (position == 'center') {
            $("body").on("show.bs.modal", ".modal", function () {
                $(this).css({
                    'top': '50%',
                    'margin-top': function () {
                        return -($(this).height() / 2);
                    }
                });
            });
        } else if (position == 'Bottom') {
            $("body").on("show.bs.modal", ".modal", function () {
                $('.modal-dialog').css({
                    'position': 'fixed',
                    'bottom': '0px',
                    'left': '50%',
                    'margin-left': function () {
                        return -($('.modal-dialog').width() / 2);
                    }
                });
            });
        }
    },

    BlockElement: function (getOpt) {

        var options = {
            MESSAGE: {
                def: "",
                help: 'Any text'
            },
            ELEMENT: {
                def: $('#NONE'),
                help: 'Any element'
            },
            TYPE: {
                def: "loader",
                help: 'loader, spinner'
            },
            STATE: {
                def: "accent",
                help: 'brand, success, accent, metal, light, primary, info, warning, danger, focus'
            },
            OPACITY: {
                def: ".03",
                help: "Any number between 0 and 1"
            }
        }

        Object.keys(options).map(function (key, index) { options[key] = options[key]["def"]; })

        if (typeof getOpt == "undefined") return options;

        options = Functions.compareObjectArray(options, getOpt);
        
        mApp.block(options.ELEMENT, {
            type: options.TYPE,
            state: options.STATE,
            opacity: options.OPACITY,
            message: options.MESSAGE
        });
    },
    UnblockElement: function (ELEMENT) {
        mApp.unblock(ELEMENT);
    }
}

var DateFunctions = {

    StringToDate: function (dateString) {
        var NewDate = new Date(dateString);
        return NewDate;
    },

    FormatDate: function (ddate, format) {
        if (!ddate) {
            ddate = new Date();
        }

        var date = new Date(ddate),
            day = date.getDate(),
            month = date.getMonth() + 1,
            year = date.getFullYear(),
            hours = date.getHours(),
            minutes = date.getMinutes(),
            seconds = date.getSeconds();

        if (ddate != "" && ddate != " ") {
            var monthNames = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

            if (!format) {
                format = "MM/dd/yyyy";
            }
            
            if (format == "UTC+") {
                return (new Date(new Date(ddate) + ((new Date()).getTimezoneOffset() * 60000))).toISOString().slice(0, -1);
            } else if (format == "UTC-") {
                return (new Date(new Date(ddate) - ((new Date()).getTimezoneOffset() * 60000))).toISOString().slice(0, -1);
            }

            if (format.indexOf("MMMM") > -1) {
                format = format.replace("MMMM", monthNames[month]);
            } else if (format.indexOf("MM") > -1) {
                format = format.replace("MM", month.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("yyyy") > -1) {
                format = format.replace("yyyy", year.toString());
            } else if (format.indexOf("yy") > -1) {
                format = format.replace("yy", year.toString().substr(2, 2));
            }

            format = format.replace("dd", day.toString().replace(/^(\d)$/, '0$1'));

            if (format.indexOf("T") > -1) {
                if (hours > 11) {
                    format = format.replace("T", "PM");
                } else {
                    format = format.replace("T", "AM");
                }
            }

            if (format.indexOf("HH") > -1) {
                format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("hh") > -1) {
                if (hours > 12) {
                    hours -= 12;
                }

                if (hours === 0) {
                    hours = 12;
                }
                format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("h") > -1) {
                if (hours > 12) {
                    hours -= 12;
                }

                if (hours === 0) {
                    hours = 12;
                }
                format = format.replace("h", hours.toString());
            }

            if (format.indexOf("mm") > -1) {
                format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("ss") > -1) {
                format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
            }

            return format;
        } else {
            return "";
        }
    },

    FormatTime: function (dTime, format) {
        if (!dTime) {
            dTime = new Date();
        }

        var time = new Date(dTime),
            hours = time.getHours(),
            minutes = time.getMinutes(),
            seconds = time.getSeconds();

        if (!format) {
            format = "hh:mm T";
        }

        if (dTime != "" && dTime != " ") {
            if (format.indexOf("T") > -1) {
                if (hours > 11) {
                    format = format.replace("T", "PM");
                } else {
                    format = format.replace("T", "AM");
                }
            }

            if (format.indexOf("HH") > -1) {
                format = format.replace("HH", hours.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("hh") > -1) {
                if (hours > 12) {
                    hours -= 12;
                }

                if (hours === 0) {
                    hours = 12;
                }
                format = format.replace("hh", hours.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("mm") > -1) {
                format = format.replace("mm", minutes.toString().replace(/^(\d)$/, '0$1'));
            }

            if (format.indexOf("ss") > -1) {
                format = format.replace("ss", seconds.toString().replace(/^(\d)$/, '0$1'));
            }

            return format;
        } else {
            return "";
        }
    },

    CompareDates: function (dateStringFrom, dateStringTo, typeOf, ReturnText) {
        //Create date from input value
        var From = new Date(dateStringFrom);

        //Get today's date
        var To = new Date(dateStringTo);

        var Calc = 0;

        if (typeOf == 'Year') {
            //Need Codes
        } else if (typeOf == 'Month') {
            var months;
            months = (To.getFullYear() - From.getFullYear()) * 12;
            months -= From.getMonth() + 1;
            months += To.getMonth();
            if (To.getDate() >= From.getDate()) {
                months++;
            }
            Calc = months <= 0 ? 0 : months;
        } else if (typeOf == 'Day') {
            Calc = Math.ceil((To.setHours(0, 0, 0, 0) - From.setHours(0, 0, 0, 0)) / (1000 * 3600 * 24));
        } else if (typeOf == 'Hour') {
            Calc = Math.ceil((Date.parse(To) - Date.parse(From)) / (1000 * 3600));
        } else if (typeOf == 'Minute') {
            Calc = Math.ceil((Date.parse(To) - Date.parse(From)) / (1000 * 60));
        }

        if (ReturnText) {
            //Return Text
            var day = "";

            switch (Calc) {
                case 0:
                    day = "Today";
                    break;
                case -1:
                    day = "Yesterday";
                    break;
                case 1:
                    day = "Tomorrow";
                    break;
                default:
                    if (Calc < 0) {
                        day = Calc * -1 + " days ago";
                    } else {
                        day = "In " + Calc + " days";
                    }
            }

            return day;
        } else {
            //Return Number
            return Calc;
        }

    },
    
    Add: function (ddate, typeOf, qty) {
        var newDate = new Date(ddate);
        
        if (typeOf == "Year") {
            newDate = new Date(newDate.setFullYear(newDate.getFullYear() + qty));
        } else if (typeOf == "Month") {
            newDate = new Date(newDate.setMonth(newDate.getMonth() + qty));
        } else if (typeOf == "Week") {
            newDate = new Date(newDate.setDate(newDate.getDate() + (qty * 7)));
        } else if (typeOf == "Day") {
            newDate = new Date(newDate.setDate(newDate.getDate() + qty));
        } else if (typeOf == "Hour") {
            newDate = new Date(newDate.setHours(newDate.getHours() + qty));
        } else if (typeOf == "Minute") {
            newDate = new Date(newDate.setMinutes(newDate.getMinutes() + qty));
        }
        return newDate;
    }
}

var sound = {
    beep: function () {
        if ($('#soundTemp')[0] == undefined) {
            $('body').append('<audio id="soundTemp" src="sound/beep.wav"></audio>');
        } else {
            $('#soundTemp')[0].setAttribute('src', "sound/beep.wav");
            $('#soundTemp')[0].load();
        }
        $('#soundTemp')[0].play();
    },
    buzz: function () {
        if ($('#soundTemp')[0] == undefined) {
            $('body').append('<audio id="soundTemp" src="sound/wrong.wav"></audio>');
        } else {
            $('#soundTemp')[0].setAttribute('src', "sound/wrong.wav");
            $('#soundTemp')[0].load();
        }
        $('#soundTemp')[0].play();
    },
    trash: function () {
        if ($('#soundTemp')[0] == undefined) {
            $('body').append('<audio id="soundTemp" src="sound/trash.wav"></audio>');
        } else {
            $('#soundTemp')[0].setAttribute('src', "sound/trash.wav");
            $('#soundTemp')[0].load();
        }
        $('#soundTemp')[0].play();
    }
}

var SlideMenu = {
    OCMenu: function (element, speed, expand) {
        $('.btn-slide').next('div').html(Functions.LanguageSelect('Por Favor Seleccione una Opción:', 'Please Select a Save Option:'));
        $('.btn-slide').html(Functions.LanguageSelect('Menú Grabar', 'Save Menu'));

        //element.html('<i class="fa fa-save slide-menu-icon"></i>');

        if (typeof expand != 'undefined') {
            element.data('expand', expand);
        } else {
            element.data('expand', element.data('expand') ? false : true);
        }

        if (element.data('expand')) {
            element.parent().animate({
                right: '0px'
            }, {
                duration: speed,
                start: function () {
                    //element.find('.fa').addClass('fa-spin fa-spin-fix');
                    element.addClass('withGlow');
                    element.parent().addClass('withGlow');
                }
            });
        } else {
            element.parent().animate({
                right: '-230px'
            }, {
                duration: speed,
                start: function () {
                    //element.find('.fa').removeClass('fa-spin fa-spin-fix');
                    element.removeClass('withGlow');
                    element.parent().removeClass('withGlow');
                }
            });
        }
    },

    slideToggleUD: function (element, speed, isUp) {
        element.siblings('.body-slide').animate({
            display: 'block',
            height: isUp ? 'hide' : 'show'
        }, {
            duration: speed,
            start: function () {
                var title = element.text();
                var icon = isUp ? 'fa-plus-square' : 'fa-minus-square';
                element.html('<i class="fa ' + icon + '"></i> ' + title);
            }
        });
    },

    collapse: function (element, elements, data, speed) {
        if (!data) {
            if (!element.data('collapse')) {
                SlideMenu.slideToggleUD(element, speed, true);
            } else {
                SlideMenu.slideToggleUD(element, speed, false);
            }
            element.data('collapse', element.data('collapse') ? false : true);
        } else {
            if (element.data('collapse')) {
                SlideMenu.slideToggleUD(element, speed, true);
            } else {
                elements.each(function () {
                    if ($(this).data('index') != element.data('index')) {
                        SlideMenu.slideToggleUD($(this), speed, true);
                        $(this).data('collapse', false);
                    }
                });
                SlideMenu.slideToggleUD(element, speed, false);
            }
            element.data('collapse', element.data('collapse') ? false : true);
        }
    },

    collapsed: function (element, data) {
        if (data) {
            if (element.data('index') == 0) {
                SlideMenu.slideToggleUD(element, 100, false);
                element.data('collapse', data);
            } else {
                SlideMenu.slideToggleUD(element, 100, true);
                element.data('collapse', !data);
            }
        } else {
            if (element.data('index') == 0) {
                SlideMenu.slideToggleUD(element, 100, false);
                element.data('collapse', data);
            } else {
                SlideMenu.slideToggleUD(element, 100, true);
                element.data('collapse', !data);
            }
        }
    },

    init: function (menu, settings) {
        var collection = menu;
        var config = {
            speedLR: 500,
            speedUD: 500,
            expand: false,
            collapse: true
        };

        if (settings) {
            $.extend(config, settings);
        }

        return menu.each(function () {
            var self = $(this);
            var elements = {
                btnSlide: self.find('.btn-slide'),
                headSlide: self.find('.head-slide')
            };

            elements.btnSlide.each(function () {
                var $this = $(this);

                SlideMenu.OCMenu($this, config.speedLR, config.expand);

                $this.click(function () {
                    SlideMenu.OCMenu($this, config.speedLR);
                });
            });

            elements.headSlide.each(function (index) {
                var $this = $(this);

                $this.data('index', index);
                SlideMenu.collapsed($this, config.collapse);

                $this.click(function () {
                    SlideMenu.collapse($this, elements.headSlide, config.collapse, config.speedUD);
                });
            });
        });
    }
}

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined' ?
                args[number] :
                match;
        });
    };
}

if (!String.prototype.contain) {
    String.prototype.contain = function (char) {
    return this.includes(char);
};
}

if (!String.prototype.titleCase) {
    String.prototype.titleCase = function () {
        var splitStr = this.toLowerCase().split(' ');
        for (var i = 0; i < splitStr.length; i++) {
            // You do not need to check if i is larger than splitStr length, as your for does that for you
            // Assign it back to the array
            splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
        }
        // Directly return the joined string
        return splitStr.join(' ');
    }
}

/**
 * Extend the Array object
 * @param candid The string to search for
 * @returns Returns the index of the first match or -1 if not found
*/
if (!Array.prototype.searchFor) {
    Array.prototype.searchFor = function(candid) {
        for (var i=0; i<this.length; i++)
            if (this[i].indexOf(candid) == 0)
                return i;
        return -1;
    };
}

if (!Date.prototype.addDays) {
    Date.prototype.addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    }
}