﻿/// <reference path="~/UI/JScript/jquery-1.2.6.js" />
var RootUrl = "";
var serviceUrl = "";
var proxy;
var visitorSilverlightVersion = "";
var trackLocation = false;

//v4.0.50401.0
// Silverlight.js
if (!window.Silverlight) window.Silverlight = {}; Silverlight._silverlightCount = 0; Silverlight.__onSilverlightInstalledCalled = false; Silverlight.fwlinkRoot = "http://go2.microsoft.com/fwlink/?LinkID="; Silverlight.__installationEventFired = false; Silverlight.onGetSilverlight = null; Silverlight.onSilverlightInstalled = function() { window.location.reload(false) }; Silverlight.isInstalled = function(b) { if (b == undefined) b = null; var a = false, m = null; try { var i = null, j = false; if (window.ActiveXObject) try { i = new ActiveXObject("AgControl.AgControl"); if (b === null) a = true; else if (i.IsVersionSupported(b)) a = true; i = null } catch (l) { j = true } else j = true; if (j) { var k = navigator.plugins["Silverlight Plug-In"]; if (k) if (b === null) a = true; else { var h = k.description; if (h === "1.0.30226.2") h = "2.0.30226.2"; var c = h.split("."); while (c.length > 3) c.pop(); while (c.length < 4) c.push(0); var e = b.split("."); while (e.length > 4) e.pop(); var d, g, f = 0; do { d = parseInt(e[f]); g = parseInt(c[f]); f++ } while (f < e.length && d === g); if (d <= g && !isNaN(d)) a = true } } } catch (l) { a = false } return a }; Silverlight.WaitForInstallCompletion = function() { if (!Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled) { try { navigator.plugins.refresh() } catch (a) { } if (Silverlight.isInstalled(null) && !Silverlight.__onSilverlightInstalledCalled) { Silverlight.onSilverlightInstalled(); Silverlight.__onSilverlightInstalledCalled = true } else setTimeout(Silverlight.WaitForInstallCompletion, 3e3) } }; Silverlight.__startup = function() { navigator.plugins.refresh(); Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null); if (!Silverlight.isBrowserRestartRequired) { Silverlight.WaitForInstallCompletion(); if (!Silverlight.__installationEventFired) { Silverlight.onInstallRequired(); Silverlight.__installationEventFired = true } } else if (window.navigator.mimeTypes) { var b = navigator.mimeTypes["application/x-silverlight-2"], c = navigator.mimeTypes["application/x-silverlight-2-b2"], d = navigator.mimeTypes["application/x-silverlight-2-b1"], a = d; if (c) a = c; if (!b && (d || c)) { if (!Silverlight.__installationEventFired) { Silverlight.onUpgradeRequired(); Silverlight.__installationEventFired = true } } else if (b && a) if (b.enabledPlugin && a.enabledPlugin) if (b.enabledPlugin.description != a.enabledPlugin.description) if (!Silverlight.__installationEventFired) { Silverlight.onRestartRequired(); Silverlight.__installationEventFired = true } } if (!Silverlight.disableAutoStartup) if (window.removeEventListener) window.removeEventListener("load", Silverlight.__startup, false); else window.detachEvent("onload", Silverlight.__startup) }; if (!Silverlight.disableAutoStartup) if (window.addEventListener) window.addEventListener("load", Silverlight.__startup, false); else window.attachEvent("onload", Silverlight.__startup); Silverlight.createObject = function(m, f, e, k, l, h, j) { var d = {}, a = k, c = l; d.version = a.version; a.source = m; d.alt = a.alt; if (h) a.initParams = h; if (a.isWindowless && !a.windowless) a.windowless = a.isWindowless; if (a.framerate && !a.maxFramerate) a.maxFramerate = a.framerate; if (e && !a.id) a.id = e; delete a.ignoreBrowserVer; delete a.inplaceInstallPrompt; delete a.version; delete a.isWindowless; delete a.framerate; delete a.data; delete a.src; delete a.alt; if (Silverlight.isInstalled(d.version)) { for (var b in c) if (c[b]) { if (b == "onLoad" && typeof c[b] == "function" && c[b].length != 1) { var i = c[b]; c[b] = function(a) { return i(document.getElementById(e), j, a) } } var g = Silverlight.__getHandlerName(c[b]); if (g != null) { a[b] = g; c[b] = null } else throw "typeof events." + b + " must be 'function' or 'string'"; } slPluginHTML = Silverlight.buildHTML(a) } else slPluginHTML = Silverlight.buildPromptHTML(d); if (f) f.innerHTML = slPluginHTML; else return slPluginHTML }; Silverlight.buildHTML = function(a) { var b = []; b.push('<object type="application/x-silverlight" data="data:application/x-silverlight,"'); if (a.id != null) b.push(' id="' + Silverlight.HtmlAttributeEncode(a.id) + '"'); if (a.width != null) b.push(' width="' + a.width + '"'); if (a.height != null) b.push(' height="' + a.height + '"'); b.push(" >"); delete a.id; delete a.width; delete a.height; for (var c in a) if (a[c]) b.push('<param name="' + Silverlight.HtmlAttributeEncode(c) + '" value="' + Silverlight.HtmlAttributeEncode(a[c]) + '" />'); b.push("</object>"); return b.join("") }; Silverlight.createObjectEx = function(b) { var a = b, c = Silverlight.createObject(a.source, a.parentElement, a.id, a.properties, a.events, a.initParams, a.context); if (a.parentElement == null) return c }; Silverlight.buildPromptHTML = function(b) { var a = "", d = Silverlight.fwlinkRoot, c = b.version; if (b.alt) a = b.alt; else { if (!c) c = ""; a = "<a href='javascript:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>"; a = a.replace("{1}", c); a = a.replace("{2}", d + "108181") } return a }; Silverlight.getSilverlight = function(e) { if (Silverlight.onGetSilverlight) Silverlight.onGetSilverlight(); var b = "", a = String(e).split("."); if (a.length > 1) { var c = parseInt(a[0]); if (isNaN(c) || c < 2) b = "1.0"; else b = a[0] + "." + a[1] } var d = ""; if (b.match(/^\d+\056\d+$/)) d = "&v=" + b; Silverlight.followFWLink("149156" + d) }; Silverlight.followFWLink = function(a) { top.location = Silverlight.fwlinkRoot + String(a) }; Silverlight.HtmlAttributeEncode = function(c) { var a, b = ""; if (c == null) return null; for (var d = 0; d < c.length; d++) { a = c.charCodeAt(d); if (a > 96 && a < 123 || a > 64 && a < 91 || a > 43 && a < 58 && a != 47 || a == 95) b = b + String.fromCharCode(a); else b = b + "&#" + a + ";" } return b }; Silverlight.default_error_handler = function(e, b) { var d, c = b.ErrorType; d = b.ErrorCode; var a = "\nSilverlight error message     \n"; a += "ErrorCode: " + d + "\n"; a += "ErrorType: " + c + "       \n"; a += "Message: " + b.ErrorMessage + "     \n"; if (c == "ParserError") { a += "XamlFile: " + b.xamlFile + "     \n"; a += "Line: " + b.lineNumber + "     \n"; a += "Position: " + b.charPosition + "     \n" } else if (c == "RuntimeError") { if (b.lineNumber != 0) { a += "Line: " + b.lineNumber + "     \n"; a += "Position: " + b.charPosition + "     \n" } a += "MethodName: " + b.methodName + "     \n" } alert(a) }; Silverlight.__cleanup = function() { for (var a = Silverlight._silverlightCount - 1; a >= 0; a--) window["__slEvent" + a] = null; Silverlight._silverlightCount = 0; if (window.removeEventListener) window.removeEventListener("unload", Silverlight.__cleanup, false); else window.detachEvent("onunload", Silverlight.__cleanup) }; Silverlight.__getHandlerName = function(b) { var a = ""; if (typeof b == "string") a = b; else if (typeof b == "function") { if (Silverlight._silverlightCount == 0) if (window.addEventListener) window.addEventListener("unload", Silverlight.__cleanup, false); else window.attachEvent("onunload", Silverlight.__cleanup); var c = Silverlight._silverlightCount++; a = "__slEvent" + c; window[a] = b } else a = null; return a }; Silverlight.onRequiredVersionAvailable = function() { }; Silverlight.onRestartRequired = function() { }; Silverlight.onUpgradeRequired = function() { }; Silverlight.onInstallRequired = function() { }; Silverlight.IsVersionAvailableOnError = function(d, a) { var b = false; try { if (a.ErrorCode == 8001 && !Silverlight.__installationEventFired) { Silverlight.onUpgradeRequired(); Silverlight.__installationEventFired = true } else if (a.ErrorCode == 8002 && !Silverlight.__installationEventFired) { Silverlight.onRestartRequired(); Silverlight.__installationEventFired = true } else if (a.ErrorCode == 5014 || a.ErrorCode == 2106) { if (Silverlight.__verifySilverlight2UpgradeSuccess(a.getHost())) b = true } else b = true } catch (c) { } return b }; Silverlight.IsVersionAvailableOnLoad = function(b) { var a = false; try { if (Silverlight.__verifySilverlight2UpgradeSuccess(b.getHost())) a = true } catch (c) { } return a }; Silverlight.__verifySilverlight2UpgradeSuccess = function(d) { var c = false, b = "4.0.50401", a = null; try { if (d.IsVersionSupported(b + ".99")) { a = Silverlight.onRequiredVersionAvailable; c = true } else if (d.IsVersionSupported(b + ".0")) a = Silverlight.onRestartRequired; else a = Silverlight.onUpgradeRequired; if (a && !Silverlight.__installationEventFired) { a(); Silverlight.__installationEventFired = true } } catch (e) { } return c }

