﻿$(document).ready(function () {
    if ($.validationEngineLanguage != undefined) {
        $.validationEngineLanguage.allRules["date"] = {
            "regex": /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/,
            "alertText": "* Invalid date, must be in dd/mm/yyyy format"
        };

        $.validationEngineLanguage.allRules["time"] = {
            "regex": /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])?$/,
            "alertText": "* Invalid Time"
        };
    }
});

function PathCombine(str1, str2) {
    if (str1 == undefined)
        str1 = '';
    if (str2 == undefined)
        str2 = '';
    if (!str1.endsWith("/"))
        str1 = str1 + '/';
    if (str2.startsWith("/"))
        str2 = str2.substring(0, str2.length - 1);
    return str1 + str2;
}
String.prototype.startsWith = function (str) {
    return this.match("^" + str) == str;
}
String.prototype.endsWith = function (str) {
    return this.match(str + "$") != null;
}
function padzero(i) {
    if (i < 10) return "0" + i
    return i
}
function pad2zeros(i) {
    if (i < 10) return "0" + i
    return i
}
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}
Date.prototype.toMSJSON = function () {
    var d = this;
    var dAsISOString = d.getFullYear() + '-' + padzero(d.getMonth() + 1) + '-' +
                   padzero(d.getDate()) + 'T' + padzero(d.getHours()) + ':' +
                   padzero(d.getMinutes()) + ':' + padzero(d.getSeconds()) + '.' +
                   pad2zeros(d.getMilliseconds()); // +'Z';
    return dAsISOString;
};

