﻿/////////////////////////////////////////////////////////
////////////////////// Include-Once /////////////////////
/////////////////////////////////////////////////////////

var included_files = new Array();

function include_once(script_filename)
{
    if (!in_array(script_filename, included_files))
    {
        included_files[included_files.length] = script_filename;
        include_dom(script_filename);
    }
}

function include_dom(script_filename)
{
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

/////////////////////////////////////////////////////////
////////////////////// In-Array /////////////////////////
/////////////////////////////////////////////////////////

function in_array(needle, haystack) {
    for (var i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            return true;
        }
    }
    return false;
}

/////////////////////////////////////////////////////////
///// Count occurences of character in string ///////////
/////////////////////////////////////////////////////////

String.prototype.count=function(s1) { 
	return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

/////////////////////////////////////////////////////////
//////////////// String Methods /////////////////////////
/////////////////////////////////////////////////////////

String.prototype.startsWith = function (str)
{
    return (this.match("^" + str) == str);
}

String.prototype.endsWith = function (str)
{
    return (this.match(str + "$") == str);
}

String.prototype.padLeft = function (padString, length)
{
    var str = this;
    var count = length - str.length;
    for (var i = 0; i < count; i++)
        str = padString + str;
    return str;
}

String.prototype.padRight = function (padString, length)
{
    var str = this;
    var count = length - str.length;
    for(var i = 0; i < count; i++)
        str = str + padString;
    return str;
}

/////////////////////////////////////////////////////////
////////////// Modified jQuery get-/postJSON ////////////
/////////////////////////////////////////////////////////

function GetJSON(ajaxUrl, onSuccess, onFailure) {
    $.ajax({
        //type: "GET",
        url: ajaxUrl,
        //contentType: "application/json; charset=utf-8",
        data: {},
        dataType: "json",
        success: onSuccess,
        error: onFailure
    });
}

function PostJSON(ajaxUrl, data, onSuccess, onFailure)
{
    $.ajax({
        type: "POST",
        url: ajaxUrl,
        data: data,
        dataType: "json",

        success: onSuccess,
        error: onFailure
    });
}

/////////////////////////////////////////////////////////
////////////// AutoExpand TextArea //////////////////////
/////////////////////////////////////////////////////////

function FitToContent(componentId, bottomPadding, allowShrink, maxHeight, minHeight) {
    //Find the component...
    var component;
    if (componentId && componentId.style)
        component = componentId;
    else
        component = document.getElementById(componentId);
    if (!component)
        return;
    
    if (component.scrollHeight > component.clientHeight) {
        //Grow to fit
        if (maxHeight)
            component.style.height = Math.min(component.scrollHeight + bottomPadding, maxHeight) + "px";
        else
            component.style.height = (component.scrollHeight + bottomPadding) + "px";
    }
    else if (allowShrink && component.scrollHeight < component.clientHeight) {
        //Shrink to fit
        if (minHeight)
            component.style.height = Math.max(component.scrollHeight + bottomPadding, minHeight) + "px";
        else
            component.style.height = (component.scrollHeight + bottomPadding) + "px";
    }
}


/////////////////////////////////////////////////////////
////////////////// AJAX Select //////////////////////////
/////////////////////////////////////////////////////////

function PopulateSelect(selectID, jsonSource, selectedVal, allowBlank, readOnly, onSuccess, onFailure) {
    if (typeof(allowBlank) == "undefined")
        allowBlank = false;
    if (typeof(readOnly) == "undefined")
        readOnly = false;
    
    var wasDisabled = $("#" + selectID).attr("disabled");
    $("#" + selectID).attr("disabled", "disabled");
    $("#" + selectID).html("<option selected='selected'>Loading...</option>");

    if (jsonSource != null && jsonSource != "") {
        GetJSON(jsonSource, function (data) {    //onSuccess
            var options = "";
            if (allowBlank && !readOnly)
                options += "<option value=''></option>";
            for (var i in data) {
                if (data[i].id == selectedVal)
                    options += "<option value='" + data[i].id + "' selected='selected'>" + data[i].value + "</option>";
                else if (!readOnly)
                    options += "<option value='" + data[i].id + "'>" + data[i].value + "</option>";
            }
            $("#" + selectID).html(options);

            if (!wasDisabled)
                $("#" + selectID).removeAttr("disabled");

            if (typeof (onSuccess) != "undefined")
                onSuccess(selectID);
        },
        function () {    //onFailure
            $("#" + selectID).html("<option selected='selected'>Error!</option>");

            //        if (!wasDisabled)
            //            $("#" + selectID).removeAttr("disabled");

            if (typeof (onFailure) != "undefined")
                onFailure(selectID);
        });
    }
    else {
        $("#" + selectID).html("");
        if (!wasDisabled)
            $("#" + selectID).removeAttr("disabled");
    }
}

/////////////////////////////////////////////////////////
////////////// jQuery AjaxSelect ////////////////////////
/////////////////////////////////////////////////////////

(function ($) {
    
    $.widget("ui.ajaxSelect", {
        options: {
            source: "",
            retainValue: true,
            allowBlank: true,
            readOnly: false,
            onloadsuccess: null,
            onloadfailure: null,
            onchange: null
        },
        reload: function() {
            if (this.options.source != null && this.options.source != "") {
                var selectedVal = this.element.val();
                var THIS = this;
                GetJSON(this.options.source, function (data) {    //onSuccess
                    var opts = "";
                    if (THIS.options.allowBlank && !THIS.options.readOnly)
                        opts += "<option value=''></option>";
                    for (var i in data) {
                        if (THIS.options.retainValue && data[i].id == selectedVal)
                            opts += "<option value='" + data[i].id + "' selected='selected'>" + data[i].value + "</option>";
                        else if (!THIS.options.readOnly)
                            opts += "<option value='" + data[i].id + "'>" + data[i].value + "</option>";
                    }
                    THIS.element.html(opts);

                    THIS.element.removeAttr("disabled");

                    if (THIS.options.onloadsuccess != null)
                        THIS.options.onloadsuccess(THIS.element);
                },
                function () {    //onFailure
                    THIS.element.html("<option selected='selected'>Error!</option>");
                    THIS.element.attr("disabled", "disabled");

                    if (THIS.options.onloadfailure != null)
                        THIS.options.onloadfailure(THIS.element);
                });
            }
            else {
                this.element.html("");
                this.element.attr("disabled", "disabled");
            }
        },
        value: function(v) {
            if(typeof(v) == 'undefined')
                return this.element.val();
            else
                this.element.val(v);
        },
//        _setOption: function(key, value) {
//            if(key == "source") {
//                this.options.source = value;
//                this.element.data("input").autocomplete("option", "source", value);
//            }
//        },
        _create: function () {
            this.reload();
        },
        destroy: function() {
            $.Widget.prototype.destroy.apply(this, arguments);
            //Local cleanup
        }
    });

})(jQuery);


/////////////////////////////////////////////////////////
////////////// jQuery ComboBox //////////////////////////
/////////////////////////////////////////////////////////

(function ($) {
    $.widget("ui.combobox", {
        options: {
            source: "",
            onchange: null,
            forceSelection: true
        },
        value: function(v) {
            if(v == null)
                return this.element.data("hidden").val();
            else
                this.element.data("hidden").val(v);
        },
        text: function(v) {
            if(v == null) {
                return this.element.data("input").val();
            }
            else {
                this.element.data("tempValue", v);
                this.element.data("input").val(v);
            }
        },
        width: function(v) {
            if(v == null) {
                return this.element.data("container").css("width");
            }
            else {
                var input = this.element.data("input");
                input.css("width", v - input.outerHeight());
                this.element.data("container").css("width", v);
            }
        },
        allowTyping: function(v) {
            if(v == null)
                return this.element.data("input").attr("readonly") == "true";
            else {
                if(v == true) {
                    this.element.data("input").attr("readonly", "true");
                }
                else {
                    this.element.data("input").attr("readonly", "false");
                }
            }
        },
        _setOption: function(key, value) {
            if(key == "source") {
                this.options.source = value;
                this.element.data("input").autocomplete("option", "source", value);
            }
            else if(key == "onchange") {
                this.options.onchange = value;
            }
            else if(key == "forceSelection") {
                this.options.forceSelection = value;
            }
        },
        _create: function () {
            this.element.wrap("<span style='position:relative; display:inline-block; width:" + this.element.css("width") + ";' />");
            var THIS = this;
            var select = this.element.hide();
            var hidden = $("<input type='hidden'>")
                    .insertAfter(select);
            var input = $("<input>")
					.insertAfter(select)
					.autocomplete({
					    source: this.options.source,
					    delay: 0,
					    minLength: 0,
                        select: function(event, ui) {
                            THIS.element.data("tempValue", ui.item.value);
                            hidden.val(ui.item.id);
                            input.val(ui.item.value);

                            var evObj = document.createEvent('HTMLEvents');
                            evObj.initEvent('change', true, true);
                            input.get(0).dispatchEvent(evObj);

                            if(THIS.options.onchange != null) {
                                THIS.options.onchange(ui.item.id, ui.item.value);
                            }
                        }
					})
                    .css("height", this.element.innerHeight())
                    .css("width", this.element.innerWidth() - this.element.outerHeight())
                    .css("position", "absolute")
                    .css("left", "0px")
                    .css("top", "0px")
                    .unbind("blur.autocomplete")
                    .keydown(function() {
                        THIS.element.data("tempValue", null);
                    })
                    .bind("blur", function() {
                        if(THIS.options.forceSelection == true) {
	                        var val = THIS.element.data("tempValue");
	                        if(typeof val === 'undefined' || val == null) {
                                val = '';

                                hidden.val("");
                                input.val("");
                                if(THIS.options.onchange != null) {
                                    THIS.options.onchange("", "");
                                }
                            }
	                        $(this).val(val);
                        }
                    })
					.addClass("ui-widget ui-widget-content ui-corner-left");
            var button = $("<button>&nbsp;</button>")
				.insertAfter(input)
				.button({
				    icons: {
				        primary: "ui-icon-triangle-1-s"
				    },
				    text: false
				})
                .attr("tabindex", "-1")
                .removeClass("ui-corner-all")
				.addClass("ui-corner-right ui-button-icon")
                .css("height", input.outerHeight())
                .css("width", input.outerHeight())
                .css("position", "absolute")
                .css("right", "0px")
                .css("top", "0px")
				.click(function () {
				    // close if already visible
				    if (input.autocomplete("widget").is(":visible")) {
				        input.autocomplete("close");
				        return false;
				    }

                    THIS.element.data("tempValue", null);
				    input.autocomplete("search", "");// input.val());
				    input.focus();

				    return false;
				});
            $("<div>")
                .insertAfter(input)
                .css("position", "relative")
                .css("left", "0px")
                .css("right", "0px")
                .css("width", "1px")
                .css("height", input.outerHeight());
            this.element.data("container", input.closest("span"));
            this.element.data("hidden", hidden);
            this.element.data("input", input);
            this.element.data("button", button);
            this.element.data("original", select);
            $("body:not(.ui-autocomplete)").live('click', function () { input.autocomplete ("close"); });
        },
        destroy: function() {
            this.element.data("input").autocomplete("destroy");
            this.element.data("container").children().not(this.element.data("original")).remove();
            this.element.data("original").unwrap().show();
        }
    });
})(jQuery);


/////////////////////////////////////////////////////////
////////////// ConfirmDelete ////////////////////////////
/////////////////////////////////////////////////////////

function ConfirmDelete(text)
{
    var result = prompt(text, '');
    if (result == "DELETE")
    {
        return true;
    }
    else
    {
        return false;
    }
}


/////////////////////////////////////////////////////////
////////////// CountDown ////////////////////////////////
/////////////////////////////////////////////////////////

function Countdown(elementID, secondsRemaining, onFinish)
{
    if (secondsRemaining == 0)
    {
        if (!onFinish)
            eval("location.href = 'maintenance.aspx'");
        else
            onFinish();
    }
    else
    {
        var component;
        if (elementID && elementID.style)
            component = elementID;
        else
            component = document.getElementById(elementID);
        if (!component)
            return;

        var seconds = Math.floor(secondsRemaining % 60);
        var minutes = Math.floor((secondsRemaining / 60) % 60);
        var hours = Math.floor((secondsRemaining / 3600));
        
        var str = '';
        
        if (hours > 0)
            str += hours + " hours, ";
        if (minutes > 0 || hours > 0)
            str += minutes + " minutes, ";
        str += seconds + " seconds";

        //$('#' + elementID).html(str);
        component.innerHTML = str;

        window.setTimeout('Countdown(' + component.id + ',' + (secondsRemaining - 1) + ')', 990);
    }
}


/////////////////////////////////////////////////////////
////////////// Get Full Axapta //////////////////////////
/////////////////////////////////////////////////////////

function GetFullAxapta(field, prefix)
{
    var component;
    component = document.getElementById(field);
    if (!component)
        return;

    if (!prefix)
        prefix = 'w1';

    if (component.value.length <= 6 && IsInteger(component.value))
    {
        component.value = prefix + '_' + padding_left(component.value, '0', 6);
    }
}


/////////////////////////////////////////////////////////
////////////// jQuery Portlets //////////////////////////
/////////////////////////////////////////////////////////

$(function () {
//    $(".column").sortable({
//        connectWith: '.column'
//    });

    $(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		    .find(".portlet-header")
			    .addClass("ui-widget-header ui-corner-all")
			    //.prepend('<span class="ui-icon ui-icon-minusthick"></span>')
			    .end()
		    .find(".portlet-content");

//    $(".portlet-header .ui-icon").click(function () {
//        $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
//        $(this).parents(".portlet:first").find(".portlet-content").toggle();
//    });

//    $(".column").disableSelection();
});


/////////////////////////////////////////////////////////
////////////// Utility Functions ////////////////////////
/////////////////////////////////////////////////////////

function padding_left(s, c, n) {
    if (!s || !c || s.length >= n) {
        return s;
    }

    var max = (n - s.length) / c.length;
    for (var i = 0; i < max; i++) {
        s = c + s;
    }

    return s;
}

function IsInteger(strString) {
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}

/////////////////////////////////////////////////////////
/////////////// Cookie Functions ////////////////////////
/////////////////////////////////////////////////////////

function SaveCookie(name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function LoadCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function EraseCookie(name)
{
    SaveCookie(name, "", -1);
}
