﻿if (typeof(jQuery) != "undefined") {
    jQuery.timer = function(interval, callback) {
        /**
        *
        * timer() provides a cleaner way to handle intervals  
        *
        *	@usage
        * $.timer(interval, callback);
        *
        *
        * @example
        * $.timer(1000, function (timer) {
        * 	alert("hello");
        * 	timer.stop();
        * });
        * @desc Show an alert box after 1 second and stop
        * 
        * @example
        * var second = false;
        *	$.timer(1000, function (timer) {
        *		if (!second) {
        *			alert('First time!');
        *			second = true;
        *			timer.reset(3000);
        *		}
        *		else {
        *			alert('Second time');
        *			timer.stop();
        *		}
        *	});
        * @desc Show an alert box after 1 second and show another after 3 seconds
        *
        * 
        */

        var interval = interval || 100;

        if (!callback)
            return false;

        _timer = function(interval, callback) {
            this.stop = function() {
                clearInterval(self.id);
            };
            this.internalCallback = function() {
                callback(self);
            };
            this.reset = function(val) {
                if (self.id)
                    clearInterval(self.id);

                var val = val || 100;
                this.id = setInterval(this.internalCallback, val);
            };
            this.interval = interval;
            this.id = setInterval(this.internalCallback, this.interval);
            var self = this;
        };
        return new _timer(interval, callback);
    };

    jQuery.stringToXML = function(string) {
        var browserName = navigator.appName;
        var doc;
        if (browserName == 'Microsoft Internet Explorer') {
            doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.async = 'false'
            doc.loadXML(string);
        } else {
            doc = (new DOMParser()).parseFromString(string, 'text/xml');
        }
        return doc;
    };

    jQuery.xmlToString = function(xmlDoc) {
        var string;
        if (window.ActiveXObject) {
            string = xmlDoc.xml;
        }
        else {
            string = (new XMLSerializer()).serializeToString(xmlDoc);
        }
        return string;
    };

    $j = jQuery.noConflict();
    $ = function(elementID) { return document.getElementById(elementID) };
};

