// Prototype.js
// Core.js
// Ms.js
// Behaviour.js
// Formhelper.js - Monorails
// "Really easy field validation with Prototype"
// Facebox (Prototype JS)
// jsDate
// Cookie
// HTMLDecode (Removed from this file)
// Global functions

jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
			encodeURIComponent(key), '=',
			options.raw ? String(value) : encodeURIComponent(String(value)),
			options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
			options.path ? '; path=' + options.path : '',
			options.domain ? '; domain=' + options.domain : '',
			options.secure ? '; secure' : ''
			].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

// Prototype.js
Object.extend = function (dest, source, replace) {
    for (var prop in source) {
        if (replace == false && dest[prop] != null) { continue; }
        dest[prop] = source[prop];
    }
    return dest;
};

Object.extend(Function.prototype, {
    apply: function (o, a) {
        var r, x = "__fapply";
        if (typeof o != "object") { o = {}; }
        o[x] = this;
        var s = "r = o." + x + "(";
        for (var i = 0; i < a.length; i++) {
            if (i > 0) { s += ","; }
            s += "a[" + i + "]";
        }
        s += ");";
        eval(s);
        delete o[x];
        return r;
    },
    bind: function (o) {
        if (!Function.__objs) {
            Function.__objs = [];
            Function.__funcs = [];
        }
        var objId = o.__oid;
        if (!objId) {
            Function.__objs[objId = o.__oid = Function.__objs.length] = o;
        }

        var me = this;
        var funcId = me.__fid;
        if (!funcId) {
            Function.__funcs[funcId = me.__fid = Function.__funcs.length] = me;
        }

        if (!o.__closures) {
            o.__closures = [];
        }

        var closure = o.__closures[funcId];
        if (closure) {
            return closure;
        }

        o = null;
        me = null;

        return Function.__objs[objId].__closures[funcId] = function () {
            return Function.__funcs[funcId].apply(Function.__objs[objId], arguments);
        };
    }
}, false);

Object.extend(Array.prototype, {
    push: function (o) {
        this[this.length] = o;
    },
    addRange: function (items) {
        if (items.length > 0) {
            for (var i = 0; i < items.length; i++) {
                this.push(items[i]);
            }
        }
    },
    clear: function () {
        this.length = 0;
        return this;
    },
    shift: function () {
        if (this.length == 0) { return null; }
        var o = this[0];
        for (var i = 0; i < this.length - 1; i++) {
            this[i] = this[i + 1];
        }
        this.length--;
        return o;
    }
}, false);

Object.extend(String.prototype, {
    trimLeft: function () {
        return this.replace(/^\s*/, "");
    },
    trimRight: function () {
        return this.replace(/\s*$/, "");
    },
    trim: function () {
        return this.trimRight().trimLeft();
    },
    endsWith: function (s) {
        if (this.length == 0 || this.length < s.length) { return false; }
        return (this.substr(this.length - s.length) == s);
    },
    startsWith: function (s) {
        if (this.length == 0 || this.length < s.length) { return false; }
        return (this.substr(0, s.length) == s);
    },
    split: function (c) {
        var a = [];
        if (this.length == 0) return a;
        var p = 0;
        for (var i = 0; i < this.length; i++) {
            if (this.charAt(i) == c) {
                a.push(this.substring(p, i));
                p = ++i;
            }
        }
        a.push(s.substr(p));
        return a;
    }
}, false);

Object.extend(String, {
    format: function (s) {
        for (var i = 1; i < arguments.length; i++) {
            s = s.replace("{" + (i - 1) + "}", arguments[i]);
        }
        return s;
    },
    isNullOrEmpty: function (s) {
        if (s == null || s.length == 0) {
            return true;
        }
        return false;
    }
}, false);

if (typeof addEvent == "undefined")
    addEvent = function (o, evType, f, capture) {
        if (o == null) { return false; }
        if (o.addEventListener) {
            o.addEventListener(evType, f, capture);
            return true;
        } else if (o.attachEvent) {
            var r = o.attachEvent("on" + evType, f);
            return r;
        } else {
            try { o["on" + evType] = f; } catch (e) { }
        }
    };

if (typeof removeEvent == "undefined")
    removeEvent = function (o, evType, f, capture) {
        if (o == null) { return false; }
        if (o.removeEventListener) {
            o.removeEventListener(evType, f, capture);
            return true;
        } else if (o.detachEvent) {
            o.detachEvent("on" + evType, f);
        } else {
            try { o["on" + evType] = function () { }; } catch (e) { }
        }
    };