//v4.0.50401.0
//Silverlight.supportedUserAgent.js
if (!window.Silverlight) window.Silverlight = {}; Silverlight.supportedUserAgent = function(g, f) { try { var b = null; if (f) b = f; else b = window.navigator.userAgent; var a = { OS: "Unsupported", Browser: "Unsupported" }; if (b.indexOf("Windows NT") >= 0 || b.indexOf("Mozilla/4.0 (compatible; MSIE 6.0)") >= 0) a.OS = "Windows"; else if (b.indexOf("PPC Mac OS X") >= 0) a.OS = "MacPPC"; else if (b.indexOf("Intel Mac OS X") >= 0) a.OS = "MacIntel"; else if (b.indexOf("Linux") >= 0) a.OS = "Linux"; if (a.OS != "Unsupported") if (b.indexOf("MSIE") >= 0) { if (navigator.userAgent.indexOf("Win64") == -1) if (parseInt(b.split("MSIE")[1]) >= 6) a.Browser = "MSIE" } else if (b.indexOf("Firefox") >= 0) { var e = b.split("Firefox/")[1].split("."), h = parseInt(e[0]); if (h >= 2) a.Browser = "Firefox"; else { var i = parseInt(e[1]); if (h == 1 && i >= 5) a.Browser = "Firefox" } } else if (b.indexOf("Chrome") >= 0) a.Browser = "Chrome"; else if (b.indexOf("Safari") >= 0) a.Browser = "Safari"; var d = parseInt(g), c = !(a.OS == "Unsupported" || a.Browser == "Unsupported" || a.OS == "Windows" && a.Browser == "Safari" || a.OS.indexOf("Mac") >= 0 && a.Browser == "MSIE" || a.OS.indexOf("Mac") >= 0 && a.Browser == "Chrome"); if (a.OS.indexOf("Windows") >= 0 && a.Browser == "Chrome" && d < 4) return false; if (a.OS == "MacPPC" && d > 1) return c && a.OS != "MacPPC"; if (a.OS == "Linux" && d > 2) return c && a.OS != "Linux"; if (g == "1.0") return c && b.indexOf("Windows NT 5.0") < 0; else return c } catch (j) { return false } }

if (!this.JSON) { this.JSON = {}; }
(function() {
    function f(n) { return n < 10 ? '0' + n : n; }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function(key) {
            debugger; return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
        }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key) { return this.valueOf(); };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function(a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
    function str(key, holder) {
        var i, k, v, 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 (Object.prototype.toString.apply(value) === '[object Array]') {
                    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 (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); 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;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {
            var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; }
            rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.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);
            }
            cx.lastIndex = 0; if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/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');
        };
    }
} ()); if (this.JSON && !this.JSON.parseWithDate) {
    var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/; var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/; JSON.parseWithDate = function(json) {
        try {
            var res = JSON.parse(json, function(key, value) {
                if (typeof value === 'string') {
                    var a = reISO.exec(value); if (a)
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); a = reMsAjax.exec(value); if (a) { var b = a[1].split(/[-+,.]/); return new Date(b[0] ? +b[0] : 0 - +b[1]); }
                }
                return value;
            }); return res;
        } catch (e) { throw new Error("JSON content could not be parsed"); return null; }
    }; JSON.stringifyWcf = function(json) {
        return JSON.stringify(json, function(key, value) {
            if (typeof value == "string") { var a = reISO.exec(value); if (a) { var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + ')/'; this[key] = val; return val; } }
            return value;
        })
    }; JSON.dateStringToDate = function(dtString) {
        var a = reISO.exec(dtString); if (a)
            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); a = reMsAjax.exec(dtString); if (a) { var b = a[1].split(/[-,.]/); return new Date(+b[0]); }
        return null;
    };
}