// String methods
Array.prototype.clear = function() {
    var me = [];
    return me;
};
String.prototype.trim = function(str) {
    var me = this.toString();
    if (!str) { str = " " };
    if (me.length) {
        while (me.length && (me.indexOf(str) == 0 || me.lastIndexOf(str) == me.length - str.length)) {
            if (me.indexOf(str) == 0) { me = me.substring(str.length) };
            if (me.lastIndexOf(str) == me.length - str.length) { me = me.substring(0, me.length - str.length) };
        };
    };
    return me;
};
String.prototype.lTrim = function(str) {
    var me = this.toString();
    if (!str) { str = " " };
    if (me.length) {
        while (me.length && me.indexOf(str) == 0) {
            if (me.indexOf(str) == 0) { me = me.substring(str.length) };
        };
    };
    return me;
};
String.prototype.rTrim = function(str) {
    var me = this.toString();
    if (!str) { str = " " };
    if (me.length) {
        while (me.length && me.lastIndexOf(str) == me.length - str.length) {
            if (me.lastIndexOf(str) == me.length - str.length) { me = me.substring(0, me.length - str.length) };
        };
    };
    return me;
};
String.prototype.toFloat = function() {
    return parseFloat(this);
};
String.prototype.toInt = function() {
    return parseInt(this);
};
String.prototype.contains = function(str) {
    if (this.indexOf(str) > -1) { return true };
    return false;
};
Number.prototype.toCurrency = function() {
    var i = parseFloat(this);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return parseFloat(s);
};

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
          this[from] === elt)
                return from;
        }
        return -1;
    };
}
//String.prototype.replace = function(find, change) {
//    if (!find) { return this.toString() };
//    if (!change) { change = "" };
//    var me = this.toString();
//    for (var i = 0; i < me.length; i++) {
//        if (me.substring(i, i + find.length) == find) {
//            me = me.substring(0, i) + change + me.substring(i + find.length, me.length);
//            i -= (find.length - change.length);
//        };
//    };
//    return me;
//};
var BrowserDetect = {
    "browser": null, // browser name
    "version": null, // browser version
    "OS": null, 	// operating system name
    "init": function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    "searchString": function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    "searchVersion": function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    "dataBrowser": [
		{
		    "string": navigator.vendor,
		    "subString": "Apple",
		    "identity": "Safari"
		},
		{
		    "prop": window.opera,
		    "identity": "Opera"
		},
		{
		    "string": navigator.vendor,
		    "subString": "iCab",
		    "identity": "iCab"
		},
		{
		    "string": navigator.vendor,
		    "subString": "KDE",
		    "identity": "Konqueror"
		},
		{
		    "string": navigator.userAgent,
		    "subString": "Firefox",
		    "identity": "Firefox"
		},
		{	// for newer Netscapes (6+)
		    "string": navigator.userAgent,
		    "subString": "Netscape",
		    "identity": "Netscape"
		},
		{
		    "string": navigator.userAgent,
		    "subString": "MSIE",
		    "identity": "Explorer",
		    "versionSearch": "MSIE"
		},
		{
		    "string": navigator.userAgent,
		    "subString": "Gecko",
		    "identity": "Mozilla",
		    "versionSearch": "rv"
		},
		{ 	// for older Netscapes (4-)
		    "string": navigator.userAgent,
		    "subString": "Mozilla",
		    "identity": "Netscape",
		    "versionSearch": "Mozilla"
		}
	],
    "dataOS": [
		{
		    "string": navigator.platform,
		    "subString": "Win",
		    "identity": "Windows"
		},
		{
		    "string": navigator.platform,
		    "subString": "Mac",
		    "identity": "Mac"
		},
		{
		    "string": navigator.platform,
		    "subString": "Linux",
		    "identity": "Linux"
		}
	]

};
BrowserDetect.init();
function stopBubbling(ev) {
    if (!ev) { ev = ev || window.event };
    if (ev) {
        if (ev.stopPropagation) { ev.stopPropagation() }
        else if (ev.preventBubble) { ev.preventBubble() }
        else { ev.cancelBubble = true };
    };
};
var EventHandler = {
    "add": function(elem, type, func, bubl) {
        if (BrowserDetect.browser == "Opera" && elem == window) { elem = document };
        try {
            if (!elem.__handlers) { elem.__handlers = {} };
        } catch (x) {
            alert("ERROR:  " + elem + "___" + func + "____" + x.message);
        }
        if (!elem.__handlers[type]) {
            elem.__handlers[type] = [func];
        } else {
            elem.__handlers[type].push(func);
        };
        elem.__handlers[type + "_bubble"] = (!bubl) ? false : true;
        if (elem.addEventListener) {
            elem.removeEventListener(type, EventHandler.process, true);
            elem.addEventListener(type, EventHandler.process, bubl);
        } else if (elem.attachEvent) {
            elem["on" + type] = EventHandler.process;
        };
    },
    "remove": function(elem, type, func) {
        if (!type) {
            if (elem.__handlers) {
                for (var each in elem.__handlers) {
                    if (elem.removeEventListener) {
                        elem.removeEventListener(each, EventHandler.process, true);
                    } else {
                        elem["on" + each] = null;
                        delete elem.__handlers[each];
                    };
                };
                try {
                    elem.__handlers = null;
                    delete elem.__handlers;
                } catch (x) { /* not working in ie? */ };
            };
        } else if (func == null || typeof func == "undefined" || (elem.__handlers && (!elem.__handlers[type] || elem.__handlers[type].length <= 0))) {
            if (elem.__handlers) {
                if (elem.removeEventListener) {
                    elem.removeEventListener(type, EventHandler.process, true);
                    //					if (type == "mouseover") {
                    //						elem.removeEventListener("mouseover",EventHandler.process,true); 
                    //						alert ("AFTER "+EventHandler.process) 
                    //					};
                } else {
                    elem["on" + type] = null;
                    delete elem.__handlers[type];
                };
            };
            elem["on" + type] = null;
        } else if (elem.__handlers && elem.__handlers[type]) {
            if (typeof func == "function") {
                for (var i = 0, f; f = elem.__handlers[type][i]; i++) {
                    if (f == func) {
                        f = elem.__handlers[type][i] = null;
                        elem.__handlers[type].splice(i, 1);
                        break;
                    };
                };
            } else if (typeof func == "number") {
                elem.__handlers[type].splice(func, 1);
            } else if (typeof func == "string") {
                for (var i = 0, f; f = elem.__handlers[type][i]; i++) {
                    var name = f.toString().replace(" ", "").substring(8, name.indexOf("("));
                    if (func == name || (func == "" && name == "anonymous")) {
                        f = elem.__handlers[type][i] = null;
                        elem.__handlers[type].splice(i, 1);
                        i--;
                    };
                };
            };
        };
    },
    "raise": function(elem, type, evnt) {
        if (elem) {
            if (!evnt) { evnt = { "type": type} };
            EventHandler.process.call(elem, evnt);
        };
    },
    "process": function(v) {
        v = v || window.event;
        //		if (v.type == "mouseup") { debug("asdf") };
        if (this.__handlers && this.__handlers[v.type]) {
            //			alert (this +" - "+ this.__handlers[v.type][0])
            for (var i = 0, f; f = this.__handlers[v.type][i]; i++) { f.call(this, v) };
            if (!this.__handlers[v.type + "_bubble"]) { EventHandler.stopBubbling(v) };
        };
    },
    "stopBubbling": function(v) {
        if (!v) { v = v || window.event };
        if (v) {
            if (v.stopPropagation) { v.stopPropagation() }
            else if (v.preventBubble) { v.preventBubble() }
            else { v.cancelBubble = true };
        };
    }
};
FunctionCaller = function(func, context) {
    this.func = func;
    this.context = context;
};
FunctionCaller.prototype = {
    "func": null,
    "context": null
};
var Watcher = {
    // add a handler
    "add": function(obj, type, func, objcontext) {
        if (obj) {
            if (!obj.__handlers) {
                obj.__handlers = {}
            };
            if (!obj.__handlers[type]) {
                obj.__handlers[type] = []
            };
            var fc;
            if (objcontext) {
                fs = new FunctionCaller(func, objcontext);
            } else {
                fs = new FunctionCaller(func, obj);
            };
            obj.__handlers[type].push(fs);

            if (objcontext) {
                for (var i = 0, fn; fn = obj.__handlers[type][i]; i++) {
                    //					alert ("contains " +fn.context.id)
                }
            }
            //		    obj.__handlers[type].push(func);
        };
    },
    // add a handler
    "remove": function(obj, type, func, context) {
        if (obj && obj.__handlers) {
            if (obj.__handlers[type]) {
                if (typeof func == "undefined" || func == null) {
                    obj.__handlers[type].clear();
                    obj.__handlers[type] = null;
                    delete obj.__handlers[type];
                } else if (typeof func == "function") {
                    for (var i = 0, f; f = obj.__handlers[type][i]; i++) {
                        if (f.func == func && f.context == context) {
                            obj.__handlers[type].remove(f)
                        };
                    };
                } else if (typeof func == "number") {
                    var funcs = [];
                    for (var i = 0, f; f = obj.__handlers[type][i]; i++) {
                        if (i != func) { funcs.push(f) };
                    };
                    obj.__handlers[type] = funcs;
                } else if (typeof func == "string") {
                    var funcs = [];
                    for (var i = 0, f; f = obj.__handlers[type][i]; i++) {
                        var name = f.func.toString();
                        name = name.replacer(" ", "");
                        name = name.substring(8, name.indexOf("("));
                        if (func == name || func == "" && name == "anonymous") {
                            // i hate ie7 like nothing else
                        } else {
                            funcs.push(f);
                        };
                    };
                    obj.__handlers[type] = funcs;
                };
            } else if (!type) {
                for (var each in obj.__handlers) {
                    try {
                        obj.__handlers[each].clear();
                    } catch (x) {
                        // not an array
                    };
                };
                obj.__handlers = null;
                delete obj.__handlers;
            };
        };
    },
    // raise the pseudo-event
    "raise": function(obj, type, additional) {
        // new better method
        //		if (type == "closed") { alert (obj.__handlers[type])}
        if (obj && type && obj.__handlers && obj.__handlers[type] && obj.__handlers[type].length) {
            var funcs = [];
            for (var i = 0, f; f = obj.__handlers[type][i]; i++) { funcs.push(f) };
            for (var i = 0, f; f = funcs[i]; i++) {
                if (f.context) {
                    f.func.call(f.context, obj, type, additional)
                } else {
                    f.call(obj, type, additional)
                };
            };
            //			var funcs = [];
            //			for (var i=0,f; f=obj.__hanlers[type][i]; i++) { funcs.push(f) };
            //			for (var i=0,f; f=funcs[i]; i++) { f.call(obj,type,additional) };
        } else {
            //		    alert ("No event '" + type + "' found on object '" + obj.id + "'");
        };
    }
};
function findPos(element) {
    var coords = { "top": 0, "left": 0, "width": 0, "height": 0 };
    if (element) {
        coords.width = parseInt(element.offsetWidth);
        coords.height = parseInt(element.offsetHeight);
        var curleft = curtop = 0;
        if (element.offsetParent) {
            do {
                curleft += element.offsetLeft;
                curtop += element.offsetTop;
            } while (element = element.offsetParent);
        }
        coords.top = curtop;
        coords.left = curleft;
    }
    return coords;
};