// Core.js

    Object.extend(Function.prototype, {
        getArguments: function () {
            var args = [];
            for (var i = 0; i < this.arguments.length; i++) {
                args.push(this.arguments[i]);
            }
            return args;
        }
    }, false);

    var MS = { "Browser": {} };

    Object.extend(MS.Browser, {
        isIE: navigator.userAgent.indexOf('MSIE') != -1,
        isFirefox: navigator.userAgent.indexOf('Firefox') != -1,
        isOpera: window.opera != null
    }, false);

    var BlocAjax = {};

    BlocAjax.IFrameXmlHttp = function () { };
    BlocAjax.IFrameXmlHttp.prototype = {
        onreadystatechange: null, headers: [], method: "POST", url: null, async: true, iframe: null,
        status: 0, readyState: 0, responseText: null,
        abort: function () {
        },
        readystatechanged: function () {
            var doc = this.iframe.contentDocument || this.iframe.document;
            if (doc != null && doc.readyState == "complete" && doc.body != null && doc.body.res != null) {
                this.status = 200;
                this.statusText = "OK";
                this.readyState = 4;
                this.responseText = doc.body.res;
                this.onreadystatechange();
                return;
            }
            setTimeout(this.readystatechanged.bind(this), 10);
        },
        open: function (method, url, async) {
            if (async == false) {
                alert("Synchronous call using IFrameXMLHttp is not supported.");
                return;
            }
            if (this.iframe == null) {
                var iframeID = "hans";
                if (document.createElement && document.documentElement &&
				(window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1)) {
                    var ifr = document.createElement('iframe');
                    ifr.setAttribute('id', iframeID);
                    ifr.style.visibility = 'hidden';
                    ifr.style.position = 'absolute';
                    ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';

                    this.iframe = document.getElementsByTagName('body')[0].appendChild(ifr);
                }
                else if (document.body && document.body.insertAdjacentHTML) {
                    document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID + '" id="' + iframeID + '" style="border:1px solid black;display:none"></iframe>');
                }
                if (window.frames && window.frames[iframeID]) {
                    this.iframe = window.frames[iframeID];
                }
                this.iframe.name = iframeID;
                this.iframe.document.open();
                this.iframe.document.write("<" + "html><" + "body></" + "body></" + "html>");
                this.iframe.document.close();
            }
            this.method = method;
            this.url = url;
            this.async = async;
        },
        setRequestHeader: function (name, value) {
            for (var i = 0; i < this.headers.length; i++) {
                if (this.headers[i].name == name) {
                    this.headers[i].value = value;
                    return;
                }
            }
            this.headers.push({ "name": name, "value": value });
        },
        getResponseHeader: function (name, value) {
            return null;
        },
        addInput: function (doc, form, name, value) {
            var ele;
            var tag = "input";
            if (value.indexOf("\n") >= 0) {
                tag = "textarea";
            }

            if (doc.all) {
                ele = doc.createElement("<" + tag + " name=\"" + name + "\" />");
            } else {
                ele = doc.createElement(tag);
                ele.setAttribute("name", name);
            }
            ele.setAttribute("value", value);
            form.appendChild(ele);
            ele = null;
        },
        send: function (data) {
            if (this.iframe == null) {
                return;
            }
            var doc = this.iframe.contentDocument || this.iframe.document;
            var form = doc.createElement("form");

            doc.body.appendChild(form);

            form.setAttribute("action", this.url);
            form.setAttribute("method", this.method);
            form.setAttribute("enctype", "application/x-www-form-urlencoded");

            for (var i = 0; i < this.headers.length; i++) {
                switch (this.headers[i].name.toLowerCase()) {
                    case "content-length":
                    case "accept-encoding":
                    case "content-type":
                        break;
                    default:
                        this.addInput(doc, form, this.headers[i].name, this.headers[i].value);
                }
            }
            this.addInput(doc, form, "data", data);
            form.submit();

            setTimeout(this.readystatechanged.bind(this), 0);
        }
    };

    var progids = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    var progid = null;

    if (typeof ActiveXObject != "undefined") {
        var ie7xmlhttp = false;
        if (typeof XMLHttpRequest == "object") {
            try { var o = new XMLHttpRequest(); ie7xmlhttp = true; } catch (e) { }
        }
        if (typeof XMLHttpRequest == "undefined" || !ie7xmlhttp) {
            XMLHttpRequest = function () {
                var xmlHttp = null;
                if (!BlocAjax.noActiveX) {
                    if (progid != null) {
                        return new ActiveXObject(progid);
                    }
                    for (var i = 0; i < progids.length && xmlHttp == null; i++) {
                        try {
                            xmlHttp = new ActiveXObject(progids[i]);
                            progid = progids[i];

                        } catch (e) { }
                    }
                }
                if (xmlHttp == null && MS.Browser.isIE) {
                    return new BlocAjax.IFrameXmlHttp();
                }
                return xmlHttp;
            };
        }
    }

    Object.extend(BlocAjax, {
        noOperation: function () { },
        onLoading: function () { },
        onError: function () { },
        onTimeout: function () { return true; },
        onStateChanged: function () { },
        cryptProvider: null,
        queue: null,
        token: "",
        version: "7.4.24.1",
        ID: "BlocAjax",
        noActiveX: false,
        timeoutPeriod: 120 * 1000,
        queue: null,
        noUtcTime: false,
        m: {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        toJSON: function (o) {
            if (o == null) {
                return "null";
            }
            var v = [];
            var i;
            var c = o.constructor;
            if (c == Number) {
                return isFinite(o) ? o.toString() : BlocAjax.toJSON(null);
            } else if (c == Boolean) {
                return o.toString();
            } else if (c == String) {
                if (/["\\\x00-\x1f]/.test(o)) {
                    o = o.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                        var c = BlocAjax.m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
						Math.floor(c / 16).toString(16) +
						(c % 16).toString(16);
                    });
                }
                return '"' + o + '"';
            } else if (c == Array) {
                for (i = 0; i < o.length; i++) {
                    v.push(BlocAjax.toJSON(o[i]));
                }
                return "[" + v.join(",") + "]";
            } else if (c == Date) {
                var d = {};
                d.__type = "System.DateTime";
                if (BlocAjax.noUtcTime == true) {
                    d.Year = o.getFullYear();
                    d.Month = o.getMonth() + 1;
                    d.Day = o.getDate();
                    d.Hour = o.getHours();
                    d.Minute = o.getMinutes();
                    d.Second = o.getSeconds();
                    d.Millisecond = o.getMilliseconds();
                } else {
                    d.Year = o.getUTCFullYear();
                    d.Month = o.getUTCMonth() + 1;
                    d.Day = o.getUTCDate();
                    d.Hour = o.getUTCHours();
                    d.Minute = o.getUTCMinutes();
                    d.Second = o.getUTCSeconds();
                    d.Millisecond = o.getUTCMilliseconds();
                }
                return BlocAjax.toJSON(d);
            }
            if (typeof o.toJSON == "function") {
                return o.toJSON();
            }
            if (typeof o == "object") {
                for (var attr in o) {
                    if (typeof o[attr] != "function") {
                        v.push('"' + attr + '":' + BlocAjax.toJSON(o[attr]));
                    }
                }
                if (v.length > 0) {
                    return "{" + v.join(",") + "}";
                }
                return "{}";
            }
            return o.toString();
        },
        dispose: function () {
            if (BlocAjax.queue != null) {
                BlocAjax.queue.dispose();
            }
        }
    }, false);

    addEvent(window, "unload", BlocAjax.dispose);

    BlocAjax.Request = function (url) {
        this.url = url;
        this.xmlHttp = null;
    };

    BlocAjax.Request.prototype = {
        url: null,
        callback: null,
        onLoading: null,
        onError: null,
        onTimeout: null,
        onStateChanged: null,
        args: null,
        context: null,
        isRunning: false,
        abort: function () {
            if (this.timeoutTimer != null) {
                clearTimeout(this.timeoutTimer);
            }
            if (this.xmlHttp) {
                this.xmlHttp.onreadystatechange = BlocAjax.noOperation;
                this.xmlHttp.abort();
            }
            if (this.isRunning) {
                this.isRunning = false;
                this.onLoading(false);
            }
        },
        dispose: function () {
            this.abort();
        },
        getEmptyRes: function () {
            return {
                error: null,
                value: null,
                request: { method: this.method, args: this.args },
                context: this.context,
                duration: this.duration
            };
        },
        endRequest: function (res) {
            this.abort();
            if (res.error != null) {
                this.onError(res.error, this);
            }

            if (typeof this.callback == "function") {
                this.callback(res, this);
            }
        },
        mozerror: function () {
            if (this.timeoutTimer != null) {
                clearTimeout(this.timeoutTimer);
            }
            var res = this.getEmptyRes();
            res.error = { Message: "Unknown", Type: "ConnectFailure", Status: 0 };
            this.endRequest(res);
        },
        doStateChange: function () {
            this.onStateChanged(this.xmlHttp.readyState, this);
            if (this.xmlHttp.readyState != 4 || !this.isRunning) {
                return;
            }
            this.duration = new Date().getTime() - this.__start;
            if (this.timeoutTimer != null) {
                clearTimeout(this.timeoutTimer);
            }
            var res = this.getEmptyRes();
            if (this.xmlHttp.status == 200 && this.xmlHttp.statusText == "OK") {
                res = this.createResponse(res);
            } else {
                res = this.createResponse(res, true);
                res.error = { Message: this.xmlHttp.statusText, Type: "ConnectFailure", Status: this.xmlHttp.status };
            }

            this.endRequest(res);
        },
        createResponse: function (r, noContent) {
            if (!noContent) {
                var responseText = "" + this.xmlHttp.responseText;

                if (BlocAjax.cryptProvider != null && typeof BlocAjax.cryptProvider.decrypt == "function") {
                    responseText = BlocAjax.cryptProvider.decrypt(responseText);
                }

                if (this.xmlHttp.getResponseHeader("Content-Type") == "text/xml") {
                    r.value = this.xmlHttp.responseXML;
                } else {
                    if (responseText != null && responseText.trim().length > 0) {
                        r.json = responseText;
                        var v = null;
                        //debugger;
                        eval("v = " + responseText + ";");
                        if (v != null) {
                            if (typeof v.value != "undefined") r.value = v.value;
                            else if (typeof v.error != "undefined") r.error = v.error;
                        }
                    }
                }
            }
            /* if(this.xmlHttp.getResponseHeader("X-" + BlocAjax.ID + "-Cache") == "server") {
            r.isCached = true;
            } */
            return r;
        },
        timeout: function () {
            try {
                this.duration = new Date().getTime() - this.__start;
                var r = this.onTimeout(this.duration, this);
                if (typeof r == "undefined" || r != false) {
                    this.abort();
                } else {
                    this.timeoutTimer = setTimeout(this.timeout.bind(this), BlocAjax.timeoutPeriod);
                }
            } catch (error) {
                //alert("error") ;
            } finally {
                ;
            }
        },
        invoke: function (method, args, callback, context) {
            this.__start = new Date().getTime();

            // if(this.xmlHttp == null) {
            this.xmlHttp = new XMLHttpRequest();
            // }

            this.isRunning = true;
            this.method = method;
            this.args = args;
            this.callback = callback;
            this.context = context;

            var async = typeof (callback) == "function" && callback != BlocAjax.noOperation;

            if (async) {
                if (MS.Browser.isIE) {
                    this.xmlHttp.onreadystatechange = this.doStateChange.bind(this);
                } else {
                    this.xmlHttp.onload = this.doStateChange.bind(this);
                    this.xmlHttp.onerror = this.mozerror.bind(this);
                }
                this.onLoading(true);
            }

            var json = BlocAjax.toJSON(args) + "";
            if (BlocAjax.cryptProvider != null && typeof BlocAjax.cryptProvider.encrypt == "function") {
                json = BlocAjax.cryptProvider.encrypt(json);
            }

            this.xmlHttp.open("POST", this.url, async);
            this.xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
            this.xmlHttp.setRequestHeader("X-" + BlocAjax.ID + "-Method", method);

            if (BlocAjax.token != null && BlocAjax.token.length > 0) {
                this.xmlHttp.setRequestHeader("X-" + BlocAjax.ID + "-Token", BlocAjax.token);
            }

            /* if(!MS.Browser.isIE) {
            this.xmlHttp.setRequestHeader("Connection", "close");
            } */

            this.timeoutTimer = setTimeout(this.timeout.bind(this), BlocAjax.timeoutPeriod);

            try { this.xmlHttp.send(json); } catch (e) { } // IE offline exception

            if (!async) {
                return this.createResponse({ error: null, value: null });
            }

            return true;
        }
    };

    BlocAjax.RequestQueue = function (conc) {
        this.queue = [];
        this.requests = [];
        this.timer = null;

        if (isNaN(conc)) { conc = 2; }

        for (var i = 0; i < conc; i++) {		// max 2 http connections
            this.requests[i] = new BlocAjax.Request();
            this.requests[i].callback = function (res) {
                var r = res.context;
                res.context = r[3][1];

                r[3][0](res, this);
            };
            this.requests[i].callbackHandle = this.requests[i].callback.bind(this.requests[i]);
        }
    };

    BlocAjax.RequestQueue.prototype = {
        process: function () {
            this.timer = null;
            if (this.queue.length == 0) {
                return;
            }
            for (var i = 0; i < this.requests.length && this.queue.length > 0; i++) {
                if (this.requests[i].isRunning == false) {
                    var r = this.queue.shift();

                    this.requests[i].url = r[0];
                    this.requests[i].onLoading = r[3].length > 2 && r[3][2] != null && typeof r[3][2] == "function" ? r[3][2] : BlocAjax.onLoading;
                    this.requests[i].onError = r[3].length > 3 && r[3][3] != null && typeof r[3][3] == "function" ? r[3][3] : BlocAjax.onError;
                    this.requests[i].onTimeout = r[3].length > 4 && r[3][4] != null && typeof r[3][4] == "function" ? r[3][4] : BlocAjax.onTimeout;
                    this.requests[i].onStateChanged = r[3].length > 5 && r[3][5] != null && typeof r[3][5] == "function" ? r[3][5] : BlocAjax.onStateChanged;

                    this.requests[i].invoke(r[1], r[2], this.requests[i].callbackHandle, r);
                    r = null;
                }
            }
            if (this.queue.length > 0 && this.timer == null) {
                this.timer = setTimeout(this.process.bind(this), 0);
            }
        },
        add: function (url, method, args, e) {
            this.queue.push([url, method, args, e]);
            if (this.timer == null) {
                this.timer = setTimeout(this.process.bind(this), 0);
            }
            // this.process();
        },
        abort: function () {
            this.queue.length = 0;
            if (this.timer != null) {
                clearTimeout(this.timer);
            }
            this.timer = null;
            for (var i = 0; i < this.requests.length; i++) {
                if (this.requests[i].isRunning == true) {
                    this.requests[i].abort();
                }
            }
        },
        dispose: function () {
            for (var i = 0; i < this.requests.length; i++) {
                var r = this.requests[i];
                r.dispose();
            }
            this.requests.clear();
        }
    };

    BlocAjax.queue = new BlocAjax.RequestQueue(2); // 2 http connections

    BlocAjax.AjaxClass = function (url) {
        this.url = url;
    };

    BlocAjax.AjaxClass.prototype = {
        invoke: function (method, args, e) {

            if (e != null) {
                if (e.length != 6) {
                    for (; e.length < 6; ) { e.push(null); }
                }
                if (e[0] != null && typeof (e[0]) == "function") {
                    return BlocAjax.queue.add(this.url, method, args, e);
                }
            }
            var r = new BlocAjax.Request();
            r.url = this.url;
            return r.invoke(method, args);
        }
    };