$.fn.InitDate = function (pin) {
    pin = $.extend(true, {
        showOn: "button",
        buttonImage: "Themes/smoothness/images/calendar.gif",
        buttonImageOnly: true,
        showAnim: "slide",
        dateFormat: "dd/mm/yy",
        onSelect: function () {
            $(this).blur();
        }
    }, pin || {});
    this.datepicker(pin);
    this.change(function () {
        var $dp = $(this);
        var val = $dp.val();
        if (Date.parseExact(val, "d/M/yyyy") == undefined)
            val = "";
        $dp.datepicker("setDate", val);
    });
    var picker = this;
    setTimeout(function () {
        picker.Watermark("dd/mm/yyyy");
    }, 0);

    return this;
}
$.fn.AutoDateRange = function (toId) {
    var fromId = this;
    this.datepicker("option", "beforeShow", function (input, inst) {
        var val = $(toId).val();
        if (val == "dd/mm/yyyy")
            $(this).datepicker("option", "maxDate", "");
        else
            $(this).datepicker("option", "maxDate", val);
    });
    $(toId).datepicker("option", "beforeShow", function (input, inst) {
        var val = $(fromId).val();
        if (val == "dd/mm/yyyy")
            $(this).datepicker("option", "minDate", "");
        else
            $(this).datepicker("option", "minDate", val);
    });
}
$.fn.AutoSelectRange = function (toId) {
    var $fromId = this;
    var $toId = $(toId);
    $fromId.change(function () {
        var fromVal = $(this).val();
        $toId.each(function () {
            var toVal = $(this).val();
            for (var i = 0; i < this.length; i++) {
                var thisVal = $(this[i]).val();
                if (fromVal >= thisVal) {
                    $(this[i]).attr("disabled", "true");
                    if (toVal == thisVal)
                        var selectAgain = true;
                }
                else {
                    $(this[i]).removeAttr("disabled");
                    if (selectAgain) {
                        $(this).val(thisVal);
                        selectAgain = false;
                    }
                }
            }
        });
    });
    $toId.change(function () {
        var toVal = $(this).val();
        $fromId.each(function () {
            var fromVal = $(this).val();
            for (var i = this.length - 1; i >= 0; i--) {
                var thisVal = $(this[i]).val();
                if (toVal <= thisVal) {
                    $(this[i]).attr("disabled", "true");
                    if (fromVal == thisVal)
                        var selectAgain = true;
                }
                else {
                    $(this[i]).removeAttr("disabled");
                    if (selectAgain) {
                        $(this).val(thisVal);
                        selectAgain = false;
                    }
                }
            }
        });
    });
}
$.fn.InitButton = function (icon) {
    if (icon)
        $(this).button({ icons: { primary: icon} });
    else
        $(this).each(function () {
            $(this).button({ icons: { primary: $(this).attr("primary")} });
        });
}
$.fn.InitTabs = function (opt) {
    opt = $.extend(true, {
        spinner: 'Loading...',
        ajaxOptions: {
            cache: false,
            error: function (xhr, status, index, anchor) {
                $(anchor.hash).html(
						"Couldn't load this tab. We'll try to fix this as soon as possible.");
            }
        },
        load: function (e, ui) {
            $(ui.panel).find(".loading-icon .tab").remove();
        },
        select: function (e, ui) {
            var $panel = $(ui.panel);

            if ($panel.is(":empty")) {
                var $loading = $("<div/>");
                $loading.addClass("loading-icon tab");
                $panel.append($loading);
            }
        }
    }, opt || {});
    this.tabs(opt);
}
$.fn.InitDialogForm = function (opt, oncommit, saveBtnText) {
    if (saveBtnText == undefined) {
        saveBtnText = "Save";
    }
    opt = $.extend(true, {
        autoOpen: false,
        height: 300,
        width: 450,
        modal: true,
        closeOnEscape: true,
        buttons: {
            Save: {
                text: saveBtnText,
                primary: "ui-icon-disk",
                click: function () {
                    if (oncommit != undefined)
                        oncommit($("form", this).serializeObject());
                }
            },
            Cancel: {
                text: "Cancel",
                primary: "ui-icon-cancel",
                click: function () {
                    $(this).dialog("close");
                }
            }
        },
        close: function () {
        }
    }, opt || {});
    this.dialog(opt);
}
$.fn.AutoGrid = function (pin, footer, editform, addform, deleteform) {
    var $tbl = this;

    var $loading = $("<div/>").insertAfter($tbl);
    $loading.addClass("loading-icon");

    var sidx = pin.sortname || "";
    var sord = pin.sortorder || "";
    var page = pin.page || 1;
    var rows = pin.rows || pin.rowNum || 10;
    if (typeof pin.postData == "object")
        pin.postData = $.prepareServiceData(pin.postData);
    var data = $.extend(true, { sidx: sidx, sord: sord, page: page, rows: rows }, pin.postData || {});
    $.CallService(
    {
        url: pin.url,
        data: data,
        success: function (result) {
            $loading.remove();

            if (footer != false) {
                var div = $("<div/>").insertAfter($tbl);
                div.attr("id", $tbl.attr("id") + "_pgr");
                div.addClass($tbl.attr("class"));
                div.attr("style", "text-align: center;");
            }
            result.length = result.records;

            $(result.colModel).each(function () {
                InitColModel(this);
            });

            pin = $.extend(true, {
                datatype: "jsonstring",
                mtype: "POST",
                datastr: result,
                colNames: result.colName,
                colModel: result.colModel,
                rowNum: 10,
                viewrecords: true,
                imgpath: "Css/Themes/Images/images",
                width: 970,
                height: "100%",
                pager: div,
                sortname: "",
                sortorder: "",
                lastsort: -1, //rfeng: fix bugs for order of first columns index
                gridComplete: function () {
                    if (result.gridComplete != undefined)
                        eval(result.gridComplete);
                }
            }, pin || {});

            if (pin.rowList == undefined)
                pin.rowList = [5, 10, 20, 50];

            $tbl.jqGrid(pin);

            if (footer != false) {
                footer = $.extend(true, { edit: false, add: false, del: false, search: false }, footer || {});
                editform = $.extend(true, editform || {});
                addform = $.extend(true, addform || {});
                deleteform = $.extend(true, deleteform || {});

                $tbl.jqGrid('navGrid', "#" + div.attr("id"), footer, editform, addform, deleteform);
                //                if (addform == undefined)
                //                    $tbl.jqGrid('navGrid', "#" + div.attr("id"), footer, editform);
                //                else {
                //                    addform = $.extend(true, addform || {});
                //                    $tbl.jqGrid('navGrid', "#" + div.attr("id"), footer, editform, addform);
                //                } 
            }
            $tbl.jqGrid('setGridParam', { datatype: 'json' });
            $("#gview_" + $tbl.attr("id") + " > .ui-jqgrid-titlebar").hide();
        },
        error: function (result) {
            alert(result.responseText.split("<title>")[1].split("</title>")[0]);
        }
    });
}
function InitDatePicker(cellvalue, options, rowObject) {
    setTimeout(function () { $('#' + options.id).InitDate(); }, 0);
    return "<input type=text value='" + cellvalue + "' />";
}
function DateValue(sender, act, tmp) {
    if (act == "set") {
        sender.val(tmp);
        sender.blur();
    }
    else
        return sender.val();
}
function InitColModel(cm) {
    for (var i in cm) {
        if (typeof cm[i] == "string") {
            if (cm[i].startsWith("function:")) {
                var methodName = cm[i].replace("function:", "");
                var method = window[methodName];
                if (method != undefined && $.isFunction(method))
                    cm[i] = method;
            }
        }
        else
            InitColModel(cm[i]);
    }
}
$.fn.GetRowId = function () {
    var item = this.parent();
    if (item.is("TR")) {
        if (item.hasClass("FormData"))
            return $("#id_g").val();
        else
            return item.attr("id");
    }
    else {
        return item.GetRowId();
    }
}
$.fn.ReloadGrid = function (url, pin) {
    pin.postData = $.prepareServiceData(pin.postData);
    pin = $.extend({
        url: url,
        page: 1
    }, pin || {});
    this.jqGrid('setGridParam', pin).trigger("reloadGrid");
}

