﻿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);
};
//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" */ };
        };
    };
};

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "mdy";    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateField, displayBelowThisObject, dtFormat, dtSep) {
    var targetDateField = dateField;

    // if we weren't told what node to display the datepicker beneath, just display it
    // beneath the date field we're updating
    if (!displayBelowThisObject)
        displayBelowThisObject = targetDateField;

    // if a date separator character was given, update the dateSeparator variable
    if (dtSep)
        dateSeparator = dtSep;
    else
        dateSeparator = defaultDateSeparator;

    // if a date format was given, update the dateFormat variable
    if (dtFormat)
        dateFormat = dtFormat;
    else
        dateFormat = defaultDateFormat;

    var x = displayBelowThisObject.offsetLeft;
    var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight;

    // deal with elements inside tables and such
    var parent = displayBelowThisObject;
    while (parent.offsetParent) {
        parent = parent.offsetParent;
        x += parent.offsetLeft;
        y += parent.offsetTop;
    }

    drawDatePicker(targetDateField, x, y);
};


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y) {
    var dt = getFieldDate(targetDateField.value);

    // the datepicker table will be drawn inside of a <div> with an ID defined by the
    // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
    // document we're working with, add one.
    if (!$(datePickerDivID)) {
        // don't use innerHTML to update the body, because it can cause global variables
        // that are currently pointing to objects on the page to have bad references
        //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
        var newNode = document.createElement("div");
        newNode.setAttribute("id", datePickerDivID);
        newNode.setAttribute("class", "dpDiv");
        newNode.setAttribute("style", "visibility: hidden;");
        document.body.appendChild(newNode);
    }

    // move the datepicker div to the proper x,y coordinate and toggle the visiblity
    var pickerDiv = $(datePickerDivID);
    pickerDiv.style.position = "absolute";
    pickerDiv.style.left = x + "px";
    pickerDiv.style.top = y + "px";
    pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
    pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
    pickerDiv.style.zIndex = 10000;

    // draw the datepicker table
    refreshDatePicker(targetDateField.id, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day) {
    // if no arguments are passed, use today's date; otherwise, month and year
    // are required (if a day is passed, it will be highlighted later)
    var thisDay = new Date();

    if ((month >= 0) && (year > 0)) {
        thisDay = new Date(year, month, 1);
    } else {
        day = thisDay.getDate();
        thisDay.setDate(1);
    }

    // the calendar will be drawn as a table
    // you can customize the table elements with a global CSS style sheet,
    // or by hardcoding style and formatting elements below
    var crlf = "\r\n";
    var TABLE = "<table cols=7 class='dpTable'>" + crlf;
    var xTABLE = "</table>" + crlf;
    var TR = "<tr class='dpTR'>";
    var TR_title = "<tr class='dpTitleTR'>";
    var TR_days = "<tr class='dpDayTR'>";
    var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
    var xTR = "</tr>" + crlf;
    var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
    var TD_title = "<td colspan=5 class='dpTitleTD'>";
    var TD_buttons = "<td class='dpButtonTD'>";
    var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
    var TD_days = "<td class='dpDayTD'>";
    var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
    var xTD = "</td>" + crlf;
    var DIV_title = "<div class='dpTitleText'>";
    var DIV_selected = "<div class='dpDayHighlight'>";
    var xDIV = "</div>";

    // start generating the code for the calendar table
    var html = TABLE;

    // this is the title bar, which displays the month and the buttons to
    // go back to a previous month or forward to the next month
    html += TR_title;
    html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
    html += TD_title + DIV_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
    html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
    html += xTR;

    // this is the row that indicates which day of the week we're on
    html += TR_days;
    for (i = 0; i < dayArrayShort.length; i++)
        html += TD_days + dayArrayShort[i] + xTD;
    html += xTR;

    // now we'll start populating the table with days of the month
    html += TR;

    // first, the leading blanks
    for (i = 0; i < thisDay.getDay(); i++)
        html += TD + "&nbsp;" + xTD;

    // now, the days of the month
    do {
        dayNum = thisDay.getDate();
        TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";

        if (dayNum == day)
            html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
        else
            html += TD + TD_onclick + dayNum + xTD;

        // if this is a Saturday, start a new row
        if (thisDay.getDay() == 6)
            html += xTR + TR;

        // increment the day
        thisDay.setDate(thisDay.getDate() + 1);
    } while (thisDay.getDate() > 1)

    // fill in any trailing blanks
    if (thisDay.getDay() > 0) {
        for (i = 6; i > thisDay.getDay(); i--)
            html += TD + "&nbsp;" + xTD;
    }
    html += xTR;

    // add a button to allow the user to easily return to today, or close the calendar
    var today = new Date();
    var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[today.getMonth()] + " " + today.getDate();
    html += TR_todaybutton + TD_todaybutton;
    html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
    html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
    html += xTD + xTR;

    // and finally, close the table
    html += xTABLE;

    document.getElementById(datePickerDivID).innerHTML = html;
    // add an "iFrame shim" to allow the datepicker to display above selection lists
    adjustiFrame();
};


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label) {
    var newMonth = (dateVal.getMonth() + adjust) % 12;
    var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
    if (newMonth < 0) {
        newMonth += 12;
        newYear += -1;
    };
    return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
};


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal) {
    var dayString = "00" + dateVal.getDate();
    var monthString = "00" + (dateVal.getMonth() + 1);
    dayString = dayString.substring(dayString.length - 2);
    monthString = monthString.substring(monthString.length - 2);
    switch (dateFormat) {
        case "dmy":
            return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
        case "ymd":
            return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
        case "mdy":
        default:
            return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
    }
};


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString) {
    var dateVal;
    var dArray;
    var d, m, y;

    try {
        dArray = splitDateString(dateString);
        if (dArray) {
            switch (dateFormat) {
                case "dmy":
                    d = parseInt(dArray[0], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
                case "ymd":
                    d = parseInt(dArray[2], 10);
                    m = parseInt(dArray[1], 10) - 1;
                    y = parseInt(dArray[0], 10);
                    break;
                case "mdy":
                default:
                    d = parseInt(dArray[1], 10);
                    m = parseInt(dArray[0], 10) - 1;
                    y = parseInt(dArray[2], 10);
                    break;
            }
            dateVal = new Date(y, m, d);
        } else if (dateString) {
            dateVal = new Date(dateString);
        } else {
            dateVal = new Date();
        }
    } catch (e) {
        dateVal = new Date();
    }

    return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString) {
    var dArray;
    if (dateString.indexOf("/") >= 0)
        dArray = dateString.split("/");
    else if (dateString.indexOf(".") >= 0)
        dArray = dateString.split(".");
    else if (dateString.indexOf("-") >= 0)
        dArray = dateString.split("-");
    else if (dateString.indexOf("\\") >= 0)
        dArray = dateString.split("\\");
    else
        dArray = false;

    return dArray;
}


function updateDateField(dateFieldName, dateString) {
    var targetDateField = $(dateFieldName);
    if (dateString)
        targetDateField.value = dateString;

    var pickerDiv = document.getElementById(datePickerDivID);
    pickerDiv.style.visibility = "hidden";
    pickerDiv.style.display = "none";

    adjustiFrame();
    //targetDateField.focus();

    // after the datepicker has closed, optionally run a user-defined function called
    // datePickerClosed, passing the field that was just updated as a parameter
    // (note that this will only run if the user actually selected a date from the datepicker)
    if ((dateString) && (typeof (datePickerClosed) == "function"))
        datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv) {
    // we know that Opera doesn't like something about this, so if we
    // think we're using Opera, don't even try
    var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
    if (is_opera)
        return;

    // put a try/catch block around the whole thing, just in case
    try {
        if (!document.getElementById(iFrameDivID)) {
            // don't use innerHTML to update the body, because it can cause global variables
            // that are currently pointing to objects on the page to have bad references
            //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
            var newNode = document.createElement("iFrame");
            newNode.setAttribute("id", iFrameDivID);
            newNode.setAttribute("src", "javascript:false;");
            newNode.setAttribute("scrolling", "no");
            newNode.setAttribute("frameborder", "0");
            document.body.appendChild(newNode);
        }

        if (!pickerDiv)
            pickerDiv = $(datePickerDivID);
        if (!iFrameDiv)
            iFrameDiv = $(iFrameDivID);

        try {
            iFrameDiv.style.position = "absolute";
            iFrameDiv.style.width = pickerDiv.offsetWidth;
            iFrameDiv.style.height = pickerDiv.offsetHeight;
            iFrameDiv.style.top = pickerDiv.style.top;
            iFrameDiv.style.left = pickerDiv.style.left;
            iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
            iFrameDiv.style.visibility = pickerDiv.style.visibility;
            iFrameDiv.style.display = pickerDiv.style.display;
        } catch (e) {
        }

    } catch (ee) {
    }
};

Timebox = function(element) {
    var me = this;
    this.element = element || ce("div", {});
    var inputs = element.getElementsByTagName("input");
    this.hour = inputs[0];
    this.minute = inputs[1];
    this.ampm = inputs[2];

    var buttons = element.getElementsByTagName("div");
    this.up = buttons[0];
    this.down = buttons[1];

    delete inputs, buttons;

    this.hour.timecontrol = this;
    this.minute.timecontrol = this;
    this.ampm.timecontrol = this;
    this.up.timecontrol = this;
    this.down.timecontrol = this;

    this.selected = this.hour;

    this.hour.onclick = this.hour.onfocus = function() {
        this.timecontrol.selected = this;
        this.select();
    };
    this.minute.onclick = this.minute.onfocus = function() {
        this.timecontrol.selected = this;
        this.select();
    };
    this.ampm.onclick = this.ampm.onfocus = function() {
        this.timecontrol.selected = this;
        this.select();
    };
    this.hour.onkeydown = function(e) {
        e = e || window.event;
        e.cancelBubble = true;
        if (e.keyCode <= 40 && e.keyCode >= 37) {
            if (e.keyCode == 37 || e.keyCode == 40) {
                this.timecontrol.addTime(-1, "hour");
            } else {
                this.timecontrol.addTime(1, "hour");
            };
        };
    };
    this.hour.onblur = this.minute.onblur = function(e) {
        e = e || window.event;
        e.cancelBubble = true;
        this.value = this.timecontrol.padTime(this.value);
    };
    this.ampm.onblur = function(e) {
        e = e || window.event;
        e.cancelBubble = true;
        this.value = this.value.toUpperCase();
        if (this.value == "AM" || this.value == "PM") {
        } else { this.value = "AM" }
    };
    this.minute.onkeydown = function(e) {
        e = e || window.event;
        e.cancelBubble = true;
        if (e.keyCode <= 40 && e.keyCode >= 37) {
            if (e.keyCode == 37 || e.keyCode == 40) {
                this.timecontrol.addTime(-1, "minute");
            } else {
                this.timecontrol.addTime(1, "minute");
            };
        };
    };
    this.ampm.onkeydown = function(e) {
        e = e || window.event;
        e.cancelBubble = true;
        if (e.keyCode <= 40 && e.keyCode >= 37) {
            if (e.keyCode == 37 || e.keyCode == 40) {
                this.timecontrol.addTime(-12, "hour");
            } else {
                this.timecontrol.addTime(12, "hour");
            };
        };
        if (viewer) { me.viewer.onDateChanged() };
    };
    this.up.onclick = function() { return false };
    this.up.onmousedown = function() {
        var timecontrol = this.timecontrol;
        timecontrol.selected.onkeydown({ "keyCode": 39 });
        timecontrol.timer = setTimeout(function() {
            timecontrol.selected.onkeydown({ "keyCode": 39 });
            timecontrol.timer = setInterval(function() {
                timecontrol.selected.onkeydown({ "keyCode": 39 });
            }, 100);
        }, 800);
    };
    this.up.onmouseup = this.up.onmouseout = function() {
        var timecontrol = this.timecontrol;
        try { clearTimeout(timecontrol.timer) } catch (x) { };
        try { clearInterval(timecontrol.timer) } catch (x) { };
        timecontrol.timer = null;
    };
    this.down.onclick = function() { return false };
    this.down.onmousedown = function() {
        var timecontrol = this.timecontrol;
        timecontrol.selected.onkeydown({ "keyCode": 40 });
        timecontrol.timer = setTimeout(function() {
            timecontrol.selected.onkeydown({ "keyCode": 40 });
            timecontrol.timer = setInterval(function() {
                timecontrol.selected.onkeydown({ "keyCode": 40 });
            }, 100);
        }, 800);
    };
    this.down.onmouseup = this.up.onmouseout = function() {
        var timecontrol = this.timecontrol;
        try { clearTimeout(timecontrol.timer) } catch (x) { };
        try { clearInterval(timecontrol.timer) } catch (x) { };
        timecontrol.timer = null;
    }
};
Timebox.prototype = {
    "addTime": function(value, interval) {
        var time = new Date("2001/01/01 " + this.hour.value + ":" + this.minute.value + " " + this.ampm.value);
        var value = parseFloat(value);
        if (interval == "hour") { time.setHours(time.getHours() + value); };
        if (interval == "minute") { time.setMinutes(time.getMinutes() + value) };

        this.hour.value = time.getHours();
        this.ampm.value = "AM";
        if (time.getHours() > 11) { this.ampm.value = "PM" };
        if (time.getHours() > 12) { this.hour.value = this.hour.value - 12 };
        if (time.getHours() == 0) { this.hour.value = 12 };

        this.hour.value = this.padTime(this.hour.value);
        this.minute.value = this.padTime(time.getMinutes());
    },
    "padTime": function(value) {
        var n = value + "";
        if (n.length <= 1) { n = "0" + n };
        return n;
    },
    "getTime": function() {
        var time = new Date("2001/01/01 " + this.hour.value + ":" + this.minute.value + " " + this.ampm.value);
        return this.padTime(time.getHours()) + ":" + this.padTime(time.getMinutes());
    },
    "getHours": function() {
        var time = new Date("2001/01/01 " + this.hour.value + ":" + this.minute.value + " " + this.ampm.value);
        return time.getHours();
    },
    "getMinutes": function() {
        var time = new Date("2001/01/01 " + this.hour.value + ":" + this.minute.value + " " + this.ampm.value);
        return time.getMinutes();
    }
};
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) {
    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 }, 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();
    });
};

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
        };
    } ();
};