// Ms.js

    var addNamespace = function (ns) {
        var nsParts = ns.split(".");
        var root = window;
        for (var i = 0; i < nsParts.length; i++) {
            if (typeof root[nsParts[i]] == "undefined") {
                root[nsParts[i]] = {};
            }
            root = root[nsParts[i]];
        }
    };

    Object.extend(window, {
        $: function () {
            var elements = [];
            for (var i = 0; i < arguments.length; i++) {
                var e = arguments[i];
                if (typeof e == 'string') {
                    e = document.getElementById(e);
                }
                if (arguments.length == 1) {
                    return e;
                }
                elements.push(e);
            }
            return elements;
        },
        Class: {
            create: function () {
                return function () {
                    if (typeof this.initialize == "function") {
                        this.initialize.apply(this, arguments);
                    }
                };
            }
        }
    }, false);

    addNamespace("MS.Debug");
    MS.Debug = {}; 	// has been removed to debug version of core.ashx

    addNamespace("MS.Position");

    Object.extend(MS.Position, {
        getLocation: function (ele) {
            var x = 0;
            var y = 0;
            var p;
            for (p = ele; p; p = p.offsetParent) {
                // if(p.style.position == "relative" || p.style.position == "absolute") break;
                if (p.offsetLeft && p.offsetTop) {
                    x += p.offsetLeft;
                    y += p.offsetTop;
                }
            }
            return { left: x, top: y };
        },
        getBounds: function (ele) {
            var offset = MS.Position.getLocation(ele);
            var width = ele.offsetWidth;
            var height = ele.offsetHeight;
            return { left: offset.left, top: offset.top, width: width, height: height };
        },
        setLocation: function (ele, loc) {
            ele.style.position = "absolute";
            ele.style.left = loc.left + "px";
            ele.style.top = loc.top + "px";
        },
        setBounds: function (ele, rect) {
            if (rect.left && rect.top) {
                MS.Position.setLocation(ele, rect);
            }
            ele.style.width = rect.width + "px";
            ele.style.height = rect.height + "px";
        }
    }, false);

    addNamespace("MS.Keys");

    Object.extend(MS.Keys, {
        TAB: 9,
        ESC: 27,
        KEYUP: 38,
        KEYDOWN: 40,
        KEYLEFT: 37,
        KEYRIGHT: 39,
        SHIFT: 16,
        CTRL: 17,
        ALT: 18,
        ENTER: 13,
        getCode: function (e) {
            e = MS.getEvent(e);
            if (e != null) { return e.keyCode; }
            return -1;
        }
    }, false);

    Object.extend(MS, {
        setText: function (ele, text) {
            if (ele == null) { return; }
            if (document.all) {
                ele.innerText = text;
            } else {
                ele.textContent = text;
            }
        },
        setHtml: function (ele, html) {
            if (ele == null) { return; }
            ele.innerHTML = html;
        },
        cancelEvent: function (e) {
            e = MS.getEvent(e);
            if (window.event) {
                e.returnValue = false;
            } else if (e) {
                e.preventDefault();
                e.stopPropagation();
            }
        },
        getEvent: function (e) {
            if (window.event) { return window.event; }
            if (e) { return e; }
            return null;
        },
        getTarget: function (e) {
            e = MS.getEvent(e);
            if (window.event) { return e.srcElement; }
            if (e) { return e.target; }
        }
    }, false);

    var StringBuilder = function () {
        this.v = [];
    };

    Object.extend(StringBuilder.prototype, {
        append: function (s) {
            this.v.push(s);
        },
        appendLine: function (s) {
            this.v.push(s + "\r\n");
        },
        clear: function () {
            this.v.clear();
        },
        toString: function () {
            return this.v.join("");
        }
    }, true);





    /*
    Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
    of Simon Willison (see comments by Simon below).

    Description:
   	
    Uses css selectors to apply javascript behaviours to enable
    unobtrusive javascript in html documents.
   	
    Usage:   
   
    var myrules = {
    'b.someclass' : function(element){
    element.onclick = function(){
    alert(this.innerHTML);
    }
    },
    '#someid u' : function(element){
    element.onmouseover = function(){
    this.innerHTML = "BLAH!";
    }
    }
    };
	
    Behaviour.register(myrules);
	
    // Call Behaviour.apply() to re-apply the rules (if you
    // update the dom, etc).

    License:
   
    This file is entirely BSD licensed.
   	
    More information:
   	
    http://ripcord.co.nz/behaviour/
   
    */

    var Behaviour = {
        list: new Array,

        register: function (sheet) {
            Behaviour.list.push(sheet);
        },

        start: function () {
            Behaviour.addLoadEvent(function () {
                Behaviour.apply();
            });
        },

        apply: function () {
            for (h = 0; sheet = Behaviour.list[h]; h++) {
                for (selector in sheet) {
                    list = document.getElementsBySelector(selector);

                    if (!list) {
                        continue;
                    }

                    for (i = 0; element = list[i]; i++) {
                        sheet[selector](element);
                    }
                }
            }
        },

        addLoadEvent: function (func) {
            var oldonload = window.onload;

            if (typeof window.onload != 'function') {
                window.onload = func;
            } else {
                window.onload = function () {
                    oldonload();
                    func();
                }
            }
        }
    }

    Behaviour.start();

    /*
    The following code is Copyright (C) Simon Willison 2004.

    document.getElementsBySelector(selector)
    - returns an array of element objects from the current document
    matching the CSS selector. Selectors can contain element names, 
    class names and ids and can be nested. For example:
     
    elements = document.getElementsBySelect('div#main p a.external')
     
    Will return an array of all 'a' elements with 'external' in their 
    class attribute that are contained inside 'p' elements that are 
    contained inside the 'div' element which has id="main"

    New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
    See http://www.w3.org/TR/css3-selectors/#attribute-selectors

    Version 0.4 - Simon Willison, March 25th 2003
    -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
    -- Opera 7 fails 
    */

    function getAllChildren(e) {
        // Returns all children of element. Workaround required for IE5/Windows. Ugh.
        return e.all ? e.all : e.getElementsByTagName('*');
    }

    document.getElementsBySelector = function (selector) {
        // Attempt to fail gracefully in lesser browsers
        if (!document.getElementsByTagName) {
            return new Array();
        }
        // Split selector in to tokens
        var tokens = selector.split(' ');
        var currentContext = new Array(document);
        for (var i = 0; i < tokens.length; i++) {
            token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, ''); ;
            if (token.indexOf('#') > -1) {
                // Token is an ID selector
                var bits = token.split('#');
                var tagName = bits[0];
                var id = bits[1];
                var element = document.getElementById(id);
                if (tagName && element.nodeName.toLowerCase() != tagName) {
                    // tag with that ID not found, return false
                    return new Array();
                }
                // Set currentContext to contain just this element
                currentContext = new Array(element);
                continue; // Skip to next token
            }
            if (token.indexOf('.') > -1) {
                // Token contains a class selector
                var bits = token.split('.');
                var tagName = bits[0];
                var className = bits[1];
                if (!tagName) {
                    tagName = '*';
                }
                // Get elements matching tag, filter them for class selector
                var found = new Array;
                var foundCount = 0;
                for (var h = 0; h < currentContext.length; h++) {
                    var elements;
                    if (tagName == '*') {
                        elements = getAllChildren(currentContext[h]);
                    } else {
                        elements = currentContext[h].getElementsByTagName(tagName);
                    }
                    for (var j = 0; j < elements.length; j++) {
                        found[foundCount++] = elements[j];
                    }
                }
                currentContext = new Array;
                var currentContextIndex = 0;
                for (var k = 0; k < found.length; k++) {
                    if (found[k].className && found[k].className.match(new RegExp('\\b' + className + '\\b'))) {
                        currentContext[currentContextIndex++] = found[k];
                    }
                }
                continue; // Skip to next token
            }
            // Code to deal with attribute selectors
            if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
                var tagName = RegExp.$1;
                var attrName = RegExp.$2;
                var attrOperator = RegExp.$3;
                var attrValue = RegExp.$4;
                if (!tagName) {
                    tagName = '*';
                }
                // Grab all of the tagName elements within current context
                var found = new Array;
                var foundCount = 0;
                for (var h = 0; h < currentContext.length; h++) {
                    var elements;
                    if (tagName == '*') {
                        elements = getAllChildren(currentContext[h]);
                    } else {
                        elements = currentContext[h].getElementsByTagName(tagName);
                    }
                    for (var j = 0; j < elements.length; j++) {
                        found[foundCount++] = elements[j];
                    }
                }
                currentContext = new Array;
                var currentContextIndex = 0;
                var checkFunction; // This function will be used to filter the elements
                switch (attrOperator) {
                    case '=': // Equality
                        checkFunction = function (e) { return (e.getAttribute(attrName) == attrValue); };
                        break;
                    case '~': // Match one of space seperated words 
                        checkFunction = function (e) { return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b'))); };
                        break;
                    case '|': // Match start with value followed by optional hyphen
                        checkFunction = function (e) { return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?'))); };
                        break;
                    case '^': // Match starts with value
                        checkFunction = function (e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
                        break;
                    case '$': // Match ends with value - fails with "Warning" in Opera 7
                        checkFunction = function (e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
                        break;
                    case '*': // Match ends with value
                        checkFunction = function (e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
                        break;
                    default:
                        // Just test for existence of attribute
                        checkFunction = function (e) { return e.getAttribute(attrName); };
                }
                currentContext = new Array;
                var currentContextIndex = 0;
                for (var k = 0; k < found.length; k++) {
                    if (checkFunction(found[k])) {
                        currentContext[currentContextIndex++] = found[k];
                    }
                }
                // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
                continue; // Skip to next token
            }

            if (!currentContext[0]) {
                return;
            }

            // If we get here, token is JUST an element (not a class or ID selector)
            tagName = token;
            var found = new Array;
            var foundCount = 0;
            for (var h = 0; h < currentContext.length; h++) {
                var elements = currentContext[h].getElementsByTagName(tagName);
                for (var j = 0; j < elements.length; j++) {
                    found[foundCount++] = elements[j];
                }
            }
            currentContext = found;
        }
        return currentContext;
    }

    /* That revolting regular expression explained 
    /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
    \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
    Tag
    */





    // Formhelper.js

    // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
    // 
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    // 
    //     http://www.apache.org/licenses/LICENSE-2.0
    // 
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.

    function monorail_formhelper_numberonly(e, exceptions, forbidalso) {
        exceptions = exceptions.concat([8, 9, 13, 38, 39, 40, 46]);
        var code = e.charCode;
        if (!code) code = e.keyCode;
        if ((e.ctrlKey && code == 118) || (e.ctrlKey && code == 122)) {
            return false;
        }
        if (e.ctrlKey || e.altKey) return true;
        for (var i = 0; i < forbidalso.length; i++) if (forbidalso[i] == code) return false;
        for (var i = 0; i < exceptions.length; i++) if (exceptions[i] == code) return true;
        if (code <= 47 || code > 57) return false;
        return true;
    }

    /* 
    The scripts on this page was produced by mordechai Sandhaus - 52action.com,
    and is copyrighted . If you like this script, we encourage you to use it,
    provided that  include this note, and link to 52action.com. 
    */

    function monorail_formhelper_getkeycode(e) {
        if (typeof (e.keyCode) == 'number') {
            return e.keyCode;
        }
        else if (typeof (e.which) == 'number') {
            return e.which;
        }
        else if (typeof (e.charCode) == 'number') {
            return e.charCode;
        }
        else {
            return null;
        }
    }

    function monorail_formhelper_getevent(e) {
        if (!e) {
            if (window.event) {
                return window.event;
            }
            else {
                return null;
            }
        }
        else {
            return e;
        }
    }

    function monorail_formhelper_mask(e, elem, loc, delim) {
        e = monorail_formhelper_getevent(e);
        var keycode = monorail_formhelper_getkeycode(e);

        var locs = loc.split(',');
        var str = elem.value;

        for (var i = 0; i <= locs.length; i++) {
            for (var k = 0; k <= str.length; k++) {
                if (k == locs[i]) {
                    if (str.substring(k, k + 1) != delim) {
                        if (keycode != 8) {
                            str = str.substring(0, k) + delim + str.substring(k, str.length);
                        }
                    }
                }
            }
        }
        elem.value = str
    }

    /*
    * Really easy field validation with Prototype
    * http://tetlaw.id.au/view/javascript/really-easy-field-validation
    * Andrew Tetlaw
    * Version 1.5.4.1 (2007-01-05)
    * 
    * Copyright (c) 2007 Andrew Tetlaw
    * Permission is hereby granted, free of charge, to any person
    * obtaining a copy of this software and associated documentation
    * files (the "Software"), to deal in the Software without
    * restriction, including without limitation the rights to use, copy,
    * modify, merge, publish, distribute, sublicense, and/or sell copies
    * of the Software, and to permit persons to whom the Software is
    * furnished to do so, subject to the following conditions:
    * 
    * The above copyright notice and this permission notice shall be
    * included in all copies or substantial portions of the Software.
    * 
    * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
    * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
    * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    * SOFTWARE.
    * 
    */
    var Validator = Class.create();

    Validator.prototype = {
        initialize: function (className, error, test, options) {
            if (typeof test == 'function') {
                this.options = $H(options);
                this._test = test;
            } else {
                this.options = $H(test);
                this._test = function () { return true };
            }
            this.error = error || 'Validation failed.';
            this.className = className;
        },
        test: function (v, elm) {
            return (this._test(v, elm) && this.options.all(function (p) {
                return Validator.methods[p.key] ? Validator.methods[p.key](v, elm, p.value) : true;
            }));
        }
    }
    Validator.methods = {
        pattern: function (v, elm, opt) { return Validation.get('IsEmpty').test(v) || opt.test(v) },
        minLength: function (v, elm, opt) { return Validation.get('IsEmpty').test(v) || v.length >= opt },
        maxLength: function (v, elm, opt) { return Validation.get('IsEmpty').test(v) || v.length <= opt },
        min: function (v, elm, opt) { return Validation.get('IsEmpty').test(v) || v >= parseFloat(opt) },
        max: function (v, elm, opt) { return Validation.get('IsEmpty').test(v) || v <= parseFloat(opt) },
        notOneOf: function (v, elm, opt) {
            return $A(opt).all(function (value) {
                return v != value;
            })
        },
        oneOf: function (v, elm, opt) {
            return $A(opt).any(function (value) {
                return v == value;
            })
        },
        is: function (v, elm, opt) { return v == opt },
        isNot: function (v, elm, opt) { return v != opt },
        equalToField: function (v, elm, opt) { return v == $F(opt) },
        notEqualToField: function (v, elm, opt) { return v != $F(opt) },
        include: function (v, elm, opt) {
            return $A(opt).all(function (value) {
                return Validation.get(value).test(v, elm);
            })
        }
    }

    var Validation = Class.create();

    Validation.prototype = {
        initialize: function (form, options) {
            this.options = Object.extend({
                onSubmit: true,
                stopOnFirst: false,
                immediate: false,
                focusOnError: true,
                useTitles: false,
                onFormValidate: function (result, form) { },
                onElementValidate: function (result, elm) { }
            }, options || {});
            this.form = $(form);
            if (this.options.onSubmit) Event.observe(this.form, 'submit', this.onSubmit.bind(this), false);
            if (this.options.immediate) {
                var useTitles = this.options.useTitles;
                var callback = this.options.onElementValidate;
                Form.getElements(this.form).each(function (input) { // Thanks Mike!
                    Event.observe(input, 'blur', function (ev) { Validation.validate(Event.element(ev), { useTitle: useTitles, onElementValidate: callback }); });
                });
            }
        },
        onSubmit: function (ev) {
            if (!this.validate()) Event.stop(ev);
        },
        validate: function () {
            var result = false;
            var useTitles = this.options.useTitles;
            var callback = this.options.onElementValidate;
            if (this.options.stopOnFirst) {
                result = Form.getElements(this.form).all(function (elm) { return Validation.validate(elm, { useTitle: useTitles, onElementValidate: callback }); });
            } else {
                result = Form.getElements(this.form).collect(function (elm) { return Validation.validate(elm, { useTitle: useTitles, onElementValidate: callback }); }).all();
            }
            if (!result && this.options.focusOnError) {
                Form.getElements(this.form).findAll(function (elm) { return $(elm).hasClassName('validation-failed') }).first().focus()
            }
            this.options.onFormValidate(result, this.form);
            return result;
        },
        reset: function () {
            Form.getElements(this.form).each(Validation.reset);
        }
    }

    Object.extend(Validation, {
        validate: function (elm, options) {
            options = Object.extend({
                useTitle: false,
                onElementValidate: function (result, elm) { }
            }, options || {});
            elm = $(elm);
            var cn = elm.classNames();
            return result = cn.all(function (value) {
                var test = Validation.test(value, elm, options.useTitle);
                options.onElementValidate(test, elm);
                return test;
            });
        },
        test: function (name, elm, useTitle) {
            var v = Validation.get(name);
            var prop = '__advice' + name.camelize();
            try {
                if (Validation.isVisible(elm) && !v.test($F(elm), elm)) {
                    if (!elm[prop]) {
                        var advice = Validation.getAdvice(name, elm);
                        if (advice == null) {
                            var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
                            advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) + '" style="display:none">' + errorMsg + '</div>'
                            switch (elm.type.toLowerCase()) {
                                case 'checkbox':
                                case 'radio':
                                    var p = elm.parentNode;
                                    if (p) {
                                        new Insertion.Bottom(p, advice);
                                    } else {
                                        new Insertion.After(elm, advice);
                                    }
                                    break;
                                default:
                                    new Insertion.After(elm, advice);
                            }
                            advice = Validation.getAdvice(name, elm);
                        }
                        if (typeof Effect == 'undefined') {
                            advice.style.display = 'block';
                        } else {
                            new Effect.Appear(advice, { duration: 1 });
                        }
                    }
                    elm[prop] = true;
                    elm.removeClassName('validation-passed');
                    elm.addClassName('validation-failed');
                    return false;
                } else {
                    var advice = Validation.getAdvice(name, elm);
                    if (advice != null) advice.hide();
                    elm[prop] = '';
                    elm.removeClassName('validation-failed');
                    elm.addClassName('validation-passed');
                    return true;
                }
            } catch (e) {
                throw (e)
            }
        },
        isVisible: function (elm) {
            while (elm.tagName != 'BODY') {
                if (!$(elm).visible()) return false;
                elm = elm.parentNode;
            }
            return true;
        },
        getAdvice: function (name, elm) {
            return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
        },
        getElmID: function (elm) {
            return elm.id ? elm.id : elm.name;
        },
        reset: function (elm) {
            elm = $(elm);
            var cn = elm.classNames();
            cn.each(function (value) {
                var prop = '__advice' + value.camelize();
                if (elm[prop]) {
                    var advice = Validation.getAdvice(value, elm);
                    advice.hide();
                    elm[prop] = '';
                }
                elm.removeClassName('validation-failed');
                elm.removeClassName('validation-passed');
            });
        },
        add: function (className, error, test, options) {
            var nv = {};
            nv[className] = new Validator(className, error, test, options);
            Object.extend(Validation.methods, nv);
        },
        addAllThese: function (validators) {
            var nv = {};
            $A(validators).each(function (value) {
                nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
            });
            Object.extend(Validation.methods, nv);
        },
        get: function (name) {
            return Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
        },
        methods: {
            '_LikeNoIDIEverSaw_': new Validator('_LikeNoIDIEverSaw_', '', {})
        }
    });

    Validation.add('IsEmpty', '', function (v) {
        return ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
    });

    Validation.addAllThese([
	['required', 'This is a required field.', function (v) {
	    return !Validation.get('IsEmpty').test(v);
	} ],
	['validate-number', 'Please enter a valid number in this field.', function (v) {
	    return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
	} ],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function (v) {
	    return Validation.get('IsEmpty').test(v) || !/[^\d]/.test(v);
	} ],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
	    return Validation.get('IsEmpty').test(v) || /^[a-zA-Z]+$/.test(v)
	} ],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function (v) {
	    return Validation.get('IsEmpty').test(v) || !/\W/.test(v)
	} ],
	['validate-date', 'Please enter a valid date.', function (v) {
	    var test = new Date(v);
	    return Validation.get('IsEmpty').test(v) || !isNaN(test);
	} ],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
	    return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
	} ],
	['validate-url', 'Please enter a valid URL.', function (v) {
	    return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
	} ],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function (v) {
	    if (Validation.get('IsEmpty').test(v)) return true;
	    var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
	    if (!regex.test(v)) return false;
	    var d = new Date(v.replace(regex, '$2/$1/$3'));
	    return (parseInt(RegExp.$2, 10) == (1 + d.getMonth())) &&
							(parseInt(RegExp.$1, 10) == d.getDate()) &&
							(parseInt(RegExp.$3, 10) == d.getFullYear());
	} ],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function (v) {
	    // [$]1[##][,###]+[.##]
	    // [$]1###+[.##]
	    // [$]0.##
	    // [$].##
	    return Validation.get('IsEmpty').test(v) || /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
	} ],
	['validate-selection', 'Please make a selection', function (v, elm) {
	    return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
	} ],
	['validate-one-required', 'Please select one of the above options.', function (v, elm) {
	    var p = elm.parentNode;
	    var options = p.getElementsByTagName('INPUT');
	    return $A(options).any(function (elm) {
	        return $F(elm);
	    });
	} ]
]);