this.HttpClient = function(opt) {
    var _I = this; this.completed = null; this.errorHandler = null; this.errorMessage = ""; this.async = true; this.evalResult = false; this.isMsAjaxJson = false; this.contentType = "application/x-www-form-urlencoded"; this.method = "GET"; this.timeout = 20000; this.headers = {}; $.extend(_I, opt); this.appendHeader = function(header, value) { _I.headers[header] = value; }
    this.send = function(url, postData, completed, errorHandler) {
        completed = completed || _I.completed; errorHandler = errorHandler || _I.errorHandler; $.ajax({ url: url, data: postData, type: (postData ? "POST" : _I.method), processData: false, contentType: _I.contentType, timeout: _I.timeout, dataType: "text", global: false, async: _I.async, beforeSend: function(xhr) { for (var header in _I.headers) xhr.setRequestHeader(header, _I.headers[header]); }, success: function(result, status) {
            var errorException = null; if (_I.evalResult) {
                try {
                    result = JSON.parseWithDate(result); if (result != null) {
                        if (result.d && result.d.__type)
                            result = result.d; else if (_I.isMsAjaxJson) { for (var property in result) { result = result[property]; break; } }
                    }
                }
                catch (e)
{ errorException = new CallbackException(e); }
            }
            if (errorException) {
                if (errorHandler)
                    errorHandler(errorException, _I); return;
            }
            if (result && (result.isCallbackError || result.iscallbackerror)) {
                if (errorHandler)
                    errorHandler(result, _I);
            }
            if (completed)
                completed(result, _I);
        }, error: function(xhr, status) {
            var err = null; if (xhr.readyState == 4) {
                var res = xhr.responseText; if (res && res.charAt(0) == '{')
                    var err = JSON.parseWithDate(res); if (!err) {
                    if (xhr.status && xhr.status != 200)
                        err = new CallbackException(xhr.status + " " + xhr.statusText); else
                        err = new CallbackException("Callback Error: " + status); err.detail = res;
                }
            }
            if (!err)
                err = new CallbackException("Callback Error: " + status); if (errorHandler)
                errorHandler(err, _I, xhr);
        }
        });
    }
    this.returnError = function(message) {
        var error = new CallbackException(message); if (_I.errorHandler)
            _I.errorHandler(error, _I);
    }
}
this.ServiceProxy = function(serviceUrl) { var _I = this; this.isWcf = true; this.serviceUrl = serviceUrl; this.invoke = function(method, params, callback, errorCallback, isBare) { var json = _I.isWcf ? JSON.stringifyWcf(params) : JSON.stringify(params); var url = _I.serviceUrl + method; var http = new HttpClient({ contentType: "application/json", evalResult: true, isMsAjaxJson: !isBare }); http.send(url, json, callback, errorCallback); } }
this.AjaxMethodCallback = function(controlId, url, opt) {
    var _I = this; this.controlId = controlId; this.postbackMode = "PostMethodParametersOnly"; this.serverUrl = url; this.formName = null; this.resultMode = "json"; this.timeout = 20000; this.completed = null; this.errorHandler = null; $.extend(this, opt); this.Http = null; this.callMethod = function(methodName, parameters, callback, errorCallback) {
        _I.completed = callback; _I.errorHandler = errorCallback; var http = new HttpClient({ timeout: _I.timeout, evalResult: true }); _I.Http = http; var data = {}; if (_I.resultMode == "msajax") { http.isMsAjax = true; data = JSON.stringify(parameters); }
        else {
            var parmCount = 0; if (parameters.length) { parmCount = parameters.length; for (var x = 0; x < parmCount; x++) { data["Parm" + (x + 1).toString()] = JSON.stringify(parameters[x]); } }
            $.extend(data, { CallbackMethod: methodName, CallbackParmCount: parmCount, __WWEVENTCALLBACK: _I.controlId }); data = $.param(data) + "&"
        }
        var formName = _I.formName || document.forms.length > 0 ? document.forms[0].id : ""; if (_I.postbackMode == "Post")
            data += $("#" + formName).serialize(); else if (_I.postbackMode == "PostNoViewstate")
            data += $().serializeNoViewState(); else if (this.postbackMode == "Get") {
            Url = this.serverUrl; if (Url.indexOf('?') > -1)
                Url += data; else
                Url += "?" + data; return http.send(Url, null, _I.onHttpCallback, _I.onHttpCallback);
        }
        return http.send(this.serverUrl, data, _I.onHttpCallback, _I.onHttpCallback);
    }
    this.onHttpCallback = function(result) {
        if (result && (result.isCallbackError || result.iscallbackerror)) {
            if (_I.errorHandler)
                _I.errorHandler(result, _I); return;
        }
        if (_I.completed != null)
            _I.completed(result, _I);
    }
}
ajaxJson = function(url, parm, callback, errorCallback, options) {
    var ser = parm; var opt = { method: "POST", contentType: "application/json", noPostEncoding: false }; $.extend(opt, options); var http = new HttpClient(opt); http.evalResult = true; if (!opt.noPostEncoding && opt.method == "POST")
        ser = JSON.stringify(parm); http.send(url, ser, callback, errorCallback);
}
ajaxCallMethod = function(url, method, parms, callback, errorCallback, options) { var proxy = new AjaxMethodCallback(null, url, options); proxy.callMethod(method, parms, callback, errorCallback); }
function onPageError(error) {
    //alert(error.message); // TODO: remove!
    showStatus(error.message, 1, true); 
    writeToLog(error.message, errorLogType);
    
}
this.CallbackException = function(message, detail) {
    this.isCallbackError = true; if (typeof (message) == "object") {
        if (message.message)
            this.message = message.message; else if (message.Message)
            this.message = message.Message;
    }
    else
        this.message = message; if (detail)
        this.detail = detail; else
        this.detail = null;
}
this.StatusBar = function(sel, opt) {
    var _I = this; var _sb = null; this.elementId = "_showstatus"; this.prependMultiline = true; this.showCloseButton = false; this.afterTimeoutText = null; this.cssClass = "statusbar"; this.highlightClass = "statusbarhighlight"; this.closeButtonClass = "statusbarclose"; this.additive = false; if (sel)
        _sb = $(sel); if (opt)
        $.extend(this, opt); if (!_sb) {
        _sb = $("<div id='_statusbar' class='" + _I.cssClass + "'>" + "<div class='" + _I.closeButtonClass + "'>" +
(_I.showCloseButton ? " X </div></div>" : "")).appendTo(document.body).show();
    }
    if (_I.showCloseButton)
        $("." + _I.cssClass).click(function(e) { $(_sb).hide(); }); this.show = function(message, timeout, isError, additive) {
            if (message == "hide")
                return _I.hide(); if (_I.additive) {
                var html = $("<div style='margin-bottom: 2px;'>" + message + "</div>"); if (_I.prependMultiline)
                    _sb.prepend(html); else
                    _sb.append(html);
            }
            else {
                if (!_I.showCloseButton)
                    _sb.text(message); else { var t = _sb.find("div.statusbarclose"); _sb.text(message).prepend(t); }
            }
            _sb.show().maxZIndex(); if (timeout) {
                _sb.addClass(_I.highlightClass); setTimeout(function() {
                    _sb.removeClass(_I.highlightClass); if (_I.afterTimeoutText)
                        _I.show(_I.afterTimeoutText);
                }, timeout);
            }
            return _I;
        }
    this.hide = function() { _sb.hide(); return _I; }
    this.release = function() {
        if (_statusbar)
            $(_statusbar).remove();
    }
}
var __statusbar = null; this.showStatus = function(message, timeout, isHighlighted, additive) {
    if (!__statusbar)
        if (typeof message == "object") { __statusbar = new StatusBar(null, message).hide(); return; }
    else
        __statusbar = new StatusBar(); __statusbar.show(message, timeout, isHighlighted, additive);
}
$.fn.centerInClient = function(options) {
    var opt = { forceAbsolute: false, container: window, completed: null }; $.extend(opt, options); return this.each(function(i) {
        var el = $(this); var jWin = $(opt.container); var isWin = opt.container == window; if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body"); else
                el.remove().appendTo(jWin.get(0));
        }
        el.css("position", "absolute"); var heightFudge = 2.2; var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2; var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2; el.css({ left: x + jWin.scrollLeft(), top: y + jWin.scrollTop() }); var zi = el.css("zIndex"); if (!zi || zi == "auto")
            el.css("zIndex", 1); if (opt.completed)
            opt.completed(this);
    });
}
$.fn.moveToMousePosition = function(evt, options) { var opt = { left: 0, top: 0 }; $.extend(opt, options); return this.each(function() { var el = $(this); el.css({ left: evt.pageX + opt.left, top: evt.pageY + opt.top, position: "absolute" }); }); }
$.fn.shadow = function(action, options, refreshOnly) {
    if (typeof action == "object")
        options = action; var opt = { offset: 5, color: "#535353", opacity: 0.85, callback: null, zIndex: 100 }; $.extend(opt, options); this.each(function() {
            var el = $(this); var box = this; var sh = $("#" + el.get(0).id + "Shadow"); if (typeof action == "string") {
                if (action == "hide" || action == "remove") {
                    if (typeof box.style.MozBoxShadow == "string") { el.css("-moz-box-shadow", ""); return; }
                    else if (typeof box.style.WebkitBoxShadow == "string") { el.css("-webkit-box-shadow", ""); return; }
                    else { el.unwatch("_shadowMove"); sh.remove(); }
                }
                return;
            }
            el.css("position", "absolute"); if (typeof box.style.MozBoxShadow == "string") { el.css("-moz-box-shadow", String.format("{0}px {0}px {0}px {1}", opt.offset, opt.color)); return; }
            else if (typeof box.style.WebkitBoxShadow == "string") { el.css("-webkit-box-shadow", String.format("{0}px {0}px {0}px {1}", opt.offset, opt.color)); return; }
            var exists = true; if (sh.length < 1) {
                sh = $("<div style='height:1px;width:1px;'></div>").attr("id", el.get(0).id + "Shadow").insertAfter(el); var zi = el.css("zIndex"); if (!zi || zi == "auto") { el.css("zIndex", opt.zIndex); sh.css("zIndex", opt.zIndex - 1); }
                var shEl = sh.get(0); if (typeof shEl.style.filter == "string") { shEl.style.filter = 'progid:DXImageTransform.Microsoft.Blur(makeShadow=1, shadowOpacity=' + opt.opacity.toString() + ', pixelRadius=' + opt.offset + ')'; opt.offset = opt.offset - 4; }
                exists = false;
            }
            var vis = el.is(":visible"); if (!vis)
                el.show(); var pos = el.position(); sh.show().css({ position: "absolute", width: el.outerWidth(), height: el.outerHeight(), opacity: opt.opacity, background: opt.color, left: pos.left + opt.offset, top: pos.top + opt.offset }); if (!vis) { sh.hide(); el.hide(); }
            zIndex = el.css("zIndex"); if (zIndex && zIndex != "auto")
                sh.css("zIndex", zIndex - 1); else { el.css("zIndex", opt.zIndex); sh.css("zIndex", opt.zIndex - 1); }
            if (!exists) {
                el.watch("left,top,width,height,display,opacity,zIndex", function(w, i) {
                    if (el.is(":visible")) { $(this).shadow(opt); sh.css("opacity", el.css("opacity") * opt.opacity); }
                    else
                        sh.hide();
                }, 100, "_shadowMove");
            }
            if (opt.callback)
                opt.callback(sh);
        }); return this;
}
$.fn.tooltip = function(msg, timeout, options) {
    var opt = { cssClass: "", isHtml: false, shadowOffset: 2, onRelease: null }; $.extend(opt, options); return this.each(function() {
        var tp = new _ToolTip(this, opt); if (msg == "hide") { tp.hide(); return; }
        tp.show(msg, timeout, opt.isHtml);
    }); function _ToolTip(sel, opt) {
        var _I = this; var jEl = $(sel); this.cssClass = ""; this.onRelease = null; $.extend(_I, opt); var el = jEl.get(0); var tt = $("#" + el.id + "_tt"); this.show = function(msg, timeout, isHtml) {
            if (tt.length > 0)
                tt.remove(); tt = $("<div></div>").attr("id", el.id + "_tt"); $(document.body).append(tt); tt.css({ position: "absolute", display: "none", zIndex: 1000 }); if (_I.cssClass)
                tt.addClass(_I.cssClass); else
                tt.css({ background: "cornsilk", border: "solid 1px gray", fontSize: "0.80em", padding: 2 }); if (isHtml)
                tt.html(msg); else
                tt.text(msg); var pos = jEl.position(); var Left = pos.left + 5; var Top = pos.top + jEl.height() - 2; var Width = tt.width(); if (Width > 400)
                Width = 400; tt.css({ left: Left, top: Top, width: Width }); tt.show(); tt.shadow({ offset: opt.shadowOffset }); if (timeout && timeout > 0)
                setTimeout(function() {
                    if (_I.onRelease)
                        _I.onRelease.call(el, _I); _I.hide();
                }, timeout);
        }
        this.hide = function() {
            if (tt.length > 0)
                tt.fadeOut("slow", function() { tt.shadow("hide") });
        }
    }
}
$.fn.watch = function(props, func, interval, id) {
    if (!interval)
        interval = 200; if (!id)
        id = "_watcher"; return this.each(function() {
            var _t = this; var el = $(this); var fnc = function() { __watcher.call(_t, id) }; var itId = null; if (typeof (this.onpropertychange) == "object")
                el.bind("propertychange." + id, fnc); else if ($.browser.mozilla)
                el.bind("DOMAttrModified." + id, fnc); else
                itId = setInterval(fnc, interval); var data = { id: itId, props: props.split(","), func: func, vals: [props.split(",").length] }; $.each(data.vals, function(i) { data.vals[i] = el.css(data.props[i]); }); el.data(id, data);
        }); function __watcher(id) {
            var el = $(this); var w = el.data(id); var changed = false; var i = 0; for (i; i < w.props.length; i++) { var newVal = el.css(w.props[i]); if (w.vals[i] != newVal) { w.vals[i] = newVal; changed = true; break; } }
            if (changed && w.func) { var _t = this; w.func.call(_t, w, i) }
        }
}
$.fn.unwatch = function(id) {
    this.each(function() {
        var w = $(this).data(id); var el = $(this); el.removeData(); try {
            if (typeof (this.onpropertychange) == "object")
                el.unbind("propertychange." + id, fnc); else if ($.browser.mozilla)
                el.unbind("DOMAttrModified." + id, fnc); else
                clearInterval(w.id);
        }
        catch (e) { }
    }); return this;
}
$.fn.listSetData = function(items, options) {
    var opt = { noClear: false, dataValueField: null, dataTextField: null }; $.extend(opt, options); return this.each(function() {
        var el = $(this); if (items == null) { el.children().remove(); return; }
        if (!opt.noClear)
            el.children().remove(); if (items.Rows)
            items = items.Rows; var IsValueList = false; if (!opt.dataTextField && !opt.dataValueField)
            IsValueList = true; for (x = 0; x < items.length; x++) {
            var row = items[x]; if (IsValueList)
                el.listAddItem(row, row); else
                el.listAddItem(row[opt.dataTextField], row[opt.dataValueField]);
        }
    });
}
$.fn.listAddItem = function(text, value) { return this.each(function() { $(this).append($("<option></option>").attr("value", value).text(text)); }); }
$.fn.listSelectItem = function(value) {
    if (this.length < 1)
        return; var list = this.get(0); if (!list.options)
        return; for (var x = list.options.length - 1; x > -1; x--) { if (list.options[x].value == value) { list.options[x].selected = true; return; } }
}
$.fn.closable = function(options) {
    var opt = { handle: null, closeHandler: null, cssClass: "closebox", imageUrl: null, fadeOut: null }; $.extend(opt, options); return this.each(function(i) {
        var el = $(this); var pos = el.css("position"); if (!pos || pos == "static")
            el.css("position", "relative"); var h = opt.handle ? $(opt.handle).css({ position: "relative" }) : el; var div = opt.imageUrl ? $("<img />").attr("src", opt.imageUrl).css("cursor", "pointer") : $("<div></div>"); div.addClass(opt.cssClass).click(function(e) {
                if (opt.closeHandler)
                    if (!opt.closeHandler.call(this, e))
                    return; if (opt.fadeOut)
                    $(el).fadeOut(opt.fadeOut); else $(el).hide();
            }); if (opt.imageUrl) div.css("background-image", "none"); h.append(div);
    });
}
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    var def = { inc: 10, group: "*" }; $.extend(def, opt); var zmax = 0; $(def.group).each(function() { var cur = parseInt($(this).css('z-index')); zmax = cur > zmax ? cur : zmax; }); if (!this.jquery)
        return zmax; return this.each(function() { zmax += def.inc; $(this).css("z-index", zmax); });
}
var _tmplCache = {}
this.parseTemplate = function(str, data) {
    var err = ""; try {
        var func = _tmplCache[str]; if (!func) {
            var strFunc = "var p=[];with(obj){p.push('" +
str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^#]*#>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<#=(.+?)#>/g, "',$1,'").split("<#").join("');").split("#>").join("p.push('")
+ "');}return p.join('');"; func = new Function("obj", strFunc); _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.htmlEncode() + " # >";
}
String.prototype.htmlEncode = function() {
    var div = document.createElement('div'); if (typeof (div.textContent) == 'string')
        div.textContent = this.toString(); else
        div.innerText = this.toString(); return div.innerHTML;
}
String.prototype.trimEnd = function(c) {
    if (c)
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), ''); return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), ''); return this.replace(/^\s+/, '');
}
String.repeat = function(chr, count) { var str = ""; for (var x = 0; x < count; x++) { str += chr }; return str; }
String.prototype.padL = function(width, pad) {
    if (!width || width < 1)
        return this; if (!pad) pad = " "; var length = width - this.length
    if (length < 1) return this.substr(0, width); return (String.repeat(pad, length) + this).substr(0, width);
}
String.prototype.padR = function(width, pad) {
    if (!width || width < 1)
        return this; if (!pad) pad = " "; var length = width - this.length
    if (length < 1) this.substr(0, width); return (this + String.repeat(pad, length)).substr(0, width);
}
String.startsWith = function(str) { if (!str) return false; return this.substr(0, str.length) == str; }
String.prototype.escapeRegExp = function() { return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0"); }; String.format = function(frmt, args) {
    for (var x = 0; x < arguments.length; x++) { frmt = frmt.replace(new RegExp("\\{" + x.toString() + "\\}", "g"), arguments[x + 1]); }
    return frmt;
}
String.prototype.format = function() { var a = [this]; $.merge(a, arguments); return String.format.apply(this, a); }
String.prototype.isNumber = function() {
    if (this.length == 0) return false; if ("0123456789".indexOf(this.charAt(0)) > -1)
        return true; return false;
}
var _monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; Date.prototype.formatDate = function(format) {
    var date = this; if (!format)
        format = "MM/dd/yyyy"; var month = date.getMonth(); var year = date.getFullYear(); if (format.indexOf("yyyy") > -1)
        format = format.replace("yyyy", year.toString()); else if (format.indexOf("yy") > -1)
        format = format.replace("yy", year.toString().substr(2, 2)); format = format.replace("dd", date.getDate().toString().padL(2, "0")); var hours = date.getHours(); if (format.indexOf("t") > -1) {
        if (hours > 11)
            format = format.replace("t", "pm")
        else
            format = format.replace("t", "am")
    }
    if (format.indexOf("HH") > -1)
        format = format.replace("HH", hours.toString().padL(2, "0")); if (format.indexOf("hh") > -1) { if (hours > 12) hours -= 12; if (hours == 0) hours = 12; format = format.replace("hh", hours.toString().padL(2, "0")); }
    if (format.indexOf("mm") > -1)
        format = format.replace("mm", date.getMinutes().toString().padL(2, "0")); if (format.indexOf("ss") > -1)
        format = format.replace("ss", date.getSeconds().toString().padL(2, "0")); if (format.indexOf("MMMM") > -1)
        format = format.replace("MMMM", _monthNames[month]); else if (format.indexOf("MMM") > -1)
        format = format.replace("MMM", _monthNames[month].substr(0, 3)); else
        format = format.replace("MM", (month + 1).toString().padL(2, "0")); return format;
}
Number.prototype.formatNumber = function(format, option) {
    var num = this; var fmt = Number.getNumberFormat(); if (format == "c") { num = Math.round(num * 100) / 100; option = option || "$"; num = num.toLocaleString(); var s = num.split("."); var p = s.length > 1 ? s[1] : ''; return option + s[0] + fmt.d + p.padR(2, '0'); }
    if (format.charAt(0) == "n") {
        if (format.length == 1)
            return num.toLocaleString()
        var dec = format.substr(1); dec = parseInt(dec); if (typeof (dec) != "number")
            return num.toLocaleString(); num = num.toFixed(dec); var x = num.split(fmt.d); var x1 = x[0]; var x2 = x.length > 1 ? fmt.d + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + fmt.c + '$2'); return x1 + x2
    }
    if (format.charAt(0) == "f") {
        if (format.length == 1)
            return num.toString(); var dec = format.substr(1); dec = parseFloat(dec); if (typeof (dec) != "number")
            return num.toString(); return num.toFixed(dec);
    }
    return num.toString();
}
Number.getNumberFormat = function(cur) {
    var t = 1000.1.toLocaleString(); var r = {}; r.d = t.charAt(5); if (r.d.isNumber())
        r.d = t.charAt(4); r.c = t.charAt(1); if (r.c.isNumber())
        r.c = ","; r.s = cur || "$"; return r;
}
registerNamespace = function(ns) {
    var pts = ns.split('.'); var stk = window; var nsp = ""; for (var i = 0; i < pts.length; i++) {
        var pt = pts[i]; if (stk[pt])
            stk = stk[pt]; else
            stk = stk[pt] = {};
    }
}
getUrlEncodedKey = function(key, query) {
    if (!query)
        query = window.location.search; var re = new RegExp("[?|&]" + key + "=(.*?)&"); var matches = re.exec(query + "&"); if (!matches || matches.length < 2)
        return ""; return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function(key, value, query) {
    query = query || window.location.search; var q = query + "&"; var re = new RegExp("[?|&]" + key + "=.*?&"); if (!re.test(q))
        q += key + "=" + encodeURI(value); else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&"); q = q.trimStart("&").trimEnd("&"); return q.charAt(0) == "?" ? q : q = "?" + q;
}
$.fn.serializeNoViewState = function() { return this.find("input,textarea,select,hidden").not("#__VIEWSTATE,#__EVENTVALIDATION").serialize(); }
$.fn.makeAbsolute = function(rebase) {
    return this.each(function() {
        var el = $(this); var pos = el.position(); el.css({ position: "absolute", marginLeft: 0, marginTop: 0, top: pos.top, left: pos.left }); if (rebase)
            el.remove().appendTo("body");
    });
}
if (!this.assert) {
    this.assert = function(cond, msg) {
        if (cond) return; if (!msg) msg = ""; alert("Assert failed\r\n" + (msg ? msg : "") + "\r\n" +
(arguments.callee.caller ? "in " + arguments.callee.caller.toString() : ""));
    }
}
var _ud = "undefined"; if (!this.JSON) { this.JSON = {}; }
(function() {
    function f(n) { return n < 10 ? '0' + n : n; }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function(key) {
            return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
        }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key) { return this.valueOf(); };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function(a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }
    function str(key, holder) {
        var i, k, v, 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 (Object.prototype.toString.apply(value) === '[object Array]') {
                    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 (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); 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;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function(value, replacer, space) {
            var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; }
            rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.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);
            }
            cx.lastIndex = 0; if (cx.test(text)) {
                text = text.replace(cx, function(a) {
                    return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/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');
        };
    }
} ()); if (this.JSON && !this.JSON.parseWithDate) {
    var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/; var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/; JSON.parseWithDate = function(json) {
        try {
            var res = JSON.parse(json, function(key, value) {
                if (typeof value === 'string') {
                    var a = reISO.exec(value); if (a)
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); a = reMsAjax.exec(value); if (a) { var b = a[1].split(/[-+,.]/); return new Date(b[0] ? +b[0] : 0 - +b[1]); }
                }
                return value;
            }); return res;
        } catch (e) { throw new Error("JSON content could not be parsed"); return null; }
    }; JSON.stringifyWcf = function(json) {
        return JSON.stringify(json, function(key, value) {
            if (typeof value == "string") { var a = reISO.exec(value); if (a) { var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + ')/'; this[key] = val; return val; } }
            return value;
        })
    }; JSON.dateStringToDate = function(dtString) {
        var a = reISO.exec(dtString); if (a)
            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); a = reMsAjax.exec(dtString); if (a) { var b = a[1].split(/[-,.]/); return new Date(+b[0]); }
        return null;
    };
}