var ce = function(tag, props) {
    // lvls is a limiter in case the function is thrown into an infinite loop.
    // elem is our element, created using the browser's document.createElement method.
    var lvls = 0; elem = document.createElement(tag);
    // If props is an object, we call the private sub addProps to add them to the element.
    if (typeof props == "object") { arguments.callee.addProps(elem, props, lvls) };
    // Finally, we return the element.
    return elem;
};
// Here's where all the magic happens.
// Passing 3 agruments, this sub adds the properties from obj to node.
ce.addProps = function(node, obj, lvls) {
    // We increase lvls, this keeps track of how many levels deep the objects should try to apply properties.
    if (isNaN(lvls = parseInt(lvls))) { lvls = 0 };
    lvls++;
    // A simple "for each" loop to go through all the prop in obj.
    for (var prop in obj) {
        // If the type of the value of the property is an object...
        if (typeof obj[prop] == "object") {
            // First try to apply the object directly.
            // It's possible that the object needs to be copied in the case of other javascript code.
            try {
                // First we try to create a blank object
                node[prop] = {};
            } catch (x) {
                // There must have been an object already if this block is executed
            } finally {
                // Whether there was an error trying to apply this object or not, we call addProps again,
                // but this time passing node[prop] as the node, and the obj[prop] as the obj.
                // This is where lvls comes in, we can run into an infinite loop here (sub calling itself).
                // You can edit this value if you need, but 10 seemed a safe number.  I've only ever needed 2 though.
                if (lvls < 10) { arguments.callee(node[prop], obj[prop], lvls) };
            };
            // If the type of the value of the property is anything but an object...
        } else {
            try { node[prop] = obj[prop] }
            catch (x) { /* node[prop] = "undefined" */ };
        };
    };
};