// Facebox for prototype

	var Facebox = Class.create({
	    initialize: function (extra_set) {
	        this.settings = {
	            loading_image: '/javascript/facebox/loading.gif',
	            close_image: '/javascript/facebox/closebox.png',
	            image_types: new RegExp('\.' + ['png', 'jpg', 'jpeg', 'gif'].join('|') + '$', 'i'),
	            inited: true,
	            facebox_html: '\
 <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img src="/javascript/facebox/closebox.png" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
	        };
	        if (extra_set) Object.extend(this.settings, extra_set);
	        $(document.body).insert({ bottom: this.settings.facebox_html });

	        this.preload = [new Image(), new Image()];
	        this.preload[0].src = this.settings.close_image;
	        this.preload[1].src = this.settings.loading_image;

	        f = this;
	        $$('#facebox .b:first, #facebox .bl, #facebox .br, #facebox .tl, #facebox .tr').each(function (elem) {
	            f.preload.push(new Image());
	            f.preload.slice(-1).src = elem.getStyle('background-image').replace(/url\((.+)\)/, '$1');
	        });

	        this.facebox = $('facebox');
	        this.keyPressListener = this.watchKeyPress.bindAsEventListener(this);

	        this.watchClickEvents();
	        fb = this;
	        Event.observe($$('#facebox .close').first(), 'click', function (e) {
	            Event.stop(e);
	            fb.close()
	        });
	        Event.observe($$('#facebox .close_image').first(), 'click', function (e) {
	            Event.stop(e);
	            fb.close()
	        });
	    },

	    watchKeyPress: function (e) {
	        // Close if espace is pressed or if there's a click outside of the facebox
	        if (e.keyCode == 27 || !Event.element(e).descendantOf(this.facebox)) this.close();
	    },

	    watchClickEvents: function (e) {
	        var f = this;
	        $$('a[rel=facebox]').each(function (elem, i) {
	            Event.observe(elem, 'click', function (e) {
	                Event.stop(e);
	                f.click_handler(elem, e);
	            });
	        });
	    },

	    loading: function () {
	        if ($$('#facebox .loading').length == 1) return true;

	        contentWrapper = $$('#facebox .content').first();
	        contentWrapper.childElements().each(function (elem, i) {
	            elem.remove();
	        });
	        contentWrapper.insert({ bottom: '<div class="loading"><img src="' + this.settings.loading_image + '"/><br class="clear" /></div>' });

	        var pageScroll = document.viewport.getScrollOffsets();
	        this.facebox.setStyle({
	            'top': pageScroll.top + (document.viewport.getHeight() / 10) + 'px',
	            'left': document.viewport.getWidth() / 2 - (this.facebox.getWidth() / 2) + 'px'
	        });

	        Event.observe(document, 'keypress', this.keyPressListener);
	        Event.observe(document, 'click', this.keyPressListener);
	    },

	    reveal: function (data, klass) {
	        this.loading();
	        load = $$('#facebox .loading').first();
	        if (load) load.remove();

	        contentWrapper = $$('#facebox .content').first();
	        if (klass) contentWrapper.addClassName(klass);
	        contentWrapper.insert({ bottom: data });

	        $$('#facebox .body').first().childElements().each(function (elem, i) {
	            elem.show();
	        });

	        if (!this.facebox.visible()) new Effect.Appear(this.facebox, { duration: .3 });
	        this.facebox.setStyle({
	            'left': document.viewport.getWidth() / 2 - (this.facebox.getWidth() / 2) + 'px'
	        });

	        Event.observe(document, 'keypress', this.keyPressListener);
	        Event.observe(document, 'click', this.keyPressListener);
	    },

	    close: function () {
	        new Effect.Fade('facebox', { duration: .3 });
	    },

	    click_handler: function (elem, e) {
	        this.loading();
	        Event.stop(e);

	        // support for rel="facebox[.inline_popup]" syntax, to add a class
	        var klass = elem.rel.match(/facebox\[\.(\w+)\]/);
	        if (klass) klass = klass[1];

	        new Effect.Appear(this.facebox, { duration: .3 });

	        if (elem.href.match(/#/)) {
	            var url = window.location.href.split('#')[0];
	            var target = elem.href.replace(url + '#', '');
	            // var data      = $$(target).first();
	            var d = $(target);
	            // create a new element so as to not delete the original on close()
	            var data = new Element(d.tagName);
	            data.innerHTML = d.innerHTML;
	            this.reveal(data, klass);
	        } else if (elem.href.match(this.settings.image_types)) {
	            var image = new Image();
	            fb = this;
	            image.onload = function () {
	                fb.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
	            }
	            image.src = elem.href;
	        } else {
	            var fb = this;
	            var url = elem.href;
	            new Ajax.Request(url, {
	                method: 'get',
	                onFailure: function (transport) {
	                    fb.reveal(transport.responseText, klass);
	                },
	                onSuccess: function (transport) {
	                    fb.reveal(transport.responseText, klass);
	                }
	            });

	        }
	    }
	});

	var facebox;
	document.observe('dom:loaded', function () {
	    facebox = new Facebox();
	});
	var addNamespace = function (ns) {
	    var nsParts = ns.split("."); var root = window; for (var i = 0; i < nsParts.length; i++) {
	        if (typeof root[nsParts[i]] == "undefined") { root[nsParts[i]] = {}; }
	        root = root[nsParts[i]];
	    }
	}; Object.extend(window, { $: function () {
	    var elements = []; for (var i = 0; i < arguments.length; i++) {
	        var e = arguments[i]; if (typeof e == 'string') { e = document.getElementById(e); }
	        if (arguments.length == 1) { return e; }
	        elements.push(e);
	    }
	    return elements;
	}, Class: { create: function () { return function () { if (typeof this.initialize == "function") { this.initialize.apply(this, arguments); } }; } }
	}, false); addNamespace("MS.Debug"); MS.Debug = {}; addNamespace("MS.Position"); Object.extend(MS.Position, { getLocation: function (ele) {
	    var x = 0; var y = 0; var p; for (p = ele; p; p = p.offsetParent) { if (p.offsetLeft && p.offsetTop) { x += p.offsetLeft; y += p.offsetTop; } }
	    return { left: x, top: y };
	}, getBounds: function (ele) { var offset = MS.Position.getLocation(ele); var width = ele.offsetWidth; var height = ele.offsetHeight; return { left: offset.left, top: offset.top, width: width, height: height }; }, setLocation: function (ele, loc) { ele.style.position = "absolute"; ele.style.left = loc.left + "px"; ele.style.top = loc.top + "px"; }, setBounds: function (ele, rect) {
	    if (rect.left && rect.top) { MS.Position.setLocation(ele, rect); }
	    ele.style.width = rect.width + "px"; ele.style.height = rect.height + "px";
	}
	}, false); addNamespace("MS.Keys"); Object.extend(MS.Keys, { TAB: 9, ESC: 27, KEYUP: 38, KEYDOWN: 40, KEYLEFT: 37, KEYRIGHT: 39, SHIFT: 16, CTRL: 17, ALT: 18, ENTER: 13, getCode: function (e) {
	    e = MS.getEvent(e); if (e != null) { return e.keyCode; }
	    return -1;
	}
	}, false); Object.extend(MS, { setText: function (ele, text) {
	    if (ele == null) { return; }
	    if (document.all) { ele.innerText = text; } else { ele.textContent = text; }
	}, setHtml: function (ele, html) {
	    if (ele == null) { return; }
	    ele.innerHTML = html;
	}, cancelEvent: function (e) { e = MS.getEvent(e); if (window.event) { e.returnValue = false; } else if (e) { e.preventDefault(); e.stopPropagation(); } }, getEvent: function (e) {
	    if (window.event) { return window.event; }
	    if (e) { return e; }
	    return null;
	}, getTarget: function (e) {
	    e = MS.getEvent(e); if (window.event) { return e.srcElement; }
	    if (e) { return e.target; }
	}
	}, false); var StringBuilder = function () { this.v = []; }; Object.extend(StringBuilder.prototype, { append: function (s) { this.v.push(s); }, appendLine: function (s) { this.v.push(s + "\r\n"); }, clear: function () { this.v.clear(); }, toString: function () { return this.v.join(""); } }, true); function getreturnurl() { $('returnurl').value = $('relurl').value; return true; }





    
    
   












// ONLOAD

// Fixes tab-index
	$j(document).ready(function () {
	    var tabindex = 0;
	    $j(":input[type=text]:visible :radio:visible, :checkbox:visible").each(function (i, e) {
	        $j(e).attr('tabindex', i);
	    });


        // Navigation: Set hover class on hover        
	    $j('#nav li.sub,#nav li.sub em').hover(function () {
	        $j(this).toggleClass('hover');
	    });
	    $j('#nav li.sub').mouseleave(function () {
	        $j(this).removeClass('hover');
	    });

        // Navigation: Toggle dropdown menu
	    $j('#nav li.sub em').click(function () {
	        var dropDown = $j(this).next('ul');

	        if ($j(dropDown).is(':hidden')) {
	            $j('#nav li ul').slideUp(200);
	            $j(dropDown).slideDown(200);
	        }
	        else {
	            $j(dropDown).slideUp(200);
	        }
	    });
        // Navigation: Hide dropdown on mouseleave
	    $j('#nav li ul').mouseleave(function () {
	        $j(this).delay(1000).slideUp(200);

	    });
        // Navigation: Abort hide dropdown on mouseleave
	    $j('#nav li ul').mouseenter(function () {
	        $j(this).stop(true, true);

	    });




	    // Show/Hide text on Focus / Blur input fields / textareas with calss .showHideValue
	    $j('.showHideValue').focus(function () {
	        if (this.value == this.defaultValue) {
	            this.value = '';
	        }
	        if (this.value != this.defaultValue) {
	            this.select();
	        }
	    }).blur(function () {
	        if ($j.trim(this.value) == '') {
	            this.value = (this.defaultValue ? this.defaultValue : '');
	        }
	    });

	    // Set focus on the first visible form element
	    $j(function () {
	        setTimeout(function () {
	            $j(':input:visible:first').focus();
	        }, 200);
	    });

	    // Change language
	    $j("#lang a").click(function () {
	        $j(this).hide();
	        $j("#langCode").show();
	    });
	    $j("select#langCode").change(function () {
	        $j(this).parent().submit();
	    });


	    // Disable input elements with .doDisable class inside a form
	    $j("form").submit(function () {
	        $j(":input.doDisable", this).attr("disabled", "disabled").val("Please wait....");
	    });



	    // IE fix for .subnav dropdown


	    $j(".subnav li").hover(function () {
	        $j(this).addClass("subnavHover");
	    }, function () {
	        $j(this).removeClass("subnavHover");
	    });

	    // #ChatbarComponent
	    var chatbarList = $j("#bottombar div.contactlist");
	    var notificationList = $j("#bottombar div.notifications");
	    var COOKIE_NAME = 'ChatbarState';
	    var ADDITIONAL_COOKIE_NAME = 'additional';
	    var options = { path: '/', expires: 10 };

	    // Reads cookie and sets status on userList
	    if ($j.cookie(COOKIE_NAME) == "open") {
	        $j(chatbarList).addClass("c-expanded");
	    } else {
	        $j(chatbarList).removeClass("c-expanded");
	    }

	    // Toggle notification show/hide trigger
	    $j("#n-button").click(function () {
	        $j(notificationList).toggleClass("n-expanded");
	        $j(chatbarList).removeClass('c-expanded');
	        chatlistStatus();
	    });

	    // Chat show/hide trigger 
	    $j(".c-button").click(function () {
	        $j(chatbarList).toggleClass("c-expanded");
	        $j(notificationList).removeClass("n-expanded");
	        chatlistStatus();
	    });

	    $j('.c-list .seeall').click(function () {
	        $j(chatbarList).removeClass('c-expanded');
	        chatlistStatus();
	    });

	    $j('#bottombar .list').css({ 'max-height': (($j(window).height()) - 250) + 'px' });

	    $j(window).resize(function () {
	        $j('#bottombar .list').css({ 'max-height': (($j(window).height()) - 250) + 'px' });
	    });



	    function chatlistStatus() {
	        if ($j(chatbarList).hasClass("c-expanded")) {
	            $j.cookie(COOKIE_NAME, 'open', options);
	        }
	        else {
	            $j.cookie(COOKIE_NAME, 'close', options);
	        }
	    }

	});

// Chatbar














//window.location = url; }



// FUNCTIONS 

// Change site within same network (Site Picker)
function changesite() {
    var url = "http://" + $('selsite').value + "/profile/changesite.rails";
    if ($('currentuid') != null && $("key") != null)
        url += "?uid=" + $F('currentuid') + "&guid=" + $F("key") + "&autologin=1&rtn=" + location.pathname + escape(location.search);
    window.location = url;
}


// Sign in => Remember where user tried to enter
function getreturnurl() {
    $('returnurl').value = $('relurl').value;
    return true;
}


//Multiple dropdowns (e.g. Country > State )
// Clear options in secondary select dropdowns
function subOptions(obj) {
    obj.options.length = 0;
}

// Refresh secondary select dropdowns 
function addOption(obj, value, text) {
    var optionP = document.createElement('option');
    optionP.text = text; optionP.value = value;
    try {
        obj.add(optionP, null);
    }
    catch (ex) {
        obj.add(optionP);
    }
}

// #nav li function
$j.fn.hoverClass = function (c) {
    return this.each(function () {
        $j(this).hover(function () {
            $j(this).addClass(c);
        },
	function () {
	    $j(this).removeClass(c);
	});
    });
};


// Supermode
function buysupermode() {
    var cuid = $('currentuid').value;
    var auto = false;
    if ($('Autosend').checked)
        auto = true;
    else
        auto = false;
    var key = $('key').value;
    Bloc.ObjectModel.Profile.BuySuperMode(cuid, key, auto, OnPostBuySuperModeCallBack);


}
function OnPostBuySuperModeCallBack(res) {
    if (res.value) {
        $('buysupermode').hide();
        $('lefttime').innerHTML = "20 days"
        $('lefttime1').innerHTML = "20 days"
        $('supermodelefttime').style.display = "block";
    }
}

function stopsupermode() {
    var cuid = $('currentuid').value;
    var key = $('key').value;
    Bloc.ObjectModel.Profile.StopSuperMode(cuid, key, OnPostStopSuperModeCallBack);

}

function OnPostStopSuperModeCallBack(res) {
    if (res.value) {
        $('buysupermode').style.display = "block";
        $('supermodelefttime').hide();
    }

}

// Verify Mobile Number
function sendphonenumber() {
    var phonenum = $('phoneNumber').value;
    var cuid = $('currentuid').value;
    if (phonenum.trim() != "")
        if (isNumber(phonenum)) {
            var key = $('key').value;
            Bloc.ObjectModel.Profile.SendMobileVerifyCode(cuid, key, phonenum, OnPostSendMobileVerifyCodeCallBack);
        }
        else {
            $('errmsg').innerHTML = 'You submittet a cellphone number that is not valid.';
            $('errmsg').style.display = "block";
        }
    else
        $('missphone').style.display = "block";
}
function OnPostSendMobileVerifyCodeCallBack(res) {
    if (res.value) {
        $('missphone').hide();
        $('receivemsg').style.display = "block";
        $('errmsg').hide();
    }
    else {
        $('missphone').hide();
        $('errmsg').innerHTML = 'You submittet a cellphone number that is not valid.';
        $('errmsg').style.display = "block";
        $('receivemsg').hide();

    }
}

function isNumber(s) {
    var regu = "^[0-9]+$";
    var re = new RegExp(regu);
    if (s.search(re) != -1) {
        return true;
    }
    else {
        return false;
    }
}

function verifymobilecode() {
    var verifyCode = $('verifyCode').value;
    var cuid = $('currentuid').value;
    var appid = $('appid').value;
    if (verifyCode.trim() != "") {
        var key = $('key').value;
        Bloc.ObjectModel.Profile.VerifyMobileCode(appid, cuid, key, verifyCode, OnPostVerifyMobileCodeCallBack);
    }
}
function OnPostVerifyMobileCodeCallBack(res) {
    if (res.value) {
        $('verifymsg').style.display = "block";
        $('errmsg').hide();
        $('receivemsg').hide();
        $('cellphoneismiss').hide();
        $('buysupermode').style.display = "block";
    }
    else {
        $('errmsg').innerHTML = 'Please ensure you have typed the correct verification code.';
        $('errmsg').style.display = "block";
        $('receivemsg').hide();
        $('verifymsg').hide();

    }
}



// jsdate.js

//Name: jsDate
//Desc: VBScript native Date functions emulated for Javascript
//Author: Rob Eberhardt, Slingshot Solutions - http://slingfive.com/


// used by dateAdd, dateDiff, datePart, weekdayName, and monthName
// note: less strict than VBScript's isDate, since JS allows invalid dates to overflow (e.g. Jan 32 transparently becomes Feb 1)
function isDate(p_Expression) {
    return !isNaN(new Date(p_Expression)); 	// <<--- this needs checking
}


// REQUIRES: isDate()
function dateAdd(p_Interval, p_Number, p_Date) {
    if (!isDate(p_Date)) { return "invalid date: '" + p_Date + "'"; }
    if (isNaN(p_Number)) { return "invalid number: '" + p_Number + "'"; }

    p_Number = new Number(p_Number);
    var dt = new Date(p_Date);
    switch (p_Interval.toLowerCase()) {
        case "yyyy":
            {// year
                dt.setFullYear(dt.getFullYear() + p_Number);
                break;
            }
        case "q":
            {		// quarter
                dt.setMonth(dt.getMonth() + (p_Number * 3));
                break;
            }
        case "m":
            {		// month
                dt.setMonth(dt.getMonth() + p_Number);
                break;
            }
        case "y": 	// day of year
        case "d": 	// day
        case "w":
            {		// weekday
                dt.setDate(dt.getDate() + p_Number);
                break;
            }
        case "ww":
            {	// week of year
                dt.setDate(dt.getDate() + (p_Number * 7));
                break;
            }
        case "h":
            {		// hour
                dt.setHours(dt.getHours() + p_Number);
                break;
            }
        case "n":
            {		// minute
                dt.setMinutes(dt.getMinutes() + p_Number);
                break;
            }
        case "s":
            {		// second
                dt.setSeconds(dt.getSeconds() + p_Number);
                break;
            }
        case "ms":
            {		// second
                dt.setMilliseconds(dt.getMilliseconds() + p_Number);
                break;
            }
        default:
            {
                return "invalid interval: '" + p_Interval + "'";
            }
    }
    return dt;
}



// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (defaults for both)
function dateDiff(p_Interval, p_Date1, p_Date2, p_firstdayofweek, p_firstweekofyear) {
    if (!isDate(p_Date1)) { return "invalid date: '" + p_Date1 + "'"; }
    if (!isDate(p_Date2)) { return "invalid date: '" + p_Date2 + "'"; }
    var dt1 = new Date(p_Date1);
    var dt2 = new Date(p_Date2);

    // get ms between dates (UTC) and make into "difference" date
    var iDiffMS = dt2.valueOf() - dt1.valueOf();
    var dtDiff = new Date(iDiffMS);

    // calc various diffs
    var nYears = dt2.getUTCFullYear() - dt1.getUTCFullYear();
    var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears != 0 ? nYears * 12 : 0);
    var nQuarters = parseInt(nMonths / 3); //<<-- different than VBScript, which watches rollover not completion

    var nMilliseconds = iDiffMS;
    var nSeconds = parseInt(iDiffMS / 1000);
    var nMinutes = parseInt(nSeconds / 60);
    var nHours = parseInt(nMinutes / 60);
    var nDays = parseInt(nHours / 24);
    var nWeeks = parseInt(nDays / 7);


    // return requested difference
    var iDiff = 0;
    switch (p_Interval.toLowerCase()) {
        case "yyyy": return nYears;
        case "q": return nQuarters;
        case "m": return nMonths;
        case "y": 		// day of year
        case "d": return nDays;
        case "w": return nDays;
        case "ww": return nWeeks; 	// week of year	// <-- inaccurate, WW should count calendar weeks (# of sundays) between
        case "h": return nHours;
        case "n": return nMinutes;
        case "s": return nSeconds;
        case "ms": return nMilliseconds; // millisecond	// <-- extension for JS, NOT available in VBScript
        default: return "invalid interval: '" + p_Interval + "'";
    }
}