this.ServiceProxy = function(serviceUrl) {
    var _I = this; this.serviceUrl = serviceUrl; this.isWcf = true; this.invoke = function(method, params, callback, errorHandler, bare) {
        var json = _I.isWcf ? JSON.stringifyWcf(params) : JSON.stringify(params); var url = _I.serviceUrl + method; $.ajax({ url: url, data: json, type: "POST", processData: false, contentType: "application/json", timeout: 10000, dataType: "text", success: function(res) {
            if (!callback) return; var result = JSON.parseWithDate(res); if (bare)
            { callback(result); return; }
            for (var property in result) { callback(result[property]); break; } 
        }, error: function(xhr, status) {
            var err = null; if (xhr.readyState == 4) {
                var res = xhr.responseText; if (res && res.charAt(0) == '{')
                    var err = JSON.parseWithDate(res); if (!err) {
                    if (xhr.status && xhr.status != 200)
                        err = new CallbackException(xhr.status + " " + xhr.statusText); else
                        err = new CallbackException("Callback Error: " + status); err.detail = res;
                } 
            }
            if (!err)
                err = new CallbackException("Callback Error: " + status); if (errorHandler)
                errorHandler(err, _I, xhr);
        } 
        });
    } 
}

function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }
    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;
    if (errorType == "ImageError" || errorType == "MediaError") {
        onHandledErrorMessage("Image or Media error in Silverlight");
        return;
    }
    var errMsg = "Error in Silverlight Application " + appSource + "\n";
    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";
    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }
    onHandledErrorMessage(errMsg);
}