$.fn.Create = function (tag, pin, html) {
    return this.CreateElement(tag, pin, html);
}
$.fn.CreateElement = function (tag, pin, html) {
    var doc = this[0];
    var ctrl = $(doc.createElement(tag));
    if (pin != undefined)
        for (var i in pin)
            ctrl.attr(i, pin[i]);
    if (html != undefined)
        ctrl.html(html);
    return ctrl;
}
$.fn.Watermark = function (text) {
    if (text == undefined)
        return this.attr("watermark");
    this.attr("watermark", text);
    this.focus(function () {
        $(this).filter(function () {
            return $(this).val() == "" || $(this).val() == $(this).attr("watermark");
        }).removeClass("watermarkOn").val("");
    });
    this.blur(function () {
        if ($(this).val() == "" || $(this).val() == $(this).attr("watermark"))
            $(this).addClass("watermarkOn").val($(this).attr("watermark"));
        else
            $(this).removeClass("watermarkOn");
    });
    this.blur();
}
$.fn.JsonDate = function (dateStr) {
    return eval('new' + dateStr.replace(/\//g, ' '));
}
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$.fn.dropdownlist = function (list) {
    var options = this;
    options.empty();
    $(list).each(function () {
        options.append($("<option />").val(this.ID).html(this.Description));
    });
};
$.fn.cloneObj = function () {
    var result = {};
    var obj = this[0];
    for (var i in obj) {
        var value = obj[i];
        if (value != undefined && typeof value == "object") {
            if (value.length == undefined) {
                if ($.isFunction(value.getTime))
                    value = value.clone();
                else
                    value = $(value).cloneObj();
            }
            else {
                var arr = [];
                $(value).each(function () {
                    arr.push($(this).cloneObj());
                });
                value = arr;
            }
        }
        result[i] = value;
    }
    return result;
}
$.fn.hasScrollBar = function () {
    return this.get(0).scrollHeight > this.height();
};
$.fn.getParentContext = function () {
    return this.getParentData("DataContext");
};
$.fn.getParentData = function (tag) {
    var $parent = this.parent();
    if ($parent.length > 0) {
        var data = $parent[0][tag];
        if (data == undefined)
            return $parent.getParentData(tag);
        else
            return data;
    }
    else
        return undefined;
};
$.extend({
    getUrlVars: function () {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            var hash0 = unescape(hash[0]);
            var hash1 = unescape(hash[1]);
            vars.push(hash0);
            vars[hash0] = hash1;
        }
        return vars;
    },
    getUrlVar: function (name) {
        return $.getUrlVars()[name];
    },
    convertJSONDate: function (date) {
        //here we will try to extract the ticks from the Date string in the "value" fields of JSON returned data
        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(date);
        if (a) {
            var date = new Date(parseInt(a[1], 10));
            try {
                if (serverTimezoneOffset != undefined && serverTimezoneOffset != 0)
                    date.add({ hours: serverTimezoneOffset / 60 });
            }
            catch (ex) { }
        }
        return date;
    },
    convertJSON: function (data) {
        if (typeof data == "string") {
            var rvalidchars = /^[\],:{}\s]*$/,
            rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	        rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	        rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
            if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
                data = $.parseJSON(data);
            }
        }

        for (var key in data) {
            var value = data[key];
            if (value != null) {
                if (value != undefined && typeof value == "object")
                    this.convertJSON(value);
                else if (value.toString().indexOf('Date') >= 0) {
                    data[key] = $.convertJSONDate(value);
                }
            }
        }
        return data;
    },
    prepareServiceData: function (oriData) {
        if (oriData == undefined)
            return {};

        var data = {};
        for (var i in oriData) {
            var value = oriData[i];
            if (typeof value == "object") {
                if (value != undefined && value.getTime != undefined)
                    data[i] = value.toMSJSON(); //value.toString("d/M/yyyy HH:mm:ss tt"); // 
                else
                    data[i] = $.prepareServiceData(value);
            }
            else
                data[i] = value;
        }

        return data;
    },
    CallService: function (pin) {
        if (typeof pin.data == "object")
            pin.data = $.prepareServiceData(pin.data);
        pin = $.extend(true, {
            url: "",
            type: "POST",
            //        contentType: "application/json; charset=utf-8",
            dataType: "text",
            data: {},
            success: function (result) {
            },
            failure: function (result) {
                alert("there is an unhandled error! " + JSON.stringify(result).split("<title>")[1].split("</title>")[0]);
            },
            error: function (result) {
                alert("there is an unhandled error! " + JSON.stringify(result).split("<title>")[1].split("</title>")[0]);
            }
        }, pin || {});
        var success = pin.success;
        pin = $.extend(true, pin, {
            success: function (result) {
                result = $.convertJSON(result);
                success(result);
            }
        });
        $.ajax(pin);
    },
    findDataContext: function (control) {
        if (control.DataContext == undefined) {
            var parent = control.parent();
            if (parent.length > 0)
                return $.findDataContext(parent);
        }
        else
            return control.DataContext;
    },
    today: function () {
        var date = new Date();
        try {
            if (serverTimezoneOffset != undefined && serverTimezoneOffset != 0)
                date.add({ hours: serverTimezoneOffset / 60 });
        }
        catch (ex) { }
        return date;
    },
    dateDiffBetween: function (date1, date2, getTotal) {
        var milisec = date2.getTime() - date1.getTime();
        var one_sec = 1000;
        var one_min = one_sec * 60;
        var one_hour = one_min * 60;
        var one_day = one_hour * 24;
        if (getTotal)
            return {
                "days": Math.floor(milisec / one_day),
                "hours": Math.floor(milisec / one_hour),
                "mins": Math.floor(milisec / one_min),
                "secs": Math.floor(milisec / one_sec),
                "milisecs": Math.floor(milisec)
            };
        else {
            return {
                "day": Math.floor(milisec / one_day),
                "hour": Math.floor(milisec % one_day / one_hour),
                "min": Math.floor(milisec % one_hour / one_min),
                "sec": Math.floor(milisec % one_min / one_sec),
                "milisec": Math.floor(milisec % one_sec)
            }
        }
    },
    redirectTo: function (url) {
        window.top.location.href = url;
    },
    showDateTime: function (d) {
        var t = $.today();
        var diff = $.dateDiffBetween(d, t);
        if (diff.day >= 1)
            return d.toString("d MMM yyyy");
        else if (diff.hour >= 1)
            return d.toString("H:mm");
        else if (diff.min > 1)
            return diff.min + " minutes ago";
        else if (diff.min == 1)
            return diff.min + " minute ago";
        else
            return "Few seconds ago";
    },
    loadJS: function (root, js, ended) {
        var jqCount = 0;
        for (var i = 0; i < js.length; i++) {
            var name = root + js[i];
            if ($("script[src*='" + name + "']").length == 0) {
                $.getScript(name, function () {
                    jqCount = jqCount + 1;
                    if (jqCount == js.length) {
                        ended();
                    }
                });
            }
            else {
                jqCount = jqCount + 1;
            }
        }
        if (jqCount == js.length)
            ended();
    }
});