// REQUIRES: isDate(), dateDiff()
// NOT SUPPORTED: firstdayofweek and firstweekofyear (does system default for both)
function datePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear) {
    if (!isDate(p_Date)) { return "invalid date: '" + p_Date + "'"; }

    var dtPart = new Date(p_Date);
    switch (p_Interval.toLowerCase()) {
        case "yyyy": return dtPart.getFullYear();
        case "q": return parseInt(dtPart.getMonth() / 3) + 1;
        case "m": return dtPart.getMonth() + 1;
        case "y": return dateDiff("y", "1/1/" + dtPart.getFullYear(), dtPart); 		// day of year
        case "d": return dtPart.getDate();
        case "w": return dtPart.getDay(); // weekday
        case "ww": return dateDiff("ww", "1/1/" + dtPart.getFullYear(), dtPart); 	// week of year
        case "h": return dtPart.getHours();
        case "n": return dtPart.getMinutes();
        case "s": return dtPart.getSeconds();
        case "ms": return dtPart.getMilliseconds(); // millisecond	// <-- extension for JS, NOT available in VBScript
        default: return "invalid interval: '" + p_Interval + "'";
    }
}


// REQUIRES: isDate()
// NOT SUPPORTED: firstdayofweek (does system default)
function weekdayName(p_Date, p_abbreviate) {
    if (!isDate(p_Date)) {
        return "invalid date: '" + p_Date + "'";
    }
    var dt = new Date(p_Date);
    var retVal = dt.toString().split(' ')[0];
    var retVal = Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')[dt.getUTCDay()];
    if (p_abbreviate == true) { retVal = retVal.substring(0, 3) } // abbr to 1st 3 chars
    return retVal;
}
// REQUIRES: isDate()
function monthName(p_Date, p_abbreviate) {
    if (!isDate(p_Date)) { return "invalid date: '" + p_Date + "'"; }
    var dt = new Date(p_Date);
    var retVal = Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')[dt.getUTCMonth()];
    if (p_abbreviate == true) { retVal = retVal.substring(0, 3) } // abbr to 1st 3 chars
    return retVal;
}