var currentPercentProgress = 0;

function onSourceDownloadProgressChanged(sender, eventArgs) {
    var progress = sender.findName("Progress");
    var progressText = sender.findName("ProgressText");
    progress.Width = eventArgs.progress * 196;
    var percent = parseInt(eventArgs.progress * 100);
    var progressInfoText = percent + "% loaded";
    progressText.Text = progressInfoText;
    if (percent == 1) logPercentProgress(1);
    else if (percent == 50) logPercentProgress(50);
    else if (percent == 99) logPercentProgress(99);
    else if (percent == 100) logPercentProgress(100);
}

function logPercentProgress(percent) {
    if (currentPercentProgress == percent) return;
    currentPercentProgress = percent;
    log(percent + "% loaded");
}

function onSourceDownloadComplete(sender, eventArgs) {
}

var notInstalledVersionArray = Array(0, 0, 0, 0);
var _versionArray;

function getSilverlightVersionArray() {
    if (_versionArray) return _versionArray;
    _versionArray = notInstalledVersionArray;
    // based on http://www.silverlightversion.com/ method
    var nav = navigator.plugins["Silverlight Plug-In"]; // Firefox and similar
    if (nav) {
        var versionSplit = nav.description.split(".");
        _versionArray = Array(parseInt(versionSplit[0]), parseInt(versionSplit[1]), parseInt(versionSplit[2]), parseInt(versionSplit[3]));
    } else {
        //try the IE one... 
        try {
            var control = new ActiveXObject('AgControl.AgControl');
            _versionArray = Array(1, 0, 0, 0);
            //the following would be faster with a binary search.
            loopMatch(control, _versionArray, 0, 1);
            loopMatch(control, _versionArray, 1, 1);
            loopMatch(control, _versionArray, 2, 10000);
            loopMatch(control, _versionArray, 2, 1000);
            loopMatch(control, _versionArray, 2, 100);
            loopMatch(control, _versionArray, 2, 10);
            loopMatch(control, _versionArray, 2, 1);
            loopMatch(control, _versionArray, 3, 1);
        } catch (e) {
            // it means that silverlight is not installed, so version should stay as initially set to notInstalledVersionArray;
        }
    }
    return _versionArray;
}

function getInt(stringArray, index) {
    return ;
}

function isSilverlightInstalled() {
    return getSilverlightVersionArray() != notInstalledVersionArray;
}

function getSilverlightVersion() {
    var versionArray = getSilverlightVersionArray();
    return versionArray.join(".");
}

function loopMatch(control, vers, idx, inc) {
    while (IsSupported(control, vers)) {
        vers[idx] += inc;
    }
    vers[idx] -= inc;
}