function showPalette(elem) {
    $j(elem).parent().addClass("expanded").find(".palette").slideDown("fast");
    $j(elem).parent().mouseleave(function() {
        $j(this).find(".palette").slideUp("fast", function() {
            $j(this).parent().removeClass("expanded");
        });
    });
};
function setPicker(elem, hiddenfieldid) {
    $j(elem).parent().parent().mouseleave().find(".tab img").eq(0).attr("src", $j(elem).find("img").eq(0).attr("src"));
    $(hiddenfieldid).value = $j(elem).find("img").eq(0).attr("alt");
};
function showTooltip(ev, snippet, args) {
    ev = ev || window.event;
    var elem = ev.target || ev.srcElement;
    stopBubbling(ev);
    var pos = findPos(elem);
    var tooltip = $("divHelper");
    tooltip.style.top = pos.top - 58 + "px";
    tooltip.style.left = pos.left + (pos.width-20) - 15 + "px";
    tooltip.style.display = "block";
    var content = $j(tooltip).find(".content")[0];
    content.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    tooltip.xhr = new XmlRequest("/includes/tooltips.aspx", null, false, true, function() { this.data = "snippet=" + snippet + "&" + args }, null, popTooltip);
    tooltip.xhr.load();
    return false;
};
function popTooltip() {
    var tooltip = $j("#divHelper");
    var content = tooltip.find(".content");
    content.html(this.xmlText);
    tooltip.find(".title span").html(content.find("h3").remove().html());
    EventHandler.add(document.body, "click", hideTooltip, true);
};
function hideTooltip() {
    var tooltip = $("divHelper");
    var content = $j(tooltip).find(".content")[0];
    tooltip.style.display = "none";
    tooltip.xhr.cancel();
    content.style.overflowY = "";
    EventHandler.remove(document.body, "click", hideTooltip, true);
};
function timerHideTooltip() {
    var tooltip = $("divHelper");
    tooltip.timer = setTimeout("hideTooltip()", 1000);
};
function timerHideTooltipCancel() {
    var tooltip = $("divHelper");
    clearTimeout(tooltip.timer);
};
function popup(url, width, height) {
    width = width || 450;
    height = height || 600;
    var newwindow = window.open(url, "name", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=" + width + ",height=" + height);
    if (window.focus) { newwindow.focus() }
};
function isNumberic(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
};
function formatCurrency(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
};
if (BrowserDetect.browser == "Explorer" && typeof XMLHttpRequest == "undefined") {
    var XMLHttpRequest = function() {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (x) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch (x) {
                alert("AJAX Not supported!\nThis application will not function.");
            };
        }
    };
};
function XmlRequest(url, post, sync, wait, before, during, after) {
    this.xhr = new XMLHttpRequest();
    this.url = url;
    this.data = post;
    this.sync = (typeof sync == "boolean") ? sync : false;
    this.wait = (typeof wait == "boolean") ? wait : false;
    if (typeof before == "function") { Watcher.add(this, "before", before) };
    if (typeof during == "function") { Watcher.add(this, "loading", during) };
    if (typeof after == "function") { Watcher.add(this, "loaded", after) };
    if (!this.wait) { this.load() };
};
XmlRequest.prototype = {
    "url": "",
    "data": "",
    "sync": false,
    "wait": false,
    "active": false,
    "progress": 0,
    "load": function(override) {
        if (override || this.progress <= 0 || this.progress >= 1) {

            // clear previous data and fix memory leaks
            this.cancel(true);
            Watcher.raise(this, "before");
            this.active = true;
            // build new request
            if (!this.sync) {
                var me = this;
                //	this.xhr.onerror = function() { GLog.write("onerror") };
                //	this.xhr.onabort = function() { GLog.write("onabort") };
                this.xhr.onreadystatechange = function() { me.loading() };
                delete me;
            };
            this.xhr.open((!this.data) ? "GET" : "POST", this.formatURL(), !this.sync);
            this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            try {
                this.xhr.send(this.data);
            } catch (x) {
                alert("xhr: " + x.message);
            }
            if (this.sync) { this.loading() };
        };
    },
    "loading": function() {
        if (this.xhr.readyState == 4) {
            var status = 0;
            try { status = this.xhr.status }
            catch (x) { status = 0 };
            if (status <= 0) {
                Watcher.raise(this, "error");
                this.cancel();
            } else {
                this.xmlDocument = this.xhr.responseXML;
                this.xmlText = this.xhr.responseText;
                this.progress = 1;
                Watcher.raise(this, "loading");
                this.active = false;
                this.xhr.abort(); // ie6 memory leak bug
                this.progress = 0;
                Watcher.raise(this, "loaded");
            };
        } else {
            try {
                var total = parseInt(this.xhr.getResponseHeader("Content-Length"));
                if (!isNaN(total)) { this.progress = this.xhr.responseText.length / total };
            } catch (x) {
                this.progress = this.xhr.readyState / 100;
            };
            Watcher.raise(this, "loading");
        };
    },
    "formatURL": function(url) {
        if (!url || !url.length) { url = this.url };
        url += (url.indexOf("?") < 0) ? "?" : "&";
        return url + "ieflush=" + (new Date().valueOf() + Math.random()); //ie6 cache bug
    },
    "getJSON": function(node) {
        var json = null, text = "";
        if (!node && this.xmlDocument) { node = this.xmlDocument.documentElement };
        if (node && node.hasChildNodes()) {
            try {
                for (var i = 0, n; n = node.childNodes[i]; i++) {
                    if (n.nodeType == 3) { text += n.nodeValue }; //	else { showAllProps(n) };
                };
                if (text.length > 0) { json = eval(text) };
            } catch (x) {
                var err = [];
                for (var i = 0; i < text.length; i = i + 200) {
                    err.push(text.substring(i, i + 200));
                    err.push("\n");
                };
                //alert("JSON: "+ x.message +"\n\n"+ err.join(""));
            };
        };
        return json;
    },
    "cancel": function(nofire) {
        if (this.xhr) {
            try { this.xhr.onreadystatechange = null }
            catch (x) { /* firefox fires event on abort */ };
            this.xhr.abort();
        };
        this.active = false;
        this.progress = 0;
        this.xmlDocument = null;
        this.xmlText = "";
        if (!nofire) { Watcher.raise(this, "cancel") };
    },
    "dispose": function() {
        this.cancel();
        this.xhr = null;
        Watcher.raise(this, "dispose");
        Watcher.remove(this);
    }
};
function toggleExpand(id) {
    var section = $j("#" + id);
    section.find(".content").toggle("fast", function() {
        section.find(".header img").attr("src", ($j(this).is(":visible")==true) ? "/images/design/16px_collapse.gif" : "/images/design/16px_expand.gif")
    });
    return false;
};
function checkall(container) {
    var container = $(container);
    for (var i = 0, elem; elem = container.getElementsByTagName("input")[i]; i++) {
        if (elem.type == "checkbox" && !elem.disabled) { elem.checked = true };
    };
    return false;
};
function uncheckall(container) {
    var container = $(container);
    for (var i = 0, elem; elem = container.getElementsByTagName("input")[i]; i++) {
        if (elem.type == "checkbox" && !elem.disabled) { elem.checked = false };
    };
    return false;
};
function showMaxLength(labelID, textID, maxLength) {
    $(labelID).innerHTML = maxLength - $(textID).value.length;
    $(labelID).style.fontWeight = "normal";
    $(labelID).style.color = "black"
    if ($(textID).value.length > maxLength) {
        $(labelID).style.fontWeight = "bold";
        $(labelID).style.color = "maroon"
    };
};
function setCountry(elem, target) {
    $j("#" + target).val($j(elem).find(":selected").attr('cccode'));
};
function replicateAddress() {
    var shippingInfo = $j("#divShippingInfo").show();
    $j("#ctl00_phldrBody_chkSameShipping:checked").each(function() {
        shippingInfo.hide();
    });
};
function rgbConvert(str) {
    str = str.replace(/rgb\(|\)/g, "").split(",");
    str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
    str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
    str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
    str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
    str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
    str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
    return ('#' + str.join(""));
};