// bootstrap different capitalizations
function IsDate(p_Expression) {
    return isDate(p_Expression);
}
function DateAdd(p_Interval, p_Number, p_Date) {
    return dateAdd(p_Interval, p_Number, p_Date);
}
function DateDiff(p_interval, p_date1, p_date2, p_firstdayofweek, p_firstweekofyear) {
    return dateDiff(p_interval, p_date1, p_date2, p_firstdayofweek, p_firstweekofyear);
}
function DatePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear) {
    return datePart(p_Interval, p_Date, p_firstdayofweek, p_firstweekofyear);
}
function WeekdayName(p_Date) {
    return weekdayName(p_Date);
}
function MonthName(p_Date) {
    return monthName(p_Date);
}



// Cookie 
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" &&
        typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

// utility function called by getCookie( )

function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}
// primary function to retrieve cookie by name

function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return "";
}
// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}



// remove the cookie by setting ancient expiration date
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

//  
//   ForDigit (Person Tagging in Photos)
//
function ForDight(Dight, How) {
    Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
    return Dight;
}


//
//   Search List 
//

var stringfragment = '<script[^>]*>([\\S\\s]*?)<\/script>';
var checkguestbookidinsearchlist;
var pagesize = 50;
var enablemenudiv = true;
var enablemenuul = true;