function IsSupported(control, ver){
    return control.IsVersionSupported(ver[0]+ "."+ ver[1] + "." + ver[2] + "." + ver[3]);
}

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
* $Rev: 4257 $
*
* Version: 1.2
*
* Requires: jQuery 1.2+
*/
eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('(5($){$.19={P:\'1.2\'};$.u([\'j\',\'w\'],5(i,d){$.q[\'O\'+d]=5(){p(!3[0])6;g a=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';6 3.B(\':y\')?3[0][\'L\'+d]:4(3,d.x())+4(3,\'n\'+a)+4(3,\'n\'+e)};$.q[\'I\'+d]=5(b){p(!3[0])6;g c=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';b=$.F({t:Z},b||{});g a=3.B(\':y\')?3[0][\'8\'+d]:4(3,d.x())+4(3,\'E\'+c+\'w\')+4(3,\'E\'+e+\'w\')+4(3,\'n\'+c)+4(3,\'n\'+e);6 a+(b.t?(4(3,\'t\'+c)+4(3,\'t\'+e)):0)}});$.u([\'m\',\'s\'],5(i,b){$.q[\'l\'+b]=5(a){p(!3[0])6;6 a!=W?3.u(5(){3==h||3==r?h.V(b==\'m\'?a:$(h)[\'U\'](),b==\'s\'?a:$(h)[\'T\']()):3[\'l\'+b]=a}):3[0]==h||3[0]==r?S[(b==\'m\'?\'R\':\'Q\')]||$.N&&r.M[\'l\'+b]||r.A[\'l\'+b]:3[0][\'l\'+b]}});$.q.F({z:5(){g a=0,f=0,o=3[0],8,9,7,v;p(o){7=3.7();8=3.8();9=7.8();8.f-=4(o,\'K\');8.k-=4(o,\'J\');9.f+=4(7,\'H\');9.k+=4(7,\'Y\');v={f:8.f-9.f,k:8.k-9.k}}6 v},7:5(){g a=3[0].7;G(a&&(!/^A|10$/i.16(a.15)&&$.14(a,\'z\')==\'13\'))a=a.7;6 $(a)}});5 4(a,b){6 12($.11(a.17?a[0]:a,b,18))||0}})(X);', 62, 72, '|||this|num|function|return|offsetParent|offset|parentOffset|||||borr|top|var|window||Height|left|scroll|Left|padding|elem|if|fn|document|Top|margin|each|results|Width|toLowerCase|visible|position|body|is|Right|Bottom|border|extend|while|borderTopWidth|outer|marginLeft|marginTop|client|documentElement|boxModel|inner|version|pageYOffset|pageXOffset|self|scrollTop|scrollLeft|scrollTo|undefined|jQuery|borderLeftWidth|false|html|curCSS|parseInt|static|css|tagName|test|jquery|true|dimensions'.split('|'), 0, {}));

/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* jFlow
* Version: 1.0 (May 13, 2008)
* Requires: jQuery 1.2+
*/

/**
* jQuery Lightbox
* Version 0.5 - 11/29/2007
* @author Warren Krewenki
*
* This package is distributed under the BSD license.
* For full license information, see LICENSE.TXT
*
* Based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
* Originally written to make use of the Prototype framework, and Script.acalo.us, now altered to use jQuery.
*
*
**/

(function($) {

    $.fn.lightbox = function(options) {
        // build main options
        var opts = $.extend({}, $.fn.lightbox.defaults, options);

        return this.each(function() {
            $(this).click(function() {
                // initalize the lightbox
                initialize();
                start(this);
                return false;
            });
        });

        /**
        * initalize()
        *
        * @return void
        * @author Warren Krewenki
        */

        function initialize() {
            $('#overlay').remove();
            $('#lightbox').remove();
            opts.inprogress = false;

            // if jsonData, build the imageArray from data provided in JSON format
            if (opts.jsonData && opts.jsonData.length > 0) {
                var parser = opts.jsonDataParser ? opts.jsonDataParser : $.fn.lightbox.parseJsonData;
                opts.imageArray = [];
                opts.imageArray = parser(opts.jsonData);
            }

            var outerImage = '<div id="outerImageContainer"><div id="imageContainer"><iframe id="lightboxIframe" /><img id="lightboxImage"><div id="hoverNav"><a href="javascript://" title="' + opts.strings.prevLinkTitle + '" id="prevLink"></a><a href="javascript://" id="nextLink" title="' + opts.strings.nextLinkTitle + '"></a></div><div id="loading"><a href="javascript://" id="loadingLink"><img src="' + opts.fileLoadingImage + '"></a></div></div></div>';
            var imageData = '<div id="imageDataContainer" class="clearfix"><div id="imageData"><div id="imageDetails"><span id="caption"></span><span id="numberDisplay"></span></div><div id="bottomNav">';

            if (opts.displayHelp)
                imageData += '<span id="helpDisplay">' + opts.strings.help + '</span>';

            imageData += '<a href="javascript://" id="bottomNavClose" title="' + opts.strings.closeTitle + '"><img src="' + opts.fileBottomNavCloseImage + '"></a></div></div></div>';

            var string;

            if (opts.navbarOnTop) {
                string = '<div id="overlay"></div><div id="lightbox">' + imageData + outerImage + '</div>';
                $("body").append(string);
                $("#imageDataContainer").addClass('ontop');
            } else {
                string = '<div id="overlay"></div><div id="lightbox">' + outerImage + imageData + '</div>';
                $("body").append(string);
            }

            $("#overlay").click(function() { end(); }).hide();
            $("#lightbox").click(function() { end(); }).hide();
            $("#loadingLink").click(function() { end(); return false; });
            $("#bottomNavClose").click(function() { end(); return false; });
            $('#outerImageContainer').width(opts.widthCurrent).height(opts.heightCurrent);
            $('#imageDataContainer').width(opts.widthCurrent);

            if (!opts.imageClickClose) {
                $("#lightboxImage").click(function() { return false; });
                $("#hoverNav").click(function() { return false; });
            }
        };

        function getPageSize() {
            var jqueryPageSize = new Array($(document).width(), $(document).height(), $(window).width(), $(window).height());
            return jqueryPageSize;
        };

        function getPageScroll() {
            var xScroll, yScroll;

            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {  // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
            } else if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;
            }

            var arrayPageScroll = new Array(xScroll, yScroll);
            return arrayPageScroll;
        };

        function pause(ms) {
            var date = new Date();
            var curDate = null;
            do { curDate = new Date(); }
            while (curDate - date < ms);
        };

        function start(imageLink) {
            $("span.sel .spike").fadeOut();
            $("select, embed, object").hide();
            var arrayPageSize = getPageSize();
            $("#overlay").hide().css({ width: '100%', height: arrayPageSize[1] + 'px', opacity: opts.overlayOpacity }).fadeIn();
            imageNum = 0;

            // if data is not provided by jsonData parameter
            if (!opts.jsonData) {
                opts.imageArray = [];
                // if image is NOT part of a set..
                if (!imageLink.rel || (imageLink.rel == '')) {
                    // add single image to Lightbox.imageArray
                    opts.imageArray.push(new Array(imageLink.href, opts.displayTitle ? imageLink.title : ''));
                } else {
                    // if image is part of a set..
                    $("a").each(function() {
                        if (this.href && (this.rel == imageLink.rel)) {
                            opts.imageArray.push(new Array(this.href, opts.displayTitle ? this.title : ''));
                        }
                    });
                }
            }

            if (opts.imageArray.length > 1) {
                for (i = 0; i < opts.imageArray.length; i++) {
                    for (j = opts.imageArray.length - 1; j > i; j--) {
                        if (opts.imageArray[i][0] == opts.imageArray[j][0]) {
                            opts.imageArray.splice(j, 1);
                        }
                    }
                }
                while (opts.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
            }

            // calculate top and left offset for the lightbox
            var arrayPageScroll = getPageScroll();
            var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
            var lightboxLeft = arrayPageScroll[0];
            $('#lightbox').css({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();


            if (!opts.slideNavBar)
                $('#imageData').hide();

            changeImage(imageNum);
        };

        function changeImage(imageNum) {
            if (opts.inprogress == false) {
                opts.inprogress = true;
                opts.activeImage = imageNum; // update global var

                // hide elements during transition
                $('#loading').show();
                $('#lightboxImage').hide();
                $('#hoverNav').hide();
                $('#prevLink').hide();
                $('#nextLink').hide();

                if (opts.slideNavBar) { // delay preloading image until navbar will slide up
                    // $('#imageDataContainer').slideUp(opts.navBarSlideSpeed, $.fn.doChangeImage);
                    $('#imageDataContainer').hide();
                    $('#imageData').hide();
                    doChangeImage();
                } else {
                    doChangeImage();
                }
            }
        };

        function doChangeImage() {

            imgPreloader = new Image();

            // once image is preloaded, resize image container
            imgPreloader.onload = function() {
                var newWidth = imgPreloader.width;
                var newHeight = imgPreloader.height;


                if (opts.fitToScreen) {
                    var arrayPageSize = getPageSize();
                    var ratio;
                    var initialPageWidth = arrayPageSize[2] - 2 * opts.borderSize;
                    var initialPageHeight = arrayPageSize[3] - 200;

                    if (imgPreloader.height > initialPageHeight) {
                        newWidth = parseInt((initialPageHeight / imgPreloader.height) * imgPreloader.width);
                        newHeight = initialPageHeight;
                    }
                    else if (imgPreloader.width > initialPageWidth) {
                        newHeight = parseInt((initialPageWidth / imgPreloader.width) * imgPreloader.height);
                        newWidth = initialPageWidth;
                    }
                }

                $('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])
							       .width(newWidth).height(newHeight);
                resizeImageContainer(newWidth, newHeight);
            };

            imgPreloader.src = opts.imageArray[opts.activeImage][0];
        };

        function end() {
            disableKeyboardNav();
            $("span.sel .spike").fadeIn();
            $('#lightbox').hide();
            $('#overlay').fadeOut();
            $('select, object, embed').show();

        };

        function preloadNeighborImages() {
            if (opts.loopImages && opts.imageArray.length > 1) {
                preloadNextImage = new Image();
                preloadNextImage.src = opts.imageArray[(opts.activeImage == (opts.imageArray.length - 1)) ? 0 : opts.activeImage + 1][0]

                preloadPrevImage = new Image();
                preloadPrevImage.src = opts.imageArray[(opts.activeImage == 0) ? (opts.imageArray.length - 1) : opts.activeImage - 1][0]
            } else {
                if ((opts.imageArray.length - 1) > opts.activeImage) {
                    preloadNextImage = new Image();
                    preloadNextImage.src = opts.imageArray[opts.activeImage + 1][0];
                }
                if (opts.activeImage > 0) {
                    preloadPrevImage = new Image();
                    preloadPrevImage.src = opts.imageArray[opts.activeImage - 1][0];
                }
            }
        };

        function resizeImageContainer(imgWidth, imgHeight) {
            // get current width and height
            opts.widthCurrent = $("#outerImageContainer").outerWidth();
            opts.heightCurrent = $("#outerImageContainer").outerHeight();

            // get new width and height
            var widthNew = Math.max(350, imgWidth + (opts.borderSize * 2));
            var heightNew = (imgHeight + (opts.borderSize * 2));

            // scalars based on change from old to new
            opts.xScale = (widthNew / opts.widthCurrent) * 100;
            opts.yScale = (heightNew / opts.heightCurrent) * 100;

            // calculate size difference between new and old image, and resize if necessary
            wDiff = opts.widthCurrent - widthNew;
            hDiff = opts.heightCurrent - heightNew;

            $('#imageDataContainer').animate({ width: widthNew }, opts.resizeSpeed, 'linear');
            $('#outerImageContainer').animate({ width: widthNew }, opts.resizeSpeed, 'linear', function() {
                $('#outerImageContainer').animate({ height: heightNew }, opts.resizeSpeed, 'linear', function() {
                    showImage();
                });
            });

            // if new and old image are same size and no scaling transition is necessary,
            // do a quick pause to prevent image flicker.
            if ((hDiff == 0) && (wDiff == 0)) {
                if (jQuery.browser.msie) { pause(250); } else { pause(100); }
            }

            $('#prevLink').height(imgHeight);
            $('#nextLink').height(imgHeight);
        };

        function showImage() {
            $('#loading').hide();
            $('#lightboxImage').fadeIn("fast");
            updateDetails();
            preloadNeighborImages();

            opts.inprogress = false;
        };

        function updateDetails() {

            $('#numberDisplay').html('');

            if (opts.imageArray[opts.activeImage][1]) {
                $('#caption').html(opts.imageArray[opts.activeImage][1]).show();
            }

            // if image is part of set display 'Image x of x'
            if (opts.imageArray.length > 1) {
                var nav_html;

                nav_html = opts.strings.image + (opts.activeImage + 1) + opts.strings.of + opts.imageArray.length;

                if (!opts.disableNavbarLinks) {
                    // display previous / next text links
                    if ((opts.activeImage) > 0 || opts.loopImages) {
                        nav_html = '<a title="' + opts.strings.prevLinkTitle + '" href="#" id="prevLinkText">' + opts.strings.prevLinkText + "</a>" + nav_html;
                    }

                    if (((opts.activeImage + 1) < opts.imageArray.length) || opts.loopImages) {
                        nav_html += '<a title="' + opts.strings.nextLinkTitle + '" href="#" id="nextLinkText">' + opts.strings.nextLinkText + "</a>";
                    }
                }

                $('#numberDisplay').html(nav_html).show();
            }

            if (opts.slideNavBar) {
                $("#imageData").slideDown(opts.navBarSlideSpeed);
            } else {
                $("#imageData").show();
            }

            var arrayPageSize = getPageSize();
            $('#overlay').height(arrayPageSize[1]);
            updateNav();
        };

        function updateNav() {
            if (opts.imageArray.length > 1) {
                $('#hoverNav').show();

                // if loopImages is true, always show next and prev image buttons 
                if (opts.loopImages) {
                    $('#prevLink,#prevLinkText').show().click(function() {
                        changeImage((opts.activeImage == 0) ? (opts.imageArray.length - 1) : opts.activeImage - 1); return false;
                    });

                    $('#nextLink,#nextLinkText').show().click(function() {
                        changeImage((opts.activeImage == (opts.imageArray.length - 1)) ? 0 : opts.activeImage + 1); return false;
                    });

                } else {
                    // if not first image in set, display prev image button
                    if (opts.activeImage != 0) {
                        $('#prevLink,#prevLinkText').show().click(function() {
                            changeImage(opts.activeImage - 1); return false;
                        });
                    }

                    // if not last image in set, display next image button
                    if (opts.activeImage != (opts.imageArray.length - 1)) {
                        $('#nextLink,#nextLinkText').show().click(function() {

                            changeImage(opts.activeImage + 1); return false;
                        });
                    }
                }

                enableKeyboardNav();
            }
        };

        function keyboardAction(e) {
            var o = e.data.opts
            var keycode = e.keyCode;
            var escapeKey = 27;

            var key = String.fromCharCode(keycode).toLowerCase();

            if ((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)) { // close lightbox
                end();
            } else if ((key == 'p') || (keycode == 37)) { // display previous image
                if (o.loopImages) {
                    disableKeyboardNav();
                    changeImage((o.activeImage == 0) ? (o.imageArray.length - 1) : o.activeImage - 1);
                }
                else if (o.activeImage != 0) {
                    disableKeyboardNav();
                    changeImage(o.activeImage - 1);
                }
            } else if ((key == 'n') || (keycode == 39)) { // display next image
                if (opts.loopImages) {
                    disableKeyboardNav();
                    changeImage((o.activeImage == (o.imageArray.length - 1)) ? 0 : o.activeImage + 1);
                }
                else if (o.activeImage != (o.imageArray.length - 1)) {
                    disableKeyboardNav();
                    changeImage(o.activeImage + 1);
                }
            }
        };

        function enableKeyboardNav() {
            $(document).bind('keydown', { opts: opts }, keyboardAction);
        };

        function disableKeyboardNav() {
            $(document).unbind('keydown');
        };

    };

    $.fn.lightbox.parseJsonData = function(data) {
        var imageArray = [];

        $.each(data, function() {
            imageArray.push(new Array(this.url, this.title));
        });

        return imageArray;
    };

    $.fn.lightbox.defaults = {
        fileLoadingImage: RootUrl + '/App_Themes/Default/images/Gallery/loading.gif',
        fileBottomNavCloseImage: RootUrl + '/App_Themes/Default/images/Gallery/closelabel.gif',
        overlayOpacity: 0.8,
        borderSize: 10,
        imageArray: new Array,
        activeImage: null,
        inprogress: false,
        resizeSpeed: 350,
        widthCurrent: 250,
        heightCurrent: 250,
        xScale: 1,
        yScale: 1,
        displayTitle: true,
        navbarOnTop: false,
        slideNavBar: false, // slide nav bar up/down between image resizing transitions
        navBarSlideSpeed: 350,
        displayHelp: false,
        strings: {
            help: ' \u2190 / P - previous image\u00a0\u00a0\u00a0\u00a0\u2192 / N - next image\u00a0\u00a0\u00a0\u00a0ESC / X - close image gallery',
            prevLinkTitle: 'previous image',
            nextLinkTitle: 'next image',
            prevLinkText: '&laquo; Previous',
            nextLinkText: 'Next &raquo;',
            closeTitle: 'close image gallery',
            image: 'Image ',
            of: ' of '
        },
        fitToScreen: false, 	// resize images if they are bigger than window
        disableNavbarLinks: false,
        loopImages: false,
        imageClickClose: true,
        jsonData: null,
        jsonDataParser: null
    };

})(jQuery);


(function($) {

    $.fn.jFlow = function(options) {
        var opts = $.extend({}, $.fn.jFlow.defaults, options);
        var cur = 0;
        var maxi = $(".jFlowControl").length;
        $(this).find(".jFlowControl").each(function(i) {
            $(this).click(function() {
                $(".jFlowControl").removeClass("jFlowSelected");
                $(this).addClass("jFlowSelected");
                var dur = Math.abs(cur - i + 1);
                $(opts.slides).animate({
                    marginLeft: "-" + (i * $(opts.slides).find(":first-child").width() + "px")
                }, opts.duration * (dur));
                cur = i;
                log($(this).get(0).innerText);
            });
        });

        $(opts.slides).before('<div id="jFlowSlide"></div>').appendTo("#jFlowSlide");

        $(opts.slides).find("div.item").each(function() {
            $(this).before('<div class="jFlowSlideContainer"></div>').appendTo($(this).prev());
        });

        //initialize the controller
        $(".jFlowControl").eq(cur).addClass("jFlowSelected");

        var resize = function(x) {
            $("#jFlowSlide").css({
                position: "relative",
                width: opts.width,
                height: opts.height,
                overflow: "hidden"
            });

            $(opts.slides).css({
                position: "relative",
                width: $("#jFlowSlide").width() * $(".jFlowControl").length + "px",
                height: $("#jFlowSlide").height() + "px",
                overflow: "hidden"
            });

            $(opts.slides).children().css({
                position: "relative",
                width: $("#jFlowSlide").width() + "px",
                height: $("#jFlowSlide").height() + "px",
                "float": "left"
            });

            $(opts.slides).css({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            });
        }

        resize();

        $(window).resize(function() {
            resize();
        });

        $(".jFlowPrev").click(function() {
            if (cur > 0)
                cur--;
            else
                cur = maxi - 1;

            $(".jFlowControl").removeClass("jFlowSelected");
            $(opts.slides).animate({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            }, opts.duration);
            $(".jFlowControl").eq(cur).addClass("jFlowSelected");
        });

        $(".jFlowNext").click(function() {
            if (cur < maxi - 1)
                cur++;
            else
                cur = 0;

            $(".jFlowControl").removeClass("jFlowSelected");
            $(opts.slides).animate({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            }, opts.duration);
            $(".jFlowControl").eq(cur).addClass("jFlowSelected");
        });
    };

    $.fn.jFlow.defaults = {
        easing: "swing",
        duration: 400,
        width: "100%"
    };

})(jQuery);


function initializeContentSlider() {
    if ($("div.FrontMenu") == null) return;
    $(".FrontMenu").fadeIn("slow");
    $(".Graduate").css({ "display": "block" });
    $("div.FrontMenu div.Bar span.item:first").addClass("sel");

    $("div.FrontMenu div.Bar a").click(function() {
        $("div.FrontMenu div.Bar").children("span.sel").removeClass("sel");
        $(this).parent().addClass("sel");
        return false;
    });

    $(".FrontMenu").jFlow({
        slides: ".FrontMenu .Panel",
        width: "662px",
        height: "360px",
        duration: 300
    });

    $(".FrontMenu div.Panel > *").addClass("item");

    $(".FrontMenu div.Panel .CmsContentBox").show();

    $(".FrontMenu .Bar a").mouseover(function() { $(this).addClass("hover"); });
    $(".FrontMenu .Bar a").mouseout(function() { $(this).removeClass("hover"); });

}

// Handles specified cliend side exception.
function onHandledError(exception) {
    if (exception) onHandledErrorMessage(exception.message);
}

// Handles specified client side error message by calling server-side error handler.
function onHandledErrorMessage(errorMessage) {
    //alert("errorMessage");
    proxy.invoke("ProcessClientError",
         { errorMessage: errorMessage },
         function() { },
         onPageError);
}

// Handles specified unhandled Silverlight error message.
function onUnhandledErrorMessage(errorMessage) {
    onHandledErrorMessage(errorMessage);
}

var normalLogType = "0"; var importantLogType = "1"; var warningLogType = "2"; var errorLogType = "3";

function log(message) {
    writeToLog(message, normalLogType);
}

function writeToLog(_message, _logType) {
    //alert("log");
	if (_message == "") return;
    proxy.invoke("WriteIntoLog",
    { logMessage: _message, logType: _logType },
    function (response) {
        if (response == "") return;
        var slApp = document.getElementById('ClientApplication');
        if (slApp && slApp.Content && slApp.Content.LogResponse) slApp.Content.LogResponse.ParseLogResponseMessage(response);
    },
    onPageError); 
}

jQuery.fn.switchClass = function(fromClassName, toClassName) {
    this.removeClass(fromClassName);
    this.addClass(toClassName);
    return this;
};

jQuery.fn.delay = function(time, func) {
    return this.each(function() {
        setTimeout(func, time);
    });
};

jQuery.fn.setFocus = function() {
    var control = this.get(0);
    control.hasFocus = true;
    control.focus();
    return this;
};

jQuery.fn.removeFocus = function() {
    this.get(0).hasFocus = false;
    return this;
};

jQuery.fn.hasFocus = function() {
    return this.get(0).hasFocus;
};

jQuery.fn.widthContainer = function() {
    return this.width() + this.outerWidth();
};

jQuery.fn.heightContainer = function() {
    return this.height() + this.outerHeight();
};

// Set focus on control specified by clientId.
function setFocus(focusControlId) {
    if (!focusControlId || focusControlId == "") return;
    var focusControl = $("#" + focusControlId);
    if (!focusControl) return;
    try {
        focusControl.setFocus();
    }
    catch (e) {
    }
}

var resizeTimer = null;
var windowWidth, windowHeight, documentHeight, documentWidth;

$(document).ready(function() {
    initialize();
});

$(window).bind('resize', function() {
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(onResize, 100);
});

$(window).bind('unload', function() {

});

function initialize() {
    initializeBrowserDetection();
    calculateWindowDimension();
    initializeTextBox();
    initializeButton();
    initializeDropDownList();
    initializeNotification();
    initializeContentSlider();
    initializeReadMore();
    setSilverlightVersion();
    setLocation();
}

function setSilverlightVersion() {
    //if (!isSilverlightInstalled()) return;
    var currentSilverlightVersion = getSilverlightVersion();
    if (visitorSilverlightVersion != currentSilverlightVersion) {
        //alert(currentSilverlightVersion + visitorSilverlightVersion);
        proxy.invoke("SetSilverlightVersion",
         { silverlightVersion: currentSilverlightVersion },
         function() { },
         onPageError); 
        visitorSilverlightVersion = currentSilverlightVersion;
    }
}

function setLocation() {
    if (!trackLocation) return;
    proxy.invoke("SetLocation", {}, function() { }, onPageError);
}

function initializeBrowserDetection() {
    $.browser.msie6 = (document.all && !window.opera && !window.XMLHttpRequest && $.browser.msie) ? true : false; // specific detection for IE6 browser.
}

// Returns whether animation is supported for application resizing.
function isAnimationSupported() {
    return !($.browser.mozilla || $.browser.msie6);
    // for some reason IE6 and Mozilla doesn't work ok for application resizing animation.
    // IE7 and Safari works ok. 
}

function initializeTextBox() {
    var textBox = $(":text, :password");
    textBox.focus(
        function() {
            $(this).setFocus();
            $(this).switchClass("TextBoxBlur", "TextBoxFocus");
        });
    textBox.blur(
        function() {
            $(this).removeFocus();
            $(this).switchClass("TextBoxFocus", "TextBoxBlur");
            $(this).removeClass("TextBoxMouseOver");
        });
    textBox.mouseover(
        function() {
            $(this).switchClass("TextBoxMouseOut", "TextBoxMouseOver");
        });
    textBox.mouseout(
        function() {
            if (!($(this).hasFocus())) {
                $(this).switchClass("TextBoxMouseOver", "TextBoxMouseOut");
            }
        });
}

function initializeButton() {
    var button = $(":submit");
    button.mouseover(
        function() {
            $(this).switchClass("ButtonMouseOut", "ButtonMouseOver");
        });
    button.mouseout(
        function() {
            if (!($(this).hasFocus())) {
                $(this).switchClass("ButtonMouseOver", "ButtonMouseOut");
            }
        });
}

function initializeDropDownList() {
    var dropdownlist = $(".DropDownList");
    dropdownlist.focus(
        function() {
            $(this).switchClass("DropDownListBlur", "DropDownListFocus");
        });
    dropdownlist.blur(
        function() {
            $(this).switchClass("DropDownListFocus", "DropDownListBlur");
        });
}

function wrapButton() {
    var button = $(":submit");
    var divWrapper = document.createElement("div");
    divWrapper.setAttribute("class", "Button");
    var dlWrapper = document.createElement("dl");
    var dtWrapper = document.createElement("dt");
    divWrapper.appendChild(dlWrapper).appendChild(dtWrapper);
    button.wrap(divWrapper);
    button.mouseover(
        function() {
            var divWrapper = getWrapperDiv($(this));
            divWrapper.removeClass();
            divWrapper.addClass("ButtonOver");
        });
    button.mouseout(
        function() {
            var divWrapper = getWrapperDiv($(this));
            divWrapper.removeClass();
            divWrapper.addClass("Button");
        });
}

function getWrapperDiv(button) {
    return button.parent().parent().parent();
}

function calculateWindowDimension() {
    windowHeight = $(window).height();
    windowWidth = $(window).width();
    documentHeight = $(document).height();
    documentWidth = $(document).width();
}

function onResize() {
    calculateWindowDimension();
    initializeNotification();
    //log("Resized to " + windowWidth + " x " + windowHeight); // log all resizing events.
}

function initializeNotification() {
    if (hasNotification()) {
        notification = $(".Notification");
        var notificationWidth = notification.width();
        var left = (windowWidth - notificationWidth) / 2;
        notification.css({ "left": left, "top": 0, "visibility": "visible" });
        notification.click(
            function() {
                $(this).fadeOut(500);
                log("Hide server notification.");
            });
        notification.mouseover(
            function() {
                $(this).addClass("NotificationHover");
            });
        //moveNotificationTo(null, null);
    }
}

function hasNotification() {
    var notification = $(".Notification");
    return (notification.find("div").length != 0);
}

function beginAjaxRequestHandle(sender, args) {

}

function endAjaxRequestHandle(sender, args) {
    initializeNotification();
}

function page_init() {
    Sys.Application.add_navigate(onStateChanged);
}

function onStateChanged(sender, e) {
    // When the page is navigated, this event is raised.
    var state = e.get_state().state;
    //alert('Revert to state ' + state);
    //    var val = parseInt(e.get_state().s || '0');
}

// Set a history point in client script.
function addHistoryPoint(stateInfo) {
    //Sys.Application.addHistoryPoint({ state: stateInfo }, "Title:" + val);
    //if (stateInfo == '') return;
    //window.location.hash = stateInfo;
    log(stateInfo);
    Sys.Application.addHistoryPoint({ state: stateInfo });
}

function showReadMore(id, e) {
    hideReadMoreLayers();
    var layer = $("#" + id);
    if (layer == null) return;
    var top = e.pageY + 20 + "px";
    var left = (windowWidth - layer.width()) / 2 + "px";
    //    layer.css({"top": top, "left": left, "position" : "absolute", "zIndex": "1000000" });
    layer.css({ "top": top, "left": left, "position": "absolute", "display": "block", opacity: "0" });
    layer.animate({ opacity: "0.90" }, 1000, "swing");
}

this.setReadMore = function() {
    //    $("a.tooltip").mousemove(function(e) {
    //        $("#tooltip")
    //			.css("top", (e.pageY - yOffset) + "px")
    //			.css("left", (e.pageX + xOffset) + "px");
    //        var height = $("#tooltip").height();
    //        yOffset = height - 40;
    //    });
    //    $("a.tooltip").mouseover(function(e) {
    //        if (!isFirst) return;
    //        this.t = this.title;
    //        this.title = "";
    //        isFirst = false;
    //    });
    $("a.ReadMoreLink").click(function(e) {
        //        $("body").append("<div id='tooltip'><div class='tooltipCont'><h4>The Card Security Number</h4>" + this.t + "</div></div>");
        //        //var height = $("#tooltip").height();		
        //        var height = 447;
        //        yOffset = height - 40;
        //        $("#tooltip")
        //			.css("top", (e.pageY - yOffset) + "px")
        //			.css("left", (e.pageX + xOffset) + "px")
        //			.fadeIn("fast");
        var rel = $(this).attr("rel");
        showReadMore(rel, e);
        return false;
    },
	function() {
	    //	    this.title = this.t;
	    //	    $("#tooltip").remove();
	});

};

function initializeReadMore() {
    setReadMore();
    $("body").click(function(e) {
        var target = $(e.target);
        var obj = target.get(0);
        if (obj && obj.className && obj.className == 'ReadMoreLink') return;
        hideReadMoreLayers();
    });
}

function hideReadMoreLayers() {
    var readMoreLayers = $(".ReadMoreLayer");
    if (readMoreLayers == null) return;
    readMoreLayers.each(function() {
        if (this.style.display != 'none') {
            $(this).fadeOut("fast");
        }
    });
}

function printApplication() {
    window.print();
}

function setPrintContainer(content) {
    $("#Print").html(content);
}

function showHideMoreInfo() {
    var moreInfoPanel = $("#MoreInfoPanel");
    if (!moreInfoPanel) return;
    var div = moreInfoPanel.get(0);
    if (div.style.display == 'none') {
        moreInfoPanel.show();
        log("Expand more info.");
    }
    else {
        moreInfoPanel.hide();
        log("Collapsed more info.");
    }
}

function logLink(aTag) {
    try {
        log("Click on " + aTag.href);
    }
    catch (exception) {
        // don't handle errors while logging link.
    }
    return true;
}

function setEnable(control, isEnabled) {
    if (control) control.disabled = !isEnabled;
}

function checkRegistrationButton(control) {
    var sending = "Sending";
    if (control.title == sending) {
        log("Prevented submit while submitting");
        return false;
    }
    control.title = sending;
    return true;
}