if (!this.JSON) {
    JSON = function() {

        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function() {
            return this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z';
        };


        var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
            gap,
            indent,
            meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"': '\\"',
                '\\': '\\\\'
            },
            rep;


        function quote(string) {
            return escapeable.test(string) ?
                '"' + string.replace(escapeable, function(a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"' :
                '"' + string + '"';
        }


        function str(key, holder) {
            var i,          // The loop counter.
                k,          // The member key.
                v,          // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];
            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }
            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }
            switch (typeof value) {
                case 'string':
                    return quote(value);

                case 'number':
                    return isFinite(value) ? String(value) : 'null';

                case 'boolean':
                case 'null':
                    return String(value);
                case 'object':
                    if (!value) {
                        return 'null';
                    }
                    gap += indent;
                    partial = [];
                    if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {
                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }
                        v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap + partial.join(',\n' + gap) +
                                  '\n' + mind + ']' :
                              '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }
                    if (typeof rep === 'object') {
                        length = rep.length;
                        for (i = 0; i < length; i += 1) {
                            k = rep[i];
                            if (typeof k === 'string') {
                                v = str(k, value, rep);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    } else {
                        for (k in value) {
                            v = str(k, value, rep);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                    v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) +
                              '\n' + mind + '}' :
                          '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
            }
        }
        return {
            stringify: function(value, replacer, space) {
                var i;
                gap = '';
                indent = '';
                if (space) {
                    if (typeof space === 'number') {
                        for (i = 0; i < space; i += 1) {
                            indent += ' ';
                        }
                    } else if (typeof space === 'string') {
                        indent = space;
                    }
                }
                if (!replacer) {
                    rep = function(key, value) {
                        if (!Object.hasOwnProperty.call(this, key)) {
                            return undefined;
                        }
                        return value;
                    };
                } else if (typeof replacer === 'function' ||
                        (typeof replacer === 'object' &&
                         typeof replacer.length === 'number')) {
                    rep = replacer;
                } else {
                    throw new Error('JSON.stringify');
                }
                return str('', { '': value });
            },

            parse: function(text, reviver) {
                var j;

                function walk(holder, key) {
                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }
                if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                    j = eval('(' + text + ')');
                    return typeof reviver === 'function' ?
                        walk({ '': j }, '') : j;
                }
                throw new SyntaxError('JSON.parse');
            },

            quote: quote
        };
    } ();
};
JSON.clone = function(obj) {
    return JSON.parse(JSON.stringify(obj));
};