// Search input in header
function seach_list() {
    getusers();
}
function getusers() {
    if ($('inputsearchuser').value.trim() != "") {
        searchword = null;
        window.location.href = '../search/quicksearch.rails?UN=' + $('inputsearchuser').value;
    }
    else {
        return false;
    }

}

// Invite Friend (move to correct page)
function SendInviteMessage() {
    var inviteemail = $('sendinviteemail').value;
    if (inviteemail.trim() == "") {
        $('pmessage').innerHTML = "Please input your friend's email";
        $('diverror').style.display = "block";
        return false;
    }

    var inaccurate = /(@.*@)|(..)|(@.)|(.@)|(^.)/;
    var pattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!(inaccurate.test(inviteemail) && pattern.test(inviteemail))) {
        $('pmessage').innerHTML = "Please input the right email";
        $('diverror').style.display = "block";
        return false;
    }
    var cuid = $('currentuid').value;
    var appid = $('appid').value;
    var key = $('key').value;
    var siteid = $('siteid').value;
    Bloc.ObjectModel.Registration.InviteFriendsInSearchList(appid, cuid, key, inviteemail, siteid, OnPostInviteFriendsInSearchListCallBack);

}

function InviteFriend() {
    var emails = $('uniqueid').getElementsByTagName('input');
    var inaccurate = /(@.*@)|(..)|(@.)|(.@)|(^.)/;
    var pattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    var cuid = $('currentuid').value;
    var appid = $('appid').value;
    var key = $('key').value;
    var siteid = $('siteid').value;

    for (var i = 0, n = emails.length; i < n; i++) {
        inviteemail = emails[i].value;
        if ((inaccurate.test(inviteemail) && pattern.test(inviteemail))) {
            Bloc.ObjectModel.Registration.InviteFriendsInSearchList(appid, cuid, key, inviteemail, siteid);
        }
        emails[i].value = "";
    }
    $('uniqueid').hide();
    $('uniqueid1').style.display = "block";
}

function InviteMore() {
    $('uniqueid1').hide();
    $('uniqueid').style.display = "block";
}


function OnPostInviteFriendsInSearchListCallBack(res) {
    if (res.value) {
        $('sendinviteemail').value = "";
        $('okmessageBox').style.display = "block";
        $('diverror').hide();
    }
    else {
        $('pmessage').innerHTML = "Try again";
        $('diverror').style.display = "block";
        $('okmessageBox').hide();
    }


}


function RequestServer() {
    var appid;
    var strjosn;
    var cuid;
    try {
        appid = document.getElementById('appid').value;
        cuid = document.getElementById('currentuid').value;
        strjosn = Bloc.ObjectModel.Profile.GetRandomProfileForHeadImageFromCache(appid, cuid, 1, 4, Alternate);
    }
    catch (e) {
        strjosn = '';
    }

    return strjosn;
}


function getreturnurl() {
    $('returnurl').value = $('relurl').value;
    return true;
}

