﻿
String.prototype.startsWith = function(str) {
    if (str == "|" && "|" == this.charAt(0)) return true;
    return (this.match("^" + str) == str)
};
String.prototype.endsWith = function(str) {
if (str == "|" && "|" == this.charAt(this.length - 1)) return true;
    return (this.match(str + "$") == str)
};
var urlParams = {};
(function() {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();
function getQueryStringParameter(name) {
    if (name in urlParams) {
        return urlParams[name];
    }
    return null;
}
function getAppPrefix() {
    var url = location.href;
    if (url.toUpperCase().startsWith("http://localhost".toUpperCase())) {
        if (url.toUpperCase().startsWith("http://localhost/MFH34/MyFloridaHouse/".toUpperCase()))
            return "/MFH34/MyFloridaHouse/"
    }
    if (url.toUpperCase().startsWith("http://ws-dev-05690".toUpperCase())) {
        if (url.toUpperCase().startsWith("http://ws-dev-05690/MFH34/MyFloridaHouse/".toUpperCase()))
            return "/MFH34/MyFloridaHouse/"
    }
    else
        return "/"
};

var prefix = getAppPrefix();

function getBaseURL() {
    var url = location.href; // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (url.startsWith('http://localhost/MFH34/MyFloridaHouse')) {
        return 'http://localhost/MFH34/MyFloridaHouse';
    }
    if (baseURL.indexOf('http://localhost') != -1 ||
    baseURL.indexOf('http://ws-dev-05690') != -1) {
        // Base Url for localhost
        var url = location.href; // window.location.href;
        var pathname = location.pathname; // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

};

function includeScript(filename) {
    var isUndefined = function(obj) {
        return (obj == null || (typeof obj == 'undefined') || (typeof obj == 'Undefined'));
    }
    if (isUndefined(filename)) return;
    var vDir = "";
    if (!filename.startsWith("http"))
        vDir = prefix;
    if (filename.startsWith("/"))
        filename = filename.substring(1);
    var fullfilename = vDir + filename;
    if (document.getElementsByTagName("head").length == 1) {
        var header = document.getElementsByTagName("head")[0];
        if (header.getElementsByTagName("script").length > 0) {
            var scriptArray = header.getElementsByTagName("script");
            var x = 0;
            for (x = 0; x < scriptArray.length; x++) {
                var tmpSrc = scriptArray[x].getAttribute("src");
                if (isUndefined(tmpSrc)) continue;
                if (tmpSrc.toUpperCase() == fullfilename.toUpperCase()) {
                    return;
                }
            }
        }
    }

    if (fullfilename.endsWith("js")) { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", fullfilename)
    }
    else
        if (fullfilename.endsWith("css")) { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", fullfilename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}



jQuery.Id = function(idString) {
    var s = "";
    try {
        var arrstring = idString.split(",");
        $(arrstring).each(function(index) {
            s = s + "#" + $.trim(this);
            if (index != (arrstring.length - 0))
                s = s + ",";

        });
    }
    catch (e) {
        s = null
    }
    return $(s);
};

jQuery.Class = function(idString) {
    var s = "";
    try {
        var arrstring = idString.split(",");
        $(arrstring).each(function(index) {
            s = s + "." + $.trim(this);
            if (index != (arrstring.length - 0))
                s = s + ",";

        });
    }
    catch (e) {
        s = null
    }
    return $(s);
};

jQuery.supplant = function(str, o) {
    return str.replace(/{([^{}]*)}/g, function(a, b) {
        var r = o[b];

        return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
};

jQuery.GetXMLfromString = function(xmlString) {

    if (typeof xmlString != 'string')
        return xmlString;
    var xml;

    if ($.browser.msie) {
        xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.async = false;
        xml.loadXML(xmlString);
    }
    else {
        xml = xmlString;
    }
    return xml;
};
jQuery.GetCurrentURLSiteFolder = function() {
    var URL = window.location.href;
    var iIndex = URL.lastIndexOf("/");
    if (iIndex != -1) {
        return URL.substring(0, iIndex + 1);
    }

    return null;
}
jQuery.GetXMLfromDomElement = function(domElement) {
    var xml;

    if ($.browser.msie) {
        xml = domElement.xml;
    }
    else
        if ($.browser.mozilla) {
        var ret = "<" + domElement.tagName;
        for (var i = 0; i < domElement.attributes.length; i++) {
            var attr = domElement.attributes[i];
            ret += " " + attr.name + "=\"" + attr.nodeValue.replace(/"/, "\"") + "\"";
        }
        ret += ">";
        ret += domElement.innerHTML + "</" + domElement.tagName + ">";
        xml = ret;

    }
    else {
        xml = domElement.outerHTML;
    }
    return xml;
};
jQuery.GetChildrenOfFirstElement = function(xmlObj) {
    var children;

    if ($.browser.msie) {
        // xmlObj must be ActiveXObject("Microsoft.XMLDOM")
        // for this to work correctly
        children = $(xmlObj).children().first().children();
    }
    else {
        children = $($(xmlObj).children());
    }
    return children;
};
jQuery.pausecomp = function(millis) {
    var date = new Date();
    var curDate = null;

    do {
        curDate = new Date();
    }
    while (curDate - date < millis);
};

jQuery.log = function(s) {
    try {
        if (typeof console != "undefined" && typeof console.log != "undefined")
            console.log(s);
        //else alert(s);
    } catch (ex) { }
};
jQuery.IsUndefined = function(obj) {
    return ((typeof obj == 'undefined') || (typeof obj == 'Undefined'));
}
jQuery.IsUndefinedOrNull = function(obj) {
    return (obj == null || (typeof obj == 'undefined') || (typeof obj == 'Undefined'));
}
jQuery.IsUndefinedNullOrEmptyString = function(obj) {
    return (obj == null || (typeof obj == 'undefined') || (typeof obj == 'Undefined') || obj == "");
}
var urlParams = {};
(function() {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();

jQuery.OperationDuration = function(LogToConsole, MessagePrefix) {

    function _myClass(LogToConsole, MessagePrefix) {
        if ($.IsUndefined(LogToConsole))
            var LogToConsole = true;
        if ($.IsUndefined(MessagePrefix))
            var MessagePrefix = "Operation Duration: ";
        var _self = this;
        var _nMS = null;
        var _dtEnd, _dtStart;

        this.Start = function() {
            _dtStart = new Date()

        }
        this.End = function() {
            _dtEnd = new Date();
            _nMS = _dtEnd.valueOf() - _dtStart.valueOf();
            if (LogToConsole) {
                $.log(MessagePrefix + ": " + _self.durationToString());
            }

        }
        this.GetDuration = function() {
            return _nMS;
        }

        this.durationToString = function() {
            var sReturn, sComp, nDur;

            nDur = _nMS % 1000;
            sComp = nDur.toString();
            while (sComp.length < 3)
                sComp = "0" + sComp;
            sReturn = "." + sComp + " seconds";

            // Strip off last component
            _nMS -= nDur;
            _nMS /= 1000;

            nDur = _nMS % 60;
            if (nDur)
                sReturn = nDur.toString() + sReturn;
            else
                sReturn = "0" + sReturn;

            // Strip off last component
            _nMS -= nDur;
            _nMS /= 60;

            nDur = _nMS % 60;
            sReturn = nDur.toString() + " minutes, and " + sReturn;

            // Strip off last component
            _nMS -= nDur;
            _nMS /= 60;

            return _nMS.toString() + " hours, " + sReturn;
        }
    }
    return new _myClass(LogToConsole, MessagePrefix);
}
jQuery.showDefaultModalMessagePanel = function(htmlmessage, panelWidth, clearAfterUse) {
    if ($.IsUndefinedNullOrEmptyString(panelWidth))
        var panelWidth = "400px";

    var p = prefix;
    if ($.IsUndefinedNullOrEmptyString(p))
        p = "/";
    var messageTemplate = "<div " +
    "style='background-color: white; color: black; border: solid thin black; width: {newwidth}; padding: 5px;'>" +
    "<img alt=\"close\" class='close' style=\"text-align: right; border: 0; float: right;\" src='" +
    p +
    "Images/close.png'></img>" +
    "<div style=\"padding: 5px;display: block;\" >{messageText}</div></div>";
    
    var message = $.supplant(messageTemplate, {
        messageText: htmlmessage,
        newwidth: panelWidth
    });
    $.showModalMessagePanel(message, clearAfterUse);
};
jQuery.RemoveSiteAddressFromString = function(s) {
    if ($.IsUndefinedOrNull(s))
        return s;
    if (s.startsWith("http")) {
        var sitefolder = $.GetCurrentURLSiteFolder();
        s = s.substring(sitefolder.length);
    }

    return s;

}
jQuery.clearModalMessagePanel = function() {

    var MessageTextDivID = "ModalMessageTextDivID";
    $.Id(MessageTextDivID).html("");
}
jQuery.showModalMessagePanel = function(htmlMessage, clearModalOnClose) {


    //Get the screen height and width   
    var maskHeight = $(document).height();
    var maskWidth = $(document).width();
    var MaskID = "ModalMessageMaskID";
    var MessageTextDivID = "ModalMessageTextDivID";

    if ($.Id(MaskID).length == 0) {
        var maskhtml = $.supplant('<div id="{maskid}" style="position:absolute; z-index:1000; background-color:#000; display:none;"></div>', {
            maskid: MaskID
        });
        $("body").append(maskhtml);
    }

    if ($.Id(MessageTextDivID).length == 0) {
        var messagedivhtml = $.supplant('<div id="{messagetextID}" style="position:absolute; display:none; z-index:1100;"></div>', {
            messagetextID: MessageTextDivID
        });
        $("body").append(messagedivhtml);
    }

    var id = $.Id(MessageTextDivID);
    id.html(htmlMessage);

    //Set height and width to mask to fill up the whole screen
    $.Id(MaskID).css({
        'width': maskWidth,
        'height': maskHeight,
        'top': 0,
        'left': 0
    });


    //transition effect        
    //        $.Id(MaskID).fadeIn(500);
    //        $.Id(MaskID).fadeTo("fast", 0.5);
    $.Id(MaskID).show();
    $.Id(MaskID).css("opacity", "0.5");
    //Get the window height and width   
    var winH = $(window).height();
    var winW = $(window).width();


    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        scrOfY = window.pageYOffset; scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft ||
             document.body.scrollTop)) {
        scrOfY = document.body.scrollTop; scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft ||
                 document.documentElement.scrollTop)) {
        scrOfY = document.documentElement.scrollTop; scrOfX = document.documentElement.scrollLeft;
    }


    $(id).css('top', winH / 2 - $(id).height() / 2 + scrOfY);
    $(id).css('left', winW / 2 - $(id).width() / 2 + scrOfX);

    //transition effect
    $(id).show();

    //if close button is clicked
    $('#' + MessageTextDivID + ' .close').click(function(e) {
        //Cancel the link behavior   
        e.preventDefault();
        $.Id(MaskID).hide();
        $.Id(MessageTextDivID).hide();

        if (clearModalOnClose)
            $.clearModalMessagePanel();
    });

    //if mask is clicked   
    $.Id(MaskID).click(function() {
        $(this).hide();
        $.Id(MessageTextDivID).hide();
        if (clearModalOnClose)
                $.clearModalMessagePanel();
    });

};



/*
highlight v3
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>
*/
jQuery.fn.highlight = function(pat, highLightClass) {
if (pat.substring(pat.length - 1) == "*")
        pat = pat.substring(0, pat.length - 1);

    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = null;
                spannode = node.ownerDocument.createElement('span');

                spannode.className = highLightClass;
                spannode.id = highLightClass + Math.floor(Math.random() * 300);
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);

                skip = 1;
            }
        }
        else
            if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.each(function() {
        innerHighlight(this, pat.toUpperCase());
    });
};

jQuery.fn.removeHighlight = function(highLightClass) {
    return this.find("span." + highLightClass).each(function() {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};


// great jquery pluggin by
// http://james.padolsey.com/javascript/special-scroll-events-for-jquery/
(function() {

    var special = jQuery.event.special, uid1 = 'D' + (+new Date()), uid2 = 'D' + (+new Date() + 1);

    special.scrollstart = {
        setup: function() {

            var timer, handler = function(evt) {

                var _self = this, _args = arguments;

                if (timer) {
                    clearTimeout(timer);
                }
                else {
                    evt.type = 'scrollstart';
                    jQuery.event.handle.apply(_self, _args);
                }

                timer = setTimeout(function() {
                    timer = null;
                }, special.scrollstop.latency);

            };

            jQuery(this).bind('scroll', handler).data(uid1, handler);

        },
        teardown: function() {
            jQuery(this).unbind('scroll', jQuery(this).data(uid1));
        }
    };

    special.scrollstop = {
        latency: 200,
        setup: function() {

            var timer, handler = function(evt) {

                var _self = this, _args = arguments;

                if (timer) {
                    clearTimeout(timer);
                }

                timer = setTimeout(function() {

                    timer = null;
                    evt.type = 'scrollstop';
                    jQuery.event.handle.apply(_self, _args);

                }, special.scrollstop.latency);

            };

            jQuery(this).bind('scroll', handler).data(uid2, handler);

        },
        teardown: function() {
            jQuery(this).unbind('scroll', jQuery(this).data(uid2));
        }
    };

})();

