﻿
var env = "production"; var tremor_host = location.host; var commonUrl = '/common/v4'; var debug = false; var ajaxUrlPath = 'service.ashx'; if (document.location.href.indexOf("debug=true") != -1) { debug = true; }
var TremorApp = { debug: debug, debug_level: "long", log_level: { "ajax": 4, "content": 4, DEFAULT: 4, "popup": 1, calendar: 1 }, log_style: { "exception": "color:red;text-decoration:underline", "ajax": "color:#77f" }, require_auth: "none", require_auth_role: ["member"], realm: 'vocalpoint', login_page: 'login.html', program_name: 'Tremor B2B', ajax_url: ajaxUrlPath, ajax_url_https: ajaxUrlPath, common_url: commonUrl, cookie_expiration_days: 30, modules: ["default", "form", "security"] }
var Tremor = { version: 1, authToken: null, realm: null, onLoad: [], COOKIE_EXPIRATION_DAYS: TremorApp.cookieExpirationDays == null ? 14 : TremorApp.cookie_expiration_days, AuthToken: function() { return Tremor.Util.GetCookie('tremor_auth_token'); }, SetAuthToken: function(token) { Tremor.Util.SetCookie('tremor_auth_token', token); }, AuthRoles: function() {
    var r = Tremor.Util.GetCookie('tremor_auth_roles'); if (r != null) { return r.split("|"); }
    return [];
}, SetAuthRoles: function(v) {
    var r = ""; for (var i = 0; i < v.length; i++) {
        if (i > 0) { r = r + "|"; }
        r = r + v[i];
    }
    return Tremor.Util.SetCookie('tremor_auth_roles', r);
}, is: { ie: navigator.appName == 'Microsoft Internet Explorer', java: navigator.javaEnabled(), ns: navigator.appName == 'Netscape', ua: navigator.userAgent.toLowerCase() || "", version: parseFloat(navigator.appVersion.substr(21)) || parseFloat(navigator.appVersion), win: navigator.platform == 'Win32' }, HasRequiredRole: function(rlist) {
    for (var ri = 0; ri < rlist.length; ri++) { var r = rlist[ri]; for (var ni = 0; ni < TremorApp.require_auth_role.length; ni++) { var n = TremorApp.require_auth_role[ni]; if (r == n) { return true; } } }
    return false;
}, SetupPage: function() {
    this.is.mac = this.is.ua.indexOf('mac') >= 0; if (this.is.ua.indexOf('opera') >= 0) { this.is.ie = this.is.ns = false; this.is.opera = true; }
    if (this.is.ua.indexOf('gecko') >= 0) { this.is.ie = this.is.ns = false; this.is.gecko = true; }
    Tremor.Debug.Log("setup page", "setup", 4); Tremor.Debug.Log("href: " + document.location.href, "setup", 4); Tremor.Debug.Log("cookies: " + document.cookie, "setup", 4); Tremor.Debug.Log("TremorApp.require_auth: " + TremorApp.require_auth, "setup", 4); var redirect = false; if (TremorApp.require_auth && TremorApp.require_auth != 'none') {
        Tremor.Debug.Log("authenticate: " + this.AuthToken() + " " + this.AuthRoles(), "setup", 4); if (TremorApp.require_auth == 'login' && !this.HasRequiredRole(this.AuthRoles())) { redirect = true; }
        else if (TremorApp.require_auth == "remembered" && !this.HasRequiredRole(this.AuthRoles())) {
            var authToken = Tremor.Util.GetCookie("rememberAuthToken"); Tremor.Debug.Log("remembered auth token: " + authToken, "security", 4); var success = false; if (!Tremor.Util.IsEmptyString(authToken)) { var params = { token: authToken, userRealm: TremorApp.realm }; var resp = Tremor.Ajax.Call("authentication", "GetAuthenticationForToken", params, { sync: true }); if (resp != null && resp.Auth.IsAuthenticated && this.HasRequiredRole(resp.Auth.Roles)) { success = true; } }
            if (!success) { redirect = true; } 
        } 
    }
    if (redirect) {
        var file = location.href.substring(location.href.lastIndexOf('/') + 1, location.href.length); if (file.indexOf('?') != -1) { file = file.substring(0, file.indexOf('?')); }
        if (!TremorApp.login_page.endsWith(file)) { Tremor.Debug.Log("login page " + TremorApp.login_page, "setup", 4); Tremor.Debug.Log("current page " + file, "setup", 4); Tremor.Util.SetCookie('login_return_url', document.location.href); document.location.href = TremorApp.login_page; } else { Behaviour.apply(); } 
    }
    else {
        for (var l = 0; l < this.onLoad.length; l++) { this.onLoad[l](); }
        Behaviour.apply();
    } 
}, AddOnWindowLoad: function(f) { this.onLoad[this.onLoad.length] = f; } 
}; var tremorModuleAssets = { "default": ["css/tremorjs.css"], "calendar": ["css/datepicker.css"], "window": ["css/ui.tabs.css"], "controls": [], "form": [], "security": [], "corners": [], "minimum": ["css/tremorjs.css"], "menu": [], "tree": [] }
function loadTremorAssets() {
    if (TremorApp.common_url[TremorApp.common_url.length - 1] != '/') { TremorApp.common_url = TremorApp.common_url + "/"; }
    var common = TremorApp.common_url; if (document.location.href.toLowerCase().indexOf("https") == 0 && common.toLowerCase().indexOf("http:") == 0) { common = "https:" + common.substring(5); }
    if (typeof TremorApp.modules != "undefined") {
        for (var i = 0; i < TremorApp.modules.length; i++) {
            var assets = tremorModuleAssets[TremorApp.modules[i]]; if (assets != null) {
                for (var a = 0; a < assets.length; a++) {
                    var asset = assets[a]; var load = ""; if (asset.substring(0, 3) == "css") { load = "<link rel='stylesheet' type='text/css' href='" + common + asset + "'/>"; }
                    document.write(load);
                } 
            }
            else { if (TremorApp.debug) { alert("Unknown module: " + TremorApp.modules[i]); } } 
        } 
    } 
}
loadTremorAssets(); function TremorOnLoad() { Tremor.SetupPage(); if (typeof (tremorOrigOnLoad) != "undefined" && tremorOrigOnLoad != null && tremorOrigOnLoad != TremorOnLoad) tremorOrigOnLoad(); }
var tremorOrigOnLoad = window.onload; if (tremorOrigOnLoad != TremorOnLoad) { window.onload = TremorOnLoad; }
var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } }; var Behaviour = { ruleList: [], register: function(rules) { this.ruleList.push(rules); }, apply: function() { Tremor.Debug.Log("should apply rules", "behavior", 1); for (var i = 0; i < this.ruleList.length; i++) { var r = this.ruleList[i]; Tremor.Debug.Log("apply " + r, "behavior", 1); for (p in r) { Tremor.Debug.Log("rule " + p, "behavior", 1); $(p).each(function() { r[p](this); }); } } }, applyElement: function(element) { for (var i = 0; i < this.ruleList.length; i++) { var r = this.ruleList[i]; Tremor.Debug.Log("apply " + r, "behavior", 1); for (p in r) { Tremor.Debug.Log("rule " + p, "behavior", 1); $(element).each(function() { r[p](this); }); $(p, element).each(function() { r[p](this); }); } } }, applyChildren: function(element) { for (var i = 0; i < this.ruleList.length; i++) { var r = this.ruleList[i]; Tremor.Debug.Log("apply " + r, "behavior", 1); for (p in r) { Tremor.Debug.Log("rule " + p, "behavior", 1); $(p, element).each(function() { r[p](this); }); } } } }; var AjaxResponse = function() { }; AjaxResponse.prototype = { url: null, params: null, callback: function(result) { this.responseText = result; if (this.params.onSuccess) { this.params.onSuccess(this); } } }; function AjaxJSONHeader(xml) { xml.setRequestHeader("accept", "text/json"); }
function AjaxRequest(url, params) {
    var myAjax = new AjaxResponse(); myAjax.url = url; myAjax.params = params; if (!params.asynchronous) { var result = $.ajax({ type: "POST", url: url, processData: false, data: params.parameters, dataType: 'json', async: false, beforeSend: AjaxJSONHeader }); if (params.onSuccess) { params.onSuccess(result); } }
    else {
        function AjaxCallback(result) { myAjax.callback(result.responseText); }
        $.ajax({ type: "POST", url: url, processData: false, data: params.parameters, complete: AjaxCallback, dataType: 'json', async: true, beforeSend: AjaxJSONHeader });
    }
    return myAjax;
}
if (typeof (Tremor) == "undefined") { Tremor = {}; }
function GetTimeString() { var d = new Date(); var s = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); return s; }
if (TremorApp.debug) {
    var tremorLog = log4javascript.getDefaultLogger(); Tremor.Debug = { Alert: function(message) { tremorLog.warn("alert: " + message, "exception", 2); alert(message); }, Warn: function(message) { tremorLog.warn("warning: " + message, "warning", 3); alert(message); }, Error: function(message) { tremorLog.error("exception: " + message, "exception", 2); alert(message); }, Exception: function(message) { tremorLog.error("exception: " + message, "exception", 1); alert(message); }, Log: function(message, module, level) {
        if (typeof (message) != 'string') { alert("invalid log: " + message); return; }
        var traceLevel = 0; if (Tremor.Util.IsDefined(TremorApp) && Tremor.Util.IsDefined(TremorApp.log_level)) {
            traceLevel = TremorApp.log_level[module]; if (traceLevel == null) { traceLevel = TremorApp.log_level.DEFAULT; }
            if (traceLevel == null) { traceLevel = 0; } 
        }
        if (level != null && level > traceLevel) { if (level > traceLevel) { return; } }
        else if (level == null && traceLevel < 3) { return; }
        var style = ""; if (module != null) {
            if (TremorApp.log_modules != null) { if (TremorApp.log_modules[module] == null) { return; } }
            message = "[" + module + "] " + message; if (Tremor.Util.IsDefined(TremorApp) && Tremor.Util.IsDefined(TremorApp.log_style) && TremorApp.log_style[module] != null) { style = TremorApp.log_style[module]; } 
        }
        tremorLog.debug(message);
    }, Assert: function(test, message) { if (!test) { Tremor.Debug.Error(message); throw message; } } 
    };
}
else { Tremor.Debug = { Error: function(message) { }, Exception: function(message) { }, Log: function(message, module, level) { }, Assert: function(test, message) { }, Alert: function(message) { } }; }; (function($) {
    $.fn.extend({ center: function(relativeTo) {
        var elem = this[0]; if (relativeTo == null) { relativeTo = window; }
        else { relativeTo = $(relativeTo)[0]; }
        elem.style.display = 'block'; var e = $(elem); var r = $(relativeTo); var s1 = { width: e.width(), height: e.height() }; var s2 = { width: r.width(), height: r.height() }; var p = { top: 0, left: 0 }; elem.style.position = 'absolute'; var l = (p.left + (s2.width - s1.width) / 2); if (l < 0) l = 0; var t = (p.top + (s2.height - s1.height) / 2)
        if (t < 0) t = 0; elem.style.left = "" + l + "px"; elem.style.top = "" + t + "px";
    } 
    });
})(jQuery); Tremor.Util = { nextGeneratedId: 10000, TrimString: function(sInString) { var out = sInString.replace(/^\s+/g, ""); out = out.replace(/\s+$/g, ""); return out; }, GetRequiredId: function(element) {
    if (element.id == null || element.id == "") { element.id = "tremorGeneratedId" + this.nextGeneratedId; this.nextGeneratedId = this.nextGeneratedId + 1; }
    return element.id;
}, behaviorSetupComplete: {}, IsBehaviorSetUp: function(element) { var complete = Tremor.Util.behaviorSetupComplete[Tremor.Util.GetRequiredId(element)]; return complete == element ? true : false; }, MarkBehaviorSetupComplete: function(element) { Tremor.Util.behaviorSetupComplete[Tremor.Util.GetRequiredId(element)] = element; }, DoOnce: function(element) {
    if (!Tremor.Util.IsBehaviorSetUp(element)) { Tremor.Util.MarkBehaviorSetupComplete(element); return true; }
    return false;
}, Log: function(module, level, msg) { if (TremorApp.log_modules != null && TremorApp.log_modules[module] != null && TremorApp.log_modules[module] <= level) { dbg_log(msg); } }, IsDefined: function(v) { return typeof (v) != "undefined"; }, IsEmptyString: function(s) { return s == null || !Tremor.Util.IsDefined(s) || !(typeof s == "string") || Tremor.Util.TrimString(s).length == 0; }, SetCookie: function(name, value, expireDays, path, domain, secure) {
    var expstring = null; if (expireDays != null) {
        var expires = new Date(); expires = new Date(expires.getTime() + expireDays * 24 * 60 * 60 * 1000); if (expires != null && expires.toGMTDateString) { expstring = expires.toGMTDateString(); }
        else if (expires != null && expires.toUTCString) { expstring = expires.toUTCString(); } 
    }
    var n = name + "=" + escape(value) +
((expstring == null) ? "" : ("; expires=" + expstring)) +
((path == null) ? "; path=/" : ("; path=" + path)) +
((domain == null) ? "" : (";domain=" + domain)) +
((secure == true) ? "; secure" : ""); Tremor.Debug.Log("set cookie: " + n, "cookie", 4); document.cookie = n;
}, GetCookie: function(name) {
    var val = ""; var search = "; " + name + "="; var cookies = "; " + document.cookie; if (document.cookie.length > 0) {
        offset = cookies.indexOf(search); if (offset != -1) {
            offset += search.length; end = cookies.indexOf(";", offset); if (end == -1)
                end = cookies.length; val = unescape(cookies.substring(offset, end));
        } 
    }
    Tremor.Debug.Log("get cookie: " + name + "=" + val, "cookie", 4); return val;
}, DeleteCookie: function(name) { Tremor.Util.SetCookie(name, "", 0); }, ShowElement: function(e) {
    Tremor.Debug.Warn("Using depricated method Tremor.Util.ShowElement.  Replace with Tremor.Element.Show()"); e = $(e)[0]; if (e && e.style && e.style.visibility != 'visible') { e.style.visibility = 'visible'; }
    if (e && e.style && (e.style.display == 'none' || e.style.display == '' || e.style.display == null)) {
        if (e.tagName == 'div') { e.style.display = 'block'; }
        else { e.style.display = 'inline'; } 
    } 
}, HideElement: function(e) { Tremor.Debug.Warn("Using depricated method Tremor.Util.HideElement.  Replace with Tremor.Element.Hide()"); e = $(e)[0]; e.style.display = 'none'; }, ParseUrl: function(url) {
    Tremor.Debug.Log("ParseUrl: " + url, "util", 4); var proto = ""; var host = ""; var query = ""; var params = {}; var fragment = null; if (url != null) {
        var frag = url.indexOf("#"); if (frag != -1) { fragment = url.substring(frag + 1); url = url.substring(0, frag); if (fragment.length > 1 && fragment[0] == '?' && url.substring(0, 4).toLowerCase() == "file") { url = url + "?" + fragment.substring(1); fragment = ""; } }
        var idx = url.indexOf("://"); if (idx != -1) {
            proto = url.substring(0, idx); url = url.substring(idx + 3); idx = url.indexOf("/"); if (idx == -1) { host = url; }
            else {
                host = url.substring(0, idx); url = url.substring(idx + 1); idx = url.indexOf("?"); if (idx == -1) { query = url; params.all = ""; }
                else { query = url.substring(0, idx); url = url.substring(idx + 1); var split = url.split("&"); for (var i = 0; i < split.length; i++) { var nameValue = split[i].split("="); params[nameValue[0].toLowerCase()] = nameValue[1]; } } 
            } 
        } 
    }
    return { protocol: proto, host: host, query: query, parameters: params, fragment: fragment };
}, ToString: function(o) {
    if (o == null || !Tremor.Util.IsDefined(o)) { return ""; }
    else {
        if (typeof o == "string" || typeof o == "number") { return o; }
        else if (typeof o == "array") {
            var s = []; for (var i = 0; i < o.length; i++) { s[s.length] = Tremor.Util.ToString(o[i]); }
            return '[' + ','.join(s) + ']';
        }
        return "";
    } 
}, letters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", IsAlpha: function(c) { return Tremor.Util.letters.indexOf(c) != -1; }, NextYear: function() { var d = new Date(); d.setFullYear(d.getFullYear() + 1); return d; }, FindElementById: function(id, parent) {
    if (parent == null) { parent = document; }
    var e = null; var i; for (i = 0; e == null && i < parent.childNodes.length; i++) { if (parent.childNodes[i].id == id) { e = parent.childNodes[i]; } }
    if (e == null) { for (i = 0; e == null && i < parent.childNodes.length; i++) { e = Tremor.Util.FindElementById(parent.childNodes[i], id); } }
    return e;
}, GetElementsByClass: function(className, parent) {
    var elements = new Array(); if (parent == null) { parent = document; }
    for (var i = 0; i < parent.childNodes.length; i++) {
        var child = parent.childNodes[i]; if (child.className != null) {
            var classNames = child.className.split(' '); var j; for (j = 0; j < classNames.length; j++) { if (classNames[j] == className) { elements.push(child); break; } }
            var c = Tremor.Util.GetElementsByClass(className, child); for (j = 0; j < c.length; j++) { elements.push(c[j]); } 
        } 
    }
    return elements;
}, GetElementByClass: function(className, parent) { var list = Tremor.Util.GetElementsByClass(className, parent); return list == null || list.length == 0 ? null : list[0]; }, GetChildrenByClass: function(className, parent) {
    var elements = []; for (var i = 0; i < parent.childNodes.length; i++) { var child = parent.childNodes[i]; if (child.className != null) { var classNames = child.className.split(' '); var j; for (j = 0; j < classNames.length; j++) { if (classNames[j] == className) { elements.push(child); break; } } } }
    return elements;
}, GetOptions: function(element) {
    element = $(element)[0]; var inner = element.innerHTML; inner = Tremor.Util.TrimString(inner); var o = {}; if (inner.startsWith("{") && inner.endsWith("}")) { var oe = document.createElement("div"); oe.innerHTML = inner; oe.className = "tremorOptions"; element.innerHTML = ""; element.appendChild(oe); }
    var e = Tremor.Util.GetChildrenByClass('tremorOptions', element)[0]; try { var edef = Tremor.Util.IsDefined(e); var idef = edef && Tremor.Util.IsDefined(e.innerHTML); if (idef) { if (e.innerHTML.length > 0) { o = Tremor.Util.Eval(e.innerHTML); } } }
    catch (ex) { Tremor.Debug.Error("invalid options for element " + element.id + ": " + e.innerHTML + "\n" + ex.message); o = null; }
    if (o == null) { o = {}; }
    return o;
}, Eval: function(x) { var r = null; eval("r = " + x); return r; }, CombineUrl: function(base, rel) {
    if (!rel.startsWith("http:") && !rel.startsWith("file:")) {
        var pos; var b; if (rel.startsWith('/')) { pos = base.indexOf('/', 9); b = base.substring(0, pos - 1); b = b + rel; return b; }
        else { pos = base.lastIndexOf('/'); b = base.substring(0, pos + 1); b = b + rel; return b; } 
    } 
}, AddUnique: function(array, val) {
    for (var i = 0; i < array.length; i++) { if (array[i] == val) { return; } }
    array[array.length] = val;
}, PageName: function() {
    var pageName = 'unknown'; var head = document.getElementsByTagName('head'); if (head != null && head.length > 0) { var meta = head[0].getElementsByTagName('meta'); for (var i = 0; meta != null && i < meta.length; i++) { var m = meta[i]; if (typeof m.name != 'undefined' && m.name.toLowerCase() == 'tremorpagename') { pageName = m.content; break; } } }
    return pageName;
} 
}; String.prototype.trim = function() { var s = this.replace(/^\s+/g, ""); return s.replace(/\s+$/g, ""); }; String.prototype.lastIndexOfNotUsed = function(c) {
    var pos = this.length - 1; while (pos >= 0 && this[pos] != c) { pos = pos - 1; }
    return pos;
}; String.prototype.endsWith = function(s) {
    Tremor.Debug.Log("ends with?: '" + this + "' '" + s + "'", "content", 1); if (this.length >= s.length) { var ss = this.substring(this.length - s.length); var result = ss == s; return result; }
    return false;
}; String.prototype.startsWith = function(s) {
    if (this.length >= s.length) { var ss = this.substring(0, s.length); var result = ss == s; return result; }
    return false;
}; Tremor.Element = { ScrollTo: function(e) { }, Show: function(e, visible) {
    if (e != null) { e = $(e)[0]; }
    if (typeof (visible) != "undefined" && visible == false) { Tremor.Element.Hide(e); return; }
    e = $(e)[0]; if (e != null && e.style != null) {
        if (e.style.visibility != 'visible') { e.style.visibility = 'visible'; }
        if (e.style.display == 'none' || e.style.display == null || e.style.display == '') {
            if (e.tagName == 'DIV') { e.style.display = 'block'; }
            else if (e.tagName == 'TR') { try { e.style.display = 'table-row'; } catch (ex) { e.style.display = 'block'; } }
            else { e.style.display = 'inline'; } 
        } 
    } 
}, Hide: function(e) {
    if (e != null) { e = $(e)[0]; }
    if (e != null) {
        if (e.style == null) { alert('excepted element'); }
        e.style.display = 'none'; e.style.visibility = 'hidden';
    } 
}, IsVisible: function(e) {
    e = $(e); var vis = true; while (e != null && vis) {
        if (e.style != null && (e.style.visibility == 'hidden' || e.style.display == 'none')) { vis = false; }
        e = e.parentNode;
    }
    return vis;
}, ToggleVisible: function(e) { e = $(e)[0]; var vis = Tremor.Element.IsVisible(e); Tremor.Element.Show(e, !vis); }, GetChildrenByTag: function(parent, tag) {
    tag = tag.toUpperCase(); var children = new Array(); for (var i = 0; i < parent.childNodes.length; i++) { var child = parent.childNodes[i]; if (child.tagName == tag) { children[children.length] = child; } }
    return children;
}, GetChildByTag: function(parent, tag) {
    tag = tag.toUpperCase(); for (var i = 0; i < parent.childNodes.length; i++) { var child = parent.childNodes[i]; if (child.tagName == tag) { return child; } }
    return null;
}, GetText: function(e) {
    var s = ""; for (var j = 0; j < e.childNodes.length; j++) { var c = e.childNodes[j]; if (c.nodeType == 3) { s = s + c.nodeValue; } }
    s = Tremor.Util.TrimString(s); return s;
}, GetChildrenByClass: function(parent, className) {
    var elements = new Array(); if (parent == null) { parent = document; }
    for (var i = 0; i < parent.childNodes.length; i++) {
        var child = parent.childNodes[i]; if (child.className != null) {
            var classNames = child.className.split(' '); var j; for (j = 0; j < classNames.length; j++) { if (classNames[j] == className) { elements.push(child); break; } }
            var c = Tremor.Util.GetElementsByClass(className, child); for (j = 0; j < c.length; j++) { elements.push(c[j]); } 
        } 
    }
    return elements;
}, GetChildByClass: function(parent, className) { var list = Tremor.Element.GetChildrenByClass(parent, className); return list == null || list.length == 0 ? null : list[0]; }, AddRoundCornersOld: function(element) {
    var borderColor = element.style.borderColor.split(' ')[0]; var bgColor = element.style.backgroundColor.split(' ')[0]; var borderWidth = parseInt(element.style.borderWidth.split(' ')[0], 10); var borderStyle = element.style.borderStyle.split(' ')[0]; var newElem = document.createElement("div"); newElem.style.height = element.style.height; newElem.style.width = element.style.width; element.style.height = "99%"; element.style.width = ""; element.parentNode.replaceChild(newElem, element); element.style.border = ""; var bstyle = "1px " + borderStyle.split(' ')[0] + " " + borderColor.split(' ')[0]; element.style.borderLeft = bstyle; element.style.borderRight = bstyle; var i; var title = element.title; var hasTitle = title != null && title != ""; for (i = 0; i < borderWidth; i++) {
        var d = document.createElement("div"); d.style.height = "1px"; d.style.overflow = "hidden"; d.style.marginLeft = "" + (borderWidth - i) + "px"; d.style.marginRight = "" + (borderWidth - i) + "px"; if (i == 0) { d.style.border = "0px"; d.style.borderTop = bstyle; d.style.backgroundColor = borderColor; }
        else {
            d.style.borderLeft = bstyle; d.style.borderRight = bstyle; if (hasTitle) { d.style.backgroundColor = borderColor; }
            else { d.style.backgroundColor = bgColor; } 
        }
        newElem.appendChild(d);
    }
    if (hasTitle) { var d = document.createElement("div"); d.style.marginLeft = "0px"; d.style.marginRight = "0px"; d.style.borderLeft = bstyle; d.style.borderRight = bstyle; d.style.backgroundColor = borderColor; d.style.color = bgColor; d.style.borderBottom = bstyle; d.innerHTML = "<span style='padding-left:" + (borderWidth + 2) + "px;'>" + title + "</span>"; newElem.appendChild(d); }
    newElem.appendChild(element); for (i = borderWidth - 1; i >= 0; i--) {
        var d = document.createElement("div"); d.style.height = "1px"; d.style.overflow = "hidden"; d.style.marginLeft = "" + (borderWidth - i) + "px"; d.style.marginRight = "" + (borderWidth - i) + "px"; if (i == 0) { d.style.borderTop = bstyle; }
        else { d.style.borderLeft = bstyle; d.style.borderRight = bstyle; d.style.backgroundColor = bgColor; }
        newElem.appendChild(d);
    } 
}, AddRoundCorners: function(element) {
    var borderColor = element.style.borderColor.split(' ')[0]; var bgColor = element.style.backgroundColor.split(' ')[0]; var borderWidth = parseInt(element.style.borderWidth.split(' ')[0], 10); var borderStyle = element.style.borderStyle.split(' ')[0]; var newElem = document.createElement("div"); newElem.style.height = element.style.height; newElem.style.width = element.style.width; element.style.height = "99%"; element.style.width = ""; element.parentNode.replaceChild(newElem, element); element.style.border = ""; var bstyle = "1px " + borderStyle.split(' ')[0] + " " + borderColor.split(' ')[0]; element.style.borderLeft = bstyle; element.style.borderRight = bstyle; var i; var title = element.title; var hasTitle = title != null && title != ""; for (i = 0; i < borderWidth; i++) {
        var d = document.createElement("div"); d.style.height = "1px"; d.style.overflow = "hidden"; d.style.marginLeft = "" + (borderWidth - i) + "px"; d.style.marginRight = "" + (borderWidth - i) + "px"; if (i == 0) { d.style.border = "0px"; d.style.borderTop = bstyle; d.style.backgroundColor = borderColor; }
        else {
            d.style.borderLeft = bstyle; d.style.borderRight = bstyle; if (hasTitle) { d.style.backgroundColor = borderColor; }
            else { d.style.backgroundColor = bgColor; } 
        }
        newElem.appendChild(d);
    }
    if (hasTitle) { var d = document.createElement("div"); d.style.marginLeft = "0px"; d.style.marginRight = "0px"; d.style.borderLeft = bstyle; d.style.borderRight = bstyle; d.style.backgroundColor = borderColor; d.style.color = bgColor; d.style.borderBottom = bstyle; d.innerHTML = "<div style='padding-left:" + (borderWidth + 2) + "px;'>" + title + "</div>"; newElem.appendChild(d); }
    newElem.appendChild(element); for (i = borderWidth - 1; i >= 0; i--) {
        var d = document.createElement("div"); d.style.height = "1px"; d.style.overflow = "hidden"; d.style.marginLeft = "" + (borderWidth - i) + "px"; d.style.marginRight = "" + (borderWidth - i) + "px"; if (i == 0) { d.style.borderTop = bstyle; }
        else { d.style.borderLeft = bstyle; d.style.borderRight = bstyle; d.style.backgroundColor = bgColor; }
        newElem.appendChild(d);
    } 
}, PosY: function(obj) {
    var curtop = 0; try {
        if (obj.offsetParent) {
            while (1) {
                curtop += obj.offsetTop; if (!obj.offsetParent)
                    break; obj = obj.offsetParent;
            } 
        }
        else if (obj.y) { curtop += obj.y; } 
    }
    catch (e) { }
    return curtop;
}, PosX: function(obj) {
    var curx = 0; if (obj.offsetParent) {
        while (1) {
            curx += obj.offsetLeft; if (!obj.offsetParent)
                break; obj = obj.offsetParent;
        } 
    }
    else if (obj.x) { curx += obj.x; }
    return curx;
}, GetAncestorByClass: function(e, className) {
    var n = e.parentNode; alert('not implemented for jquery'); while (n != null && !YAHOO.util.Dom.hasClass(n, className)) { n = n.parentNode; }
    return n;
} 
}; var javascriptrules = { '.tremorJavascript': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var javascript = element.innerHTML; javascript = javascript.trim(); if (javascript.startsWith("<!--") && javascript.endsWith("-->")) { javascript = javascript.substring(4, javascript.length - 3); }
        Tremor.Debug.Log("eval: " + javascript, "javascript", 4); try { RunInDocumentScope(function() { eval(javascript); }); } catch (e) { Tremor.Debug.Error("exception: " + e.message + "\nexecuting: " + javascript); if (TremorApp.debug) { throw e; } } 
    } 
} 
}; function RunInDocumentScope(f) { f.apply(document); }
Behaviour.register(javascriptrules); function $type(obj, types) {
    if (!obj) return false; var type = false; if (obj instanceof Function) type = 'function'; else if (obj.nodeName) { if (obj.nodeType == 3 && !/\S/.test(obj.nodeValue)) type = 'textnode'; else if (obj.nodeType == 1) type = 'element'; }
    else if (obj instanceof Array) type = 'array'; else if (typeof obj == 'object') type = 'object'; else if (typeof obj == 'string') type = 'string'; else if (typeof obj == 'number' && isFinite(obj)) type = 'number'; return type;
}
var transporttrules = { '.tremorRedirect': function(element) { if (!Tremor.Util.IsEmptyString(element.href)) { document.location = element.href; } }, '.tremorTransport': function(element) {
    var tranid = element.id; if (Tremor.Util.DoOnce(element)) {
        tranid = tranid.split(":")[0]; var eid = element.id; var href = element.href; var target = element.target; element.onclick = function() {
            Transport(eid, tranid, href, target); if (typeof (event) != "undefined" && event != null) { event.returnValue = false; }
            return false;
        };
    } 
} 
}; Behaviour.register(transporttrules); function Transport(eid, id, href, target) {
    var redirect = Tremor.Ajax.Call("tracking", "GetTransportUrl", { id: id, href: href }, { sync: true }); if (redirect != null && redirect.Type == "success") { href = redirect.url; }
    var a = $(eid)[0]; if (target == null || target == "") { document.location.href = href; }
    else { window.open(href, target); }
    return false;
}
var dragdroprules = { '.tremorDragdrop': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var moveId = element.id; var moveElement = element.parentNode; if (moveId != null && moveId != "") { var s = moveId.split(":"); if (s.length > 1) { moveId = s[0]; moveElement = $(moveId)[0] || element.parentNode; } }
        new Tremor.DragDrop(moveElement, element);
    } 
}, '.tremorSizeBorder': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var sizeId = element.id; var sizeElement = element; if (sizeId != null && sizeId != "") { var s = sizeId.split(":"); if (s.length > 1) { sizeId = s[0]; moveElement = $(sizeId)[0] || element; } }
        new Tremor.SizeBorder(element, sizeElement);
    } 
} 
}; Behaviour.register(dragdroprules); Tremor.DragDrop = Class.create(); Tremor.DragDrop.prototype = { initialize: function(moveElement, selElement) { this.selElement = selElement || moveElement; this.moveElement = moveElement; alert('not implemented for jquery'); YAHOO.util.Event.addListener(this.selElement, "mousedown", this.handleMouseDown, this, true); }, handleMouseDown: function(e, odd) { this.shim = new Tremor.Shim(); this.shim.opacity = 10; this.shim.Show(); alert('not implemented for jquery'); YAHOO.util.Event.addListener(document, "mousemove", this.handleMouseMove, this, true); YAHOO.util.Event.addListener(document, "mouseup", this.handleMouseUp, this, true); var p = YAHOO.util.Dom.getXY(this.moveElement); this.deltaSetXY = [0, 0]; this.startPageX = p[0]; this.startPageY = p[1]; var EU = YAHOO.util.Event; this.startPoint = new YAHOO.util.Point(EU.getPageX(e), EU.getPageY(e)); return false; }, handleMouseUp: function(e, odd) {
    if (this.shim != null) { this.shim.Hide(); this.shim = null; }
    alert('not implemented for jquery'); YAHOO.util.Event.removeListener(document, "mousemove", this.handleMouseMove); YAHOO.util.Event.removeListener(document, "mouseup", this.handleMouseUp); return false;
}, handleMouseMove: function(e, odd) { alert('not implemented for jquery'); var EU = YAHOO.util.Event; var curPoint = new YAHOO.util.Point(EU.getPageX(e), EU.getPageY(e)); this.moveElement.style.left = "" + (this.startPageX + (curPoint[0] - this.startPoint[0])) + "px"; this.moveElement.style.top = "" + (this.startPageY + (curPoint[1] - this.startPoint[1])) + "px"; return false; } 
}
Tremor.SizeBorder = Class.create(); Tremor.SizeBorder.prototype = { OFF: 0, TOP: 1, BOTTOM: 2, LEFT: 3, RIGHT: 4, TL: 5, TR: 6, BL: 7, BR: 8, initialize: function(element, targetElement) { this.element = element; this.targetElement = targetElement; alert('not implemented for jquery'); YAHOO.util.Event.addListener(this.element, "mousedown", this.startResize, this, true); YAHOO.util.Event.addListener(this.element, "mouseover", this.handleMouseOver, this, true); YAHOO.util.Event.addListener(this.element, "mousemove", this.SetCursor, this, true); }, GetBorder: function(ev) {
    var x = ev.offsetX || ev.layerX; var y = ev.offsetY || ev.layerY; var h = this.element.offsetHeight; var w = this.element.offsetWidth; var bw = 8; if (x < bw) { if (y < bw) return this.TL; if (h - bw < y) return this.BL; return this.LEFT; }
    else if (w - bw < x) { if (y < bw) return this.TR; if (h - bw < y) return this.BR; return this.RIGHT; }
    else if (y < bw) { return this.TOP; }
    else if (h - bw < y) { return this.BOTTOM; }
    return this.OFF;
}, handleMouseOver: function(ev, odd) { this.SetCursor(ev); }, SetCursor: function(ev) {
    var border = this.GetBorder(ev); var cursor = null; switch (border) { case this.TOP: cursor = "n-resize"; break; case this.BOTTOM: cursor = "s-resize"; break; case this.LEFT: cursor = "w-resize"; break; case this.RIGHT: cursor = "e-resize"; break; case this.TL: cursor = "nw-resize"; break; case this.TR: cursor = "ne-resize"; break; case this.BL: cursor = "sw-resize"; break; case this.BR: cursor = "se-resize"; break; }
    if (cursor != null) { this.element.style.borderSize = ev.offsetX; this.element.style.cursor = cursor; }
    return false;
}, startResize: function(e, odd) {
    this.sizeBorder = this.GetBorder(e); if (this.sizeBorder == this.OFF) { return; }
    this.shim = new Tremor.Shim(); this.shim.opacity = 50; this.shim.Show(); alert('not implemented for jquery'); YAHOO.util.Event.addListener(document, "mousemove", this.resize, this, true); YAHOO.util.Event.addListener(document, "mouseup", this.endSize, this, true); this.startRegion = YAHOO.util.Dom.getRegion(this.targetElement); this.startPoint = new YAHOO.util.Point(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); this.startLeft = this.targetElement.offsetLeft; this.startWidth = this.targetElement.offsetWidth; this.startTop = this.targetElement.offsetTop; this.startHeight = this.targetElement.offsetHeight; var EU = YAHOO.util.Event; return false;
}, endSize: function(e, odd) {
    if (this.shim != null) { this.shim.Hide(); this.shim = null; }
    alert('not implemented for jquery'); YAHOO.util.Event.removeListener(document, "mousemove", this.resize); YAHOO.util.Event.removeListener(document, "mouseup", this.endSize); return false;
}, resize: function(e, odd) {
    alert('not implemented for jquery'); var curPoint = new YAHOO.util.Point(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); switch (this.sizeBorder) { case this.TL: cursor = "nw-resize"; this.targetElement.style.top = "" + (this.startTop + (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.height = "" + (this.startHeight - (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.left = "" + (this.startLeft + (curPoint[0] - this.startPoint[0])) + "px"; this.targetElement.style.width = "" + (this.startWidth - (curPoint[0] - this.startPoint[0])) + "px"; break; case this.TR: cursor = "ne-resize"; this.targetElement.style.top = "" + (this.startTop + (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.height = "" + (this.startHeight - (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.width = "" + (this.startWidth + (curPoint[0] - this.startPoint[0])) + "px"; break; case this.TOP: this.targetElement.style.top = "" + (this.startTop + (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.height = "" + (this.startHeight - (curPoint[1] - this.startPoint[1])) + "px"; break; case this.BR: cursor = "se-resize"; this.targetElement.style.height = "" + (this.startHeight + (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.width = "" + (this.startWidth + (curPoint[0] - this.startPoint[0])) + "px"; break; case this.BL: cursor = "sw-resize"; this.targetElement.style.height = "" + (this.startHeight + (curPoint[1] - this.startPoint[1])) + "px"; this.targetElement.style.left = "" + (this.startLeft + (curPoint[0] - this.startPoint[0])) + "px"; this.targetElement.style.width = "" + (this.startWidth - (curPoint[0] - this.startPoint[0])) + "px"; break; case this.BOTTOM: this.targetElement.style.height = "" + (this.startHeight + (curPoint[1] - this.startPoint[1])) + "px"; break; case this.LEFT: cursor = "w-resize"; this.targetElement.style.left = "" + (this.startLeft + (curPoint[0] - this.startPoint[0])) + "px"; this.targetElement.style.width = "" + (this.startWidth - (curPoint[0] - this.startPoint[0])) + "px"; break; case this.RIGHT: cursor = "e-resize"; this.targetElement.style.width = "" + (this.startWidth + (curPoint[0] - this.startPoint[0])) + "px"; break; }
    WindowResize(); return false;
} 
}
var zebrarules = { '.tremorZebraTable': function(element) { if (Tremor.Util.DoOnce(element)) { if (element.tagName == "TABLE") { var table = new Tremor.Table(element); table.Stripe("oddRow", "evenRow"); } } } }; Behaviour.register(zebrarules); Tremor.Table = Class.create(); Tremor.Table.prototype = { table: null, initialize: function(element) { table = element; }, Stripe: function(oddClass, evenClass) {
    var tbody = table.getElementsByTagName("tbody"); var rows; if (tbody != null) { for (var i = 0; i < tbody.length; i++) { this.StripeRows(tbody[i].getElementsByTagName("tr"), oddClass, evenClass); } }
    else { this.StripeRows(table.getElementsByTagName("tr"), oddClass, evenClass); } 
}, StripeRows: function(rows, oddClass, evenClass) { var odd = true; for (var i = 0; i < rows.length; i++) { var add = odd ? oddClass : evenClass; var remove = !odd ? oddClass : evenClass; $(rows[i]).addClass(add); $(rows[i]).removeClass(remove); odd = !odd; } } 
}
Tremor.Ajax = { lastResponse: null, requestCount: 0, StartRequest: function() { $('#ajaxWorkingMessage').show(); $('#tremorWorkingMessage').show(); Tremor.Ajax.requestCount = Tremor.Ajax.requestCount + 1; Tremor.Debug.Log("request count: " + Tremor.Ajax.requestCount, "ajax", 4); }, EndRequest: function() { Tremor.Ajax.requestCount = Tremor.Ajax.requestCount - 1; if (Tremor.Ajax.requestCount == 0) { $('#ajaxWorkingMessage').show(); $('#tremorWorkingMessage').show(); } }, Call: function(service, method, parameters, options) {
    if (options == null) { options = {}; }
    Tremor.Ajax.StartRequest(); var url = null; if (document.location.href.indexOf("https") == 0 || (options != null && options.secure)) { url = TremorApp.ajax_url_https || TremorApp.ajax_url_secure; }
    else { url = TremorApp.ajax_url; }
    var reqParams = "ajaxversion=" + Tremor.version + "&service=" + service + "&request=" + method + "&pageName=" + Tremor.Util.PageName(); reqParams = reqParams + this.OptionalParam("authToken", Tremor.AuthToken()); if (reqParams.indexOf('realm=') != -1) { reqParams = reqParams + this.OptionalParam("realm", Tremor.realm); }
    if (TremorApp.program_name != null) { reqParams = reqParams + "&program=" + escape(TremorApp.program_name); }
    if (parameters != null) { reqParams = reqParams + this.CreateParamPairs(parameters); }
    if (reqParams == null || reqParams == "") { reqParams = "pageParameters=" + escape(document.location.search); }
    else { reqParams = reqParams + "&pageParameters=" + escape(document.location.search); }
    reqParams = reqParams + "&" + Tremor.Ajax.TrackingBrowserInfo(); Tremor.Debug.Log("request: " + reqParams, "ajax", 4); var async = options.sync != true && options.sync != "true"; var reqOptions = { method: 'post', requestHeaders: ['accept', 'text/jason'], parameters: reqParams, asynchronous: false }; Tremor.Debug.Log("async request", "ajax", 4); var successCallback = options.onSuccess; var failCallback = options.onFail; var progress = null; if (async && options.showProgressOver != null) { progress = Tremor.Ajax.CreateProgressOverlay(options.showProgressOver); }
    reqOptions.onSuccess = function(x) {
        Tremor.Ajax.EndRequest(); try { Tremor.Ajax.OnSuccess(x, successCallback, failCallback); } catch (e) { Tremor.Debug.Log("ajax failed to handle response: " + e.message, "ajax", 2); Tremor.Ajax.OnFail(x, failCallback); }
        Tremor.Ajax.HideProgressOverlay(progress);
    }; reqOptions.onFailure = function(x) { Tremor.Ajax.EndRequest(); Tremor.Ajax.OnFail(x, failCallback); HideProgressOverlay(progress); }; reqOptions.asynchronous = async; reqOptions.sync = !async; Tremor.Debug.Log("send request: " + url, "ajax", 4); reqOptions.dataType = 'json'; var myAjax = AjaxRequest(url, reqOptions);
}, CreateProgressOverlay: function(showProgressOver) { var overlay = document.createElement('div'); var offset = $(showProgressOver).offset(); var height = $(showProgressOver).height(); var width = $(showProgressOver).width(); overlay.style.left = "" + offset.left + "px"; ; overlay.style.top = "" + offset.top + "px"; overlay.style.width = "" + width + "px"; overlay.style.height = "" + height + "px"; overlay.style.position = "absolute"; overlay.className = "progressOverlay"; overlay.style.display = "block"; overlay.style.visibility = "visible"; overlay.style.zIndex = 2000; $(document.body).append(overlay); return overlay; }, HideProgressOverlay: function(progressOverlay) { if (progressOverlay != null) { $(progressOverlay).remove(); } }, OnSuccess: function(response, successCallback, failCallback) {
    this.lastResponse = response; Tremor.Debug.Log("ajax request succeeded", "ajax", 3); try { var text = response.responseText; Tremor.Debug.Log("response: " + text, "ajax", 4); eval("var json = (" + text + ")" + ";"); }
    catch (e) { Tremor.Debug.Log("cannot parse response: " + response.responseText); Tremor.Debug.Log("exception: " + e); Tremor.Ajax.OnFail(response, failCallback); return false; }
    var result = json.result; this.lastResponse = result; if (result == null || response.status < 200 || response.status >= 300) {
        Tremor.Debug.Error("no result returned"); if (failCallback) { Tremor.Ajax.OnFail(response, failCallback); }
        return false;
    }
    var success = false; if (result.Redirect) { window.location.href = result.Location; return; }
    if (result.AjaxException) {
        var msg = ""; if (result.AjaxErrorMessage) { msg = result.AjaxErrorMessage + "\n\n"; Tremor.Content.ShowErrorNotice(result.AjaxErrorMessage); }
        msg = msg + result.AjaxException; Tremor.Debug.Exception(msg);
    }
    else if (result.AjaxErrorMessage) { Tremor.Content.ShowErrorNotice(result.AjaxErrorMessage); Tremor.Debug.Error(result.AjaxErrorMessage); }
    else {
        if (result.AjaxSuccess) {
            result = result.ServiceResult; if (result.Type == "error") { Tremor.Content.ShowErrorNotice(result.Notice, result.NoticeDisplaySeconds); success = false; }
            else { Tremor.Content.ShowNotice(result.Notice, result.NoticeDisplaySeconds); success = true; } 
        } 
    }
    if (success && successCallback) { successCallback(result); }
    else if (!success) { Tremor.Ajax.OnFail(response, failCallback); }
    return success;
}, OnFail: function(response, callback) {
    this.lastResponse = response; Tremor.Debug.Log("ajax request failed", "ajax", 3); if (response && callback) {
        var json = null; try { var text = response.responseText; eval("json = (" + text + ")" + ";"); this.lastResponse = json.result; }
        catch (e) { }
        callback(response, json);
    } 
}, OptionalParam: function(name, val) {
    if (val != null) { return "&" + name + "=" + val; }
    return "";
}, CreateParamPairs: function(params) {
    if (typeof params == 'string') { return params; }
    var s = ""; for (var n in params) { if (params[n] != null && n != 'service' && n != 'request' && ((typeof params[n]) != 'function')) { s = s + "&"; s = s + n + "=" + escape('' + params[n]).replace(/\+/g, '%2B'); } }
    return s;
}, TrackingBrowserInfo: function() { var s = "tdatetime=" + escape(Tremor.Ajax.GetGMT()) + "&tcaps=" + escape(Tremor.Ajax.GetCaps()) + "&ttimezone=" + escape(Tremor.Ajax.GetTimeZone()); return s; }, GetCaps: function() {
    var caps = "v1"
+ "~" + screen.width
+ "~" + screen.height
+ "~" + screen.colorDepth; return caps;
}, GetGMT: function() {
    var now = new Date(); if (now.toGMTString) { return now.toGMTString(); }
    return "na";
}, GetTimeZone: function() {
    var now = new Date(); if (now.getTimezoneOffset) { return now.getTimezoneOffset(); }
    return "na";
}, AddHiddenValues: function(form) { form = $(form)[0]; Tremor.Ajax.AddHiddenValue(form, "pageParameters", escape(document.location.search)); Tremor.Ajax.AddHiddenValue(form, "ajaxversion", Tremor.version); Tremor.Ajax.AddHiddenValue(form, "pageName", Tremor.Util.PageName()); }, AddHiddenValue: function(form, name, val) { var e = document.createElement('INPUT'); e.setAttribute('type', 'hidden'); e.setAttribute('name', name); e.setAttribute('value', val); form.appendChild(e); } 
}; $().ajaxStart(function() { $('body').css('cursor', 'wait'); })
$().ajaxStop(function() { $('body').css('cursor', 'default'); })
var contentrules = { '.tremorContent': function(element) { if (Tremor.Util.DoOnce(element)) { Tremor.Content.LoadContent(element); } }, '.tremorControl': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var name = null; var options = Tremor.Util.GetOptions(element); var empty = {}; var params = null; if (options == null || options.params == null) { params = {}; }
        else { params = options.params; }
        if (options != null && typeof options.url != "undefined") { name = options.url; }
        else { name = element.id.split(':')[0]; }
        var filename = name.replace(/-/g, '/'); Tremor.Content.LoadControl(element, filename, params);
    } 
} 
}; Behaviour.register(contentrules); Tremor.Content = { Load: function(targetElement, file, params, options) {
    var overlay = Tremor.Ajax.CreateProgressOverlay(targetElement); $(targetElement).load(file, params, function() {
        Behaviour.applyChildren($(targetElement)[0]); Tremor.Ajax.HideProgressOverlay(overlay); if (typeof options == 'function') { options(); }
        else if (options != null && options.onSuccess) { options.onSuccess(); } 
    });
}, LoadControl: function(targetElementOrId, controlName, params, options) {
    this.HideNotice(); var targetElement = $(targetElementOrId)[0]; if (targetElement == null && typeof targetElementOrId == 'string') { targetElement = $('#' + targetElementOrId)[0]; }
    if (targetElement == null) { Tremor.Debug.Alert("unknow control: " + targetElementOrId); return; }
    if (typeof options == 'function') { options = { onSuccess: options }; }
    var opt = options || Tremor.Util.GetOptions(targetElement); options = opt; var nf = '#'; params = params || options.parameters; if ($(targetElement).is('.tremorBookmark')) {
        var f = location.hash; var tid = targetElement.id; var found = false; if (f != null && f != '') {
            var parts = f.substring(1).split(","); for (var i = 0; i < parts.length; i++) {
                if (i > 0) { nf = nf + ","; }
                var nv = parts[i].split("="); if (nv.length > 1) {
                    if (nv[0] == tid) { nf = nf + nv[0] + "=" + controlName; found = true; }
                    else { nf = nf + parts[i]; } 
                } 
            }
            if (!found) { nf = nf + "," + targetElement.id + "=" + controlName; } 
        }
        else { nf = nf + targetElement.id + "=" + controlName; }
        window.location.hash = nf;
    }
    params = params || {}; if (!Tremor.Util.IsDefined(params.sync)) { params.sync = false; }
    if (controlName == null) { var name = targetElement.id.split(':'); controlName = name[0]; }
    if (controlName.indexOf(".") == -1) { controlName = controlName + ".thtml"; }
    targetElement = $(targetElement)[0]; Tremor.Debug.Assert(targetElement != null, "missing targetElement in Tremor.Content.LoadControl"); Tremor.Debug.Assert(controlName != null, "missing controlName in Tremor.Content.LoadControl"); var url = controlName; url = url.replace(/-/g, "/"); if (document.location.protocol == "file:") { var text = Tremor.Content.GetFileContents(url); Tremor.Debug.Log("contents: " + text, "content", 4); Tremor.Content.LoadTemplate(targetElement, text, params, options); }
    else {
        params.templateName = controlName; options.sync = options.sync || params.sync; Tremor.Debug.Log("load: " + url, "content", 4); var parameters = params.parameters; if (typeof parameters == "undefined") { parameters = params; }
        parameters = Tremor.Ajax.CreateParamPairs(parameters); if (parameters == null || parameters == "") { parameters = "pageParameters=" + escape(document.location.search); }
        else { parameters = parameters + "&pageParameters=" + escape(document.location.search); }
        parameters = parameters + "&" + Tremor.Ajax.TrackingBrowserInfo(); Tremor.Debug.Log("parameters: " + parameters, "content", 4); Tremor.Ajax.StartRequest(); var myAjax = AjaxRequest(url, { parameters: parameters, method: 'get', asynchronous: !options.sync, onSuccess: function(x) { Tremor.Content.OnSuccess(x.responseText, targetElement, params, options); Tremor.Ajax.EndRequest(); }, onFailure: function(x) { Tremor.Content.OnFail(x, targetElement, options); Tremor.Ajax.EndRequest(); } });
    } 
}, LoadTemplate: function(targetElement, template, params) {
    if (params == null) { params = { sync: false }; }
    targetElement = $(targetElement)[0]; Tremor.Debug.Assert(targetElement != null, "missing targetElement in Tremor.Content.LoadTemplate"); Tremor.Debug.Log("load template: " + targetElement.id); var telement = $(template)[0]; if (telement == null) { params.template = template; }
    else { params.template = telement.innerHTML; }
    var targetId = Tremor.Util.GetRequiredId(targetElement); var options = {}; options.onSuccess = function(x) { Tremor.Content.OnSuccess(x, targetId, params); }; options.onFail = function(x) { Tremor.Content.OnFail(x, targetId); }; options.sync = false; options.showProgressOver = targetElement; var resp = Tremor.Ajax.Call("content", "FillTemplate", params, options);
}, CreateElements: function(data) {
    var e = null; data = Tremor.Util.TrimString(data); if (data.startsWith('<tr')) { e = document.createElement("table"); var b = document.createElement("tbody"); e.appendChild(b); b.innerHTML = data; e = b; }
    else if (data.startsWith('<td')) { e = document.createElement("table"); var r = document.createElement("tr"); r.innerHTML = data; e = r; }
    else { e = document.createElement('span'); e.innerHTML = data; }
    var l = e.childNodes; return l;
}, OnSuccess: function(data, target, params, options) {
    try {
        params = params || {}; target = $(target)[0]; Tremor.Debug.Log("load succeeded: " + data, "content", 4); Tremor.Debug.Assert(target != null, "missing targetElement in Tremor.Content.LoadTemplate"); var applyBehaviors = true; var newElements; var n; if ((typeof (params) != 'undefined' && typeof (params.noBehaviors) != 'undefined' && params.noBehaviors == true) || (typeof (options) != 'undefined' && typeof (options.noBehaviors) != 'undefined' && options.noBehaviors == true)) { applyBehaviors = false; }
        if ((typeof (params) != 'undefined' && typeof (params.insertBefore) != 'undefined' && params.insertBefore == true) || (typeof (options) != 'undefined' && typeof (options.insertBefore) != 'undefined' && options.insertBefore == true)) { newElements = this.CreateElements(data); while (newElements.length > 0) { n = newElement.childNodes[i]; target.parentNode.insertBefore(newElements[i], target); if (applyBehaviors) { Behaviour.applyElement(n); } } }
        else if ((typeof (params) != 'undefined' && typeof (params.replace) != 'undefined' && params.replace == true) || (typeof (options) != 'undefined' && typeof (options.replace) != 'undefined' && options.replace == true)) {
            newElements = this.CreateElements(data); n = newElements[0]; var p = target.parentNode; p.replaceChild(n, target); var b = []; b[0] = n; while (newElements.length > 0) { n = newElements[0]; p.appendChild(n); b[b.length] = n; }
            if (applyBehaviors) { for (var i = 0; i < b.length; i++) { Behaviour.applyChildren(b[i]); } } 
        }
        else { target.innerHTML = data; Tremor.Element.Show(target); if (applyBehaviors) { Behaviour.applyChildren(target); } }
        if (options != "undefined" && options != null && options.onSuccess != null) { options.onSuccess(); } 
    }
    catch (e) { Tremor.Debug.Error("failed to load content: " + e.message); } 
}, OnFail: function(data, target) {
    Tremor.Debug.Log("load failed: " + data, "content", 4); target.innerHTML = ""; if (TremorApp.debug) { target.innerHTML = 'error'; }
    Tremor.Element.Show(target);
}, LoadContent: function(element, templateElement) {
    element = $(element)[0]; templateElement = $(templateElement) || document.getElementById(element.id + ":template"); if (templateElement == null) { templateElement = element; }
    var template = templateElement.innerHTML; Tremor.Debug.Log("load template: " + template, "content", 4); Tremor.Content.LoadTemplate(element, template);
}, ShowNotice: function(notice, showSeconds) {
    var noticeElement = $('#tremorAjaxNotice')[0]; if (noticeElement != null) {
        if (!Tremor.Util.IsEmptyString(notice)) { noticeElement.innerHTML = notice; Tremor.Element.Show(noticeElement); if (showSeconds > 0) { setTimeout(function() { Tremor.Element.Hide(noticeElement); }, 1000 * showSeconds); } }
        else { Tremor.Element.Hide(noticeElement); } 
    }
    $('#tremorAjaxErrorNotice').hide();
}, ShowErrorNotice: function(notice) {
    var noticeElement = $('#tremorAjaxErrorNotice')[0] || $('#tremorAjaxNotice')[0]; if (noticeElement != null) {
        if (!Tremor.Util.IsEmptyString(notice)) { noticeElement.innerHTML = notice; Tremor.Element.Show(noticeElement); }
        else { Tremor.Element.Hide(noticeElement); } 
    } 
}, HideNotice: function() {
    var noticeElement = $('#tremorAjaxErrorNotice')[0]; if (noticeElement != null) { Tremor.Element.Hide(noticeElement); }
    noticeElement = $('#tremorAjaxNotice')[0]; if (noticeElement != null) { Tremor.Element.Hide(noticeElement); } 
}, LoadFragments: function() { var hash = location.hash; if (hash != null && hash != '') { var s = hash.substring(1).split(","); for (var i = 0; i < s.length; i++) { var p = s[i].split("="); if (p.length > 1) { Tremor.Content.LoadControl(p[0], p[1]); } } } }, GetFileContents: function(name) { Tremor.Debug.Log("loading file: " + name, "content", 4); var myAjax = new Ajax.Request(name, { method: 'get', asynchronous: false }); var text = myAjax.transport.responseText; return text; } 
}; $(document).ready(function() { Tremor.Content.LoadFragments(); }); var calendarrules = { '.tremorCalendar': function(element) { if (Tremor.Util.DoOnce(element)) { Tremor.Calendar.Setup(element); } } }; Behaviour.register(calendarrules); Tremor.Calendar = { Setup: function(element) { $(element).datepicker({ showOn: 'both', buttonImageOnly: true, buttonImage: '/common/v3/images/calendar.gif', buttonText: 'Calendar' }); } }
var tabrules = { '.tremorTabContainer': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var cache = false; if ($(element).hasClass('cachePanels')) { cache = true; }
        $(element).tabs({ show: TabLoaded, cache: cache });
    } 
}, '.tremorRemoteTabContainer': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var cache = false; if ($(element).hasClass('cachePanels')) { cache = true; }
        $(element).tabs({ remote: true, show: TabLoaded, cache: cache }); $(element).show();
    } 
} 
}; Behaviour.register(tabrules); function TabLoaded(tab) { Behaviour.applyChildren(null); }
var nextShimId = 1000; var Shim = Class.create(); Shim.prototype = { opacity: 50, zIndex: 50, cursor: 'default', initialize: function() { this.opacity = 50; this.zIndex = 50; this.shim = null; this.backgroundColor = '#fff'; }, Create: function() { if (this.shim == null) { this.shim = document.createElement('div'); this.shim.id = 'fcshim-' + nextShimId; this.shim.style.zIndex = '' + this.zIndex; this.shim.style.backgroundColor = this.backgroundColor; this.shim.style.position = 'absolute'; this.shim.style.cursor = this.cursor; this.shim.style.opacity = "" + this.opacity / 100; this.shim.style.filter = "alpha(opacity=" + this.opacity + ")"; document.body.appendChild(this.shim); } }, Show: function() {
    if (document.documentElement.scrollTop) { document.documentElement.scrollTop = 0; }
    else if (document.body.scrollTop) { document.body.scrollTop = 0; }
    this.Cover(window);
}, Cover: function(elem) { this.Create(); var e = $(elem); var p = elem == window ? { left: 0, top: 0} : e.position(); ; var s = { width: e.width(), height: e.height() }; this.shim.style.left = "" + p.left + "px"; this.shim.style.top = "" + p.top + "px"; this.shim.style.width = "" + s.width + "px"; this.shim.style.height = "" + s.height + "px"; this.shim.style.display = 'block'; }, Hide: function() { if (this.shim != null) { this.shim.style.display = 'none'; } } 
}; Tremor.Dialog = { shim: null, HideShim: function() { if (Tremor.Dialog.shim != null) { Tremor.Dialog.shim.Hide(); } }, ShowShim: function() {
    if (Tremor.Dialog.shim == null) { Tremor.Dialog.shim = new Shim(); }
    Tremor.Dialog.shim.Show();
}, Show: function(id) {
    Tremor.Dialog.ShowShim(); var dlg = $(id)[0]; if (dlg.parentNode != document.body) { document.body.appendChild(dlg); }
    Tremor.Dialog.curDlg = dlg; $('#' + id).fadeIn('slow'); $(dlg).center(); dlg.style.top = '25%'; $('.autoFocus', Tremor.Dialog.curDlg).each(function() { this.focus(); }); $('.tremorCancel', dlg).click(Tremor.Dialog.Cancel); $('.tremorOK', dlg).click(Tremor.Dialog.Submit); $(document).keypress(function(e) { if (e.which == 27) { Tremor.Dialog.Cancel(); }; });
}, Submit: function() {
    var dlg = Tremor.Dialog.curDlg; var form = $('form', dlg)[0]; var end = true; if (form != null) {
        if (Tremor.Validate.ValidateForm(form[0])) { try { Tremor.Form.Submit(form); } catch (e) { Tremor.Debug.Log('error: ' + e, 'dialog', 1); } }
        else { end = false; } 
    }
    if (end) { Tremor.Dialog.End(); }
    return false;
}, Cancel: function() { Tremor.Dialog.End(); return false; }, End: function() { if (Tremor.Dialog.curDlg != null) { $(Tremor.Dialog.curDlg).fadeOut('slow', Tremor.Dialog.HideShim); } } 
}
var formrules = { '.tremorForm': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        if (element.className.indexOf('tremorNoAutoFocus') == -1) { if (element.focus == null) { Tremor.Form.SetFocus(element); } }
        var form = Tremor.Form.GetForm(element); Tremor.Form.SetInputNames(form); if (element.onsubmit == null) {
            form.onsubmit = function() {
                if (Tremor.Validate == null || Tremor.Validate.ValidateForm(element)) {
                    Tremor.Form.Submit(form); if (typeof (event) != "undefined" && event != null) { event.returnValue = false; }
                    return false;
                }
                else { return false; } 
            };
        } 
    } 
}, '.tremorUploadForm': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        if (element.className.indexOf('tremorNoAutoFocus') == -1) { Tremor.Form.SetFocus(element); }
        var form = Tremor.Form.GetForm(element); var n = "resultFrame:" + Tremor.Util.GetRequiredId(element); form.setAttribute('target', n); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute("action", "upload.ashx"); form.setAttribute("method", "POST"); form.enctype = 'multipart/form-data'; form.encoding = 'multipart/form-data'; form.action = "upload.ashx"; form.method = "POST"; form.target = n; Tremor.Ajax.AddHiddenValues(form); Tremor.Ajax.AddHiddenValue(form, 'returnType', 'html/javascript-variable'); var d = document.getElementById(n); if (d == null) { d = document.createElement('DIV'); var pos = ";left:-9999px;width:1px;height:1px;"; d.innerHTML = '<iframe style="display:block;border:1px solid #000;position:absolute;bottom:0px' + pos + '"  id="' + n + '" name="' + n + '" onload="Tremor.Form.IFrameResultLoaded(\'' + element.id + '\',\'' + n + '\')" src=\'about:blank\'></iframe>'; document.body.appendChild(d); }
        form.onsubmit = function() {
            if (Tremor.Validate == null || Tremor.Validate.ValidateForm(form)) {
                var r = true; if (typeof (event) != "undefined" && event != null) { event.returnValue = r; }
                form.submit(); return r;
            }
            else {
                if (typeof (event) != "undefined" && event != null) { event.returnValue = false; }
                return false;
            } 
        };
    } 
}, '.tremorSubmit': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var form = element.parentNode; while (form != null && form.tagName != "FORM") { form = form.parentNode; }
        if (form != null) {
            Tremor.Form.SetDefaultButton(form, element); var oldOnclick = element.onclick; element.onclick = function() {
                if (oldOnclick) { var oc = oldOnclick(); if (typeof (oc) != "undefined" && oc == false) { return false; } }
                if (form.onsubmit != null) { form.onsubmit(); }
                else { if (Tremor.Validate == null || Tremor.Validate.ValidateForm(form)) { Tremor.Form.Submit(form); } }
                return false;
            };
        }
        if (typeof element.href != "undefined") { element.href = "javascript:"; } 
    } 
}, '.tremorReset': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        if (true || element.onclick == null) {
            var form = element.parentNode; while (form != null && form.tagName != "FORM") { form = form.parentNode; }
            if (form != null) {
                element.onclick = function() {
                    var first = null; for (var b = 0; b < form.length; b++) {
                        var myObj = form[b]; if (first == null) first = myObj; if (myObj.type == "text" || myObj.type == "textarea" || myObj.type == "file" || myObj.type == "password") { myObj.value = ""; }
                        else if (myObj.type.toString().charAt(0) == "s" && myObj.selectedIndex != 0) { myObj.selectedIndex = 0; }
                        else if (myObj.type == "checkbox" || myObj.type == "radio") { myObj.checked = false; } 
                    }
                    if (first != null) { first.focus(); }
                    return false;
                };
            } 
        } 
    } 
}, '.tremorDefaultOption': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var sel = null; if (element.id != null && element.id.endsWith(":default")) { var id = element.id.substring(0, element.id.length - ":default".length); sel = $(id)[0]; if (sel == null) { return; } }
        sel = sel || element.parentNode; var defOption = -1; var val = null; if (element.tagName == "OPTION") { val = element.value || element.innerHTML; }
        else { val = element.innerHTML; }
        val = val.toLowerCase(); Tremor.Debug.Log("tremorDefaultOption for " + sel.id + " " + val); var hasSelected = false; if (sel.selectedIndex > 0) { hasSelected = true; }
        for (var i = 0; i < sel.options.length; i++) {
            var o = sel.options[i]; if (o == element) { defOption = i; }
            else if (o.value.toLowerCase() == val) { o.selected = 'selected'; }
            else if (!hasSelected) { o.selected = ''; } 
        }
        if (defOption != -1) { sel.options[defOption] = null; } 
    } 
} 
}; Behaviour.register(formrules); function DisableForm(form) { for (var i = 0; i < form.length; i++) { var e = form[i]; e.disabled = true; } }
function EnableForm(form) { for (var i = 0; i < form.length; i++) { var e = form[i]; e.disabled = false; } }
function get_form_params(form) {
    var params = new Object; for (var p in params) { params[p] = null; }
    var i = 0; for (i = 0; i < form.elements.length; i++) {
        var n = form.elements[i].name; if (n == null || n == "") { n = form.elements[i].id; }
        var v = form.elements[i].value; if (n != null && v != null && n != "" && n != 'extend') {
            if (n == "fileName" && document.location.protocol == "file:") { params[n] = "FILE_CONTENTS[" + Tremor.Content.GetFileContent(v); +"]"; }
            else if (form.elements[i].type == 'checkbox') { params[n] = (form.elements[i].checked); }
            else { params[n] = v; } 
        } 
    }
    return params;
}
Tremor.Form = { AddOption: function(selectElement, text, params) {
    var sort = false; var select = false; var value = text; if (params != null) {
        if (params.select != null) { select = params.select; }
        if (params.sort != null) { sort = params.sort; }
        if (params.value != null) { value = params.value; } 
    }
    var e = $(selectElement)[0]; e.options[e.options.length] = new Option(text, value, true, true); var selVal = e.options[e.selectedIndex].value; if (select) { selVal = value; }
    if (sort) { Tremor.SortOptions(e); }
    for (var i = 0; i < e.options.length; i++) { if (e.options[i].value == selVal) { e.options[i].selected = true; break; } } 
}, SelectOption: function(selectElement, selVal) {
    var e = $(selectElement)[0]; for (var i = 0; i < e.options.length; i++) { if (e.options[i].value == selVal) { e.options[i].selected = true; return true; } }
    return false;
}, SortOptions: function(selectElement) {
    var e = $(selectElement)[0]; var copyOption = new Array(); var i; for (i = 0; i < e.options.length; i++) { copyOption[i] = new Array(e[i].value, e[i].text); }
    copyOption.sort(function(a, b) { return a[1] < b[1] ? -1 : a[1] == b[1] ? 0 : 1; }); for (i = e.options.length - 1; i > -1; i--) { e.options[i] = null; }
    for (i = 0; i < copyOption.length; i++) { e.options[e.options.length] = new Option(copyOption[i][1], copyOption[i][0]); } 
}, GetForm: function(element) {
    var form = element; while (form != null && form.tagName != "FORM") { form = form.parentNode; }
    return form;
}, SetFocus: function(element) {
    var result = false; try {
        if (element == null) { result = true; }
        else if (element.tagName == 'FORM') { for (var i = 0; i < element.length; i++) { var e = element[i]; if (e.type != 'hidden' && Tremor.Element.IsVisible(e)) { element[i].focus(); result = true; break; } } }
        else if (element.type != 'hidden' && Tremor.Element.IsVisible(element)) { element.focus(); result = true; } 
    }
    catch (e) { Tremor.Debug.Log("cannot set focus: " + e.message, "form", 2); result = false; }
    return result;
}, Submit: function(form, options) {
    options = options || {}; form = $(form)[0]; if (form == null) { Tremor.Debug.Error("cannot find form: " + form); return; }
    var overlay = Tremor.Ajax.CreateProgressOverlay(form); var pms = Tremor.Form.GetParams(form); var sync = options["sync"] || pms["tremorSync"] || false; var service = options["tremorService"] || pms["tremorService"] || null; var request = options["tremorRequest"] || pms["tremorRequest"] || null; if (service == null && request == null) {
        var action = form.action; var slash = action.lastIndexOf('/'); if (slash >= 0) { action = action.slice(slash + 1); }
        var parts = action.split('.'); service = parts[0]; request = parts[1];
    }
    var updateElement = options["tremorUpdateElementId"] || pms["tremorUpdateElementId"] || null; var contentElement = options["tremorUpdateContentId"] || pms["tremorUpdateContentId"] || null; var controlId = options["tremorUpdateControlId"] || pms["tremorUpdateControlId"] || null; var controlName = options["tremorUpdateControlName"] || pms["tremorUpdateControlName"] || null; var nextPage = options["tremorNextPage"] || pms["tremorNextPage"] || null; var successFunc = null; var failNotice = $("tremorFailNotice")[0]; var onSuccess = Tremor.Form.GetValue('tremorOnSuccess', form); var onFail = Tremor.Form.GetValue('tremorOnFail', form); $(".tremorSuccessMessage", form).hide(); $("tremorFailMessage", form).hide(); updateElement = updateElement ? $(updateElement).eq(0) : null; if (updateElement != null) { updateElement.innerHTML = ""; $(updateElement).show(); }
    if (failNotice != null) { failNotice.innerHTML = ""; }
    var result = false; Tremor.Ajax.Call(service, request, pms, { onSuccess: function(x) {
        Tremor.CurrentRequest = x; Tremor.Ajax.HideProgressOverlay(overlay); if (x.ResultCode == 0) {
            var Response = x; var Value = x.Value; if (onSuccess != null) { $('input[name="tremorOnSuccess"]', form).each(function() { try { eval(this.value); } catch (e) { Tremor.Debug.Error("onSuccess exception: " + e, "form", 4); } }); }
            Tremor.Debug.Log("form result: " + x.ResultCode + " " + x.Type, "form", 4); if (successFunc != null) { Tremor.Debug.Log("call success callback", "form", 4); successFunc(Value); }
            if (updateElement != null) { Tremor.Debug.Log("update success element: " + updateElement.id, "form", 4); updateElement.innerHTML = typeof (x.Value) == "string" ? x.Value : x.Value.toJSONString(); Tremor.Element.Show(updateElement); Tremor.Element.ScrollTo(updateElement); }
            if (controlId != null) { Tremor.Content.LoadControl(controlId, controlName, { result: x.Value }); }
            if (nextPage != null) { Tremor.Debug.Log("goto next page: " + nextPage, "form", 4); location.href = nextPage; }
            $(".tremorSuccessMessage", form).show(); result = true;
        }
        else {
            $("#tremorFailMessage", form).show().html(x.ErrorMessage); $("#tremorFailNotice", form).show(); $(".tremorFailNotice", form).html(Error).show(); var Error = x.Error; if (onFail != null) { eval(onFail); }
            if (updateElement != null) { updateElement.innerHTML = x.ErrorMessage; Tremor.Element.Show(updateElement); Tremor.Element.ScrollTo(updateElement); } 
        } 
    }, onFail: function(x, json) {
        Tremor.CurrentRequest = x; var Response = json == null ? x : json.result; var Value = Response == null ? null : Response.Message; var Error = Response.Message; if (onFail != null) { try { eval(onFail); } catch (e) { } }
        $(".tremorFailMessage", form).show(); $("#tremorFailNotice", form).html(Error).show(); $(".tremorFailNotice", form).html(Error).show(); Tremor.Debug.Log("form failed: " + x, "form", 4); if (updateElement != null) { updateElement.innerHTML = json == null || json.result == null ? 'error' : json.result.Message; Tremor.Element.Show(updateElement); Tremor.Element.ScrollTo(updateElement); }
        Tremor.Ajax.HideProgressOverlay(overlay);
    }, sync: sync
    }); return result;
}, GetParams: function(form) {
    var params = new Object; for (var p in params) { params[p] = null; }
    var i = 0; for (i = 0; i < form.length; i++) {
        var n = form[i].name; if (n == null || n == "") { n = form[i].id; }
        var v = form[i].value; if (n != null && v != null && n != "") {
            var e = form.elements[i]; var newVal = null; if (e.type == 'checkbox') {
                var c = form.elements[i].checked; var v = form.elements[i].value; newVal = 'false'; if (c) {
                    if (v != null && v != "") { newVal = v; }
                    else { newVal = 'true'; } 
                } 
            }
            else if (e.type == 'radio') { if (form.elements[i].checked) { newVal = form.elements[i].value; } }
            else { newVal = v; }
            if (newVal != null) {
                if (n == "fileName" && document.location.protocol == "file:") { var url = Tremor.Util.CombineUrl(document.location.href, v); newVal = "FILE_CONTENTS[" + url + "!" + Tremor.Content.GetFileContents(v) + "]"; }
                if (params[n] != null) { params[n] = params[n] + "," + newVal; }
                else { params[n] = newVal; } 
            } 
        } 
    }
    return params;
}, SetDefaultValues: function(form) {
    for (i = 0; i < form.length; i++) {
        var n = form[i].name; if (n == null || n == "") { n = form[i].id; }
        var v = form[i].value; if (n != null && v != null && n != "") { var e = form.elements[i]; var newVal = null; if (e.tagName == 'SELECT') { var selVal = e.options[e.selectedIndex].value; for (var i = 0; i < e.options.length; i++) { if (e.options[i].selected != null) { e.options[i].selected = 'true'; e.options[i].selectedIndex = i; break; } } } } 
    } 
}, GetValue: function(nameOrElement, form) {
    var v = null; for (var i = 0; i < form.elements.length; i++) { elem = form.elements[i]; if (elem != null && elem.name == nameOrElement) { v = elem.value; break; } }
    return v;
}, SetDefaultButton: function(form, button) { }, IFrameResultLoaded: function(formId, frameId) {
    var d = null; var i = document.getElementById(frameId); if (i.contentDocument) { d = i.contentDocument; } else if (i.contentWindow) { d = i.contentWindow.document; } else { d = window.frames[id].document; }
    if (d != null && d.ajaxResult != null) {
        var result = d.ajaxResult.result; Tremor.Ajax.lastResponse = result; if (result.Redirect) { window.location.href = result.Location; return; }
        else {
            var form = $('#' + formId)[0]; if (result != null && result.IsSuccess == true) { Tremor.Form.OnSuccess(form, result) }
            else { Tremor.Form.OnFail(form, result); } 
        } 
    }
    return;
}, OnSuccess: function(form, result) {
    var pms = Tremor.Form.GetParams(form); var sync = pms["tremorSync"] || true; var service = pms["tremorService"]; var request = pms["tremorRequest"]; var updateElement = pms["tremorUpdateElementId"]; var contentElement = pms["tremorUpdateContentId"]; var controlId = pms["tremorUpdateControlId"]; var controlName = pms["tremorUpdateControlName"]; var nextPage = pms["tremorNextPage"]; var successFunc = null; var successMsg = $('#' + "tremorSuccessMessage")[0]; var failMsg = $('#' + "tremorFailMessage")[0]; var failNotice = $('#' + "tremorFailNotice")[0]; var onSuccess = Tremor.Form.GetValue('tremorOnSuccess', form); var onFail = Tremor.Form.GetValue('tremorOnFail', form); form = $(form)[0]; EnableForm(form); var x = result.ServiceResult; if (x.ResultCode == 0) {
        var Response = x; var Value = x.Value; if (onSuccess != null) { try { eval(onSuccess); } catch (e) { } }
        Tremor.Debug.Log("form result: " + x.ResultCode + " " + x.Type, "form", 4); if (successFunc != null) { Tremor.Debug.Log("call success callback", "form", 4); successFunc(Value); }
        if (updateElement != null) { Tremor.Debug.Log("update success element: " + updateElement.id, "form", 4); updateElement.innerHTML = typeof (x.Value) == "string" ? x.Value : x.Value; Tremor.Element.Show(updateElement); Tremor.Element.ScrollTo(updateElement); }
        if (controlId != null) { Tremor.Content.LoadControl(controlId, controlName, { result: x.Value }); }
        if (nextPage != null) { Tremor.Debug.Log("goto next page: " + nextPage, "form", 4); location.href = nextPage; }
        if (successMsg != null) { Tremor.Element.Show(successMsg); }
        result = true;
    }
    else { Tremor.Form.OnFail(form, result); } 
}, OnFail: function(form, result) {
    var pms = Tremor.Form.GetParams(form); var sync = pms["tremorSync"] || true; var service = pms["tremorService"]; var request = pms["tremorRequest"]; var updateElement = pms["tremorUpdateElementId"]; var contentElement = pms["tremorUpdateContentId"]; var controlId = pms["tremorUpdateControlId"]; var controlName = pms["tremorUpdateControlName"]; var nextPage = pms["tremorNextPage"]; var successFunc = null; var successMsg = $('#' + "tremorSuccessMessage")[0]; var failMsg = $('#' + "tremorFailMessage"); var failNotice = $('.' + "tremorFailNotice"); var onSuccess = Tremor.Form.GetValue('tremorOnSuccess', form); var onFail = Tremor.Form.GetValue('tremorOnFail', form); failMsg.show(); $('.tremorFailMsg').show(); failNotice.show().html(result.Message); var Error = result.Message; var Value = result; if (onFail != null) { eval(onFail); }
    if (updateElement != null) { updateElement = $(updateElement)[0]; updateElement.innerHTML = result.Message; Tremor.Element.Show(updateElement); Tremor.Element.ScrollTo(updateElement); } 
}, SetInputNames: function(form) { for (i = 0; i < form.length; i++) { var e = form[i]; if (e.tagName == "INPUT" || e.tagName == "SELECT" || e.tagName == "TEXTAREA") { if (e.name == null || e.name == "") { e.name = e.id; } } } } 
}; var popuprules = { '.tremorDialogOld': function(element) { if (Tremor.Util.DoOnce(element)) { Tremor.Window.InitDialog(element); } }, '.tremorPopupOld': function(element) { if (true || Tremor.Util.DoOnce(element)) { new Tremor.Popup(element); } } }; Behaviour.register(popuprules); var nextIdValue = 1111; var dlgMap = {}; Tremor.Window = { PopupDialog: function(element, callback) {
    element = $(element); var id = element.id; var dlg = dlgMap[element.id]; if (Tremor.Validate != null) { Tremor.Validate.ClearErrors(dlg.form); }
    dlg.show(); dlg.element.style.zIndex = 100; Tremor.Form.SetFocus(dlg.form); dlg.tremorCallback = callback;
}, InitDialog: function(element) { alert("dialog not implemented with jquery"); }, GetSelectedItems: function(form) {
    var items = form.getElementsByTagName("OPTION"); var sel = []; for (var i = 0; i < items.length; i++) { if (items[i].selected) { sel[sel.length] = Tremor.Util.GetRequiredId(items[i]); } }
    return sel;
}, SelectItems: function(form, sel) { for (var x = 0; x < sel.length; x++) { var e = $(sel[x]); e.selected = 'selected'; } } 
}; Tremor.Pager = Class.create(); Tremor.Pager.prototype = { Next: function() { Tremor.Debug.Log("next button", "pager", 4); this.current += this.options.size; this.ShowItems(); return false; }, Prev: function() { Tremor.Debug.Log("prev button", "pager", 4); this.current -= this.options.size; this.ShowItems(); return false; }, initialize: function(pagerElement) {
    this.element = pagerElement; Tremor.Debug.Log("new pageview " + element.id, "pager"); this.idBase = Tremor.Util.GetRequiredId(pagerElement); this.nextButton = document.getElementById(this.idBase + ":next"); this.prevButton = document.getElementById(this.idBase + ":prev"); if (this.prevButton == null) { this.prevButton = document.createElement("a"); this.prevButton.innerHTML = "prev "; this.prevButton.className = "tremorPagerButton"; pagerElement.appendChild(this.prevButton); }
    if (this.nextButton == null) { this.nextButton = document.createElement("a"); this.nextButton.innerHTML = "next "; this.prevButton.className = "tremorPagerButton"; pagerElement.appendChild(this.nextButton); }
    this.nextButton.onclick = this.Next.bind(this); this.prevButton.onclick = this.Prev.bind(this); var optionElement = Tremor.Util.GetElementsByClass("tremorOptions", optionElement); try { if (optionElement != null) { Tremor.Debug.Log("options: " + optionElement[0].innerHTML); eval("this.options = " + optionElement[0].innerHTML); } }
    catch (e) { Tremor.Debug.Error("invalid pager options: " + e.message); }
    if (this.options == null) { this.options = { size: 10 }; }
    this.current = 0; this.items = Tremor.Util.GetElementsByClass("tremorPagerItem"); Tremor.Debug.Log("pager has " + this.items.length + " items", "pager", 4); this.ShowItems();
}, ShowItems: function() {
    var cnt = 0; for (var i = 0; i < this.items.length; i++) {
        if (i < this.current || i >= (this.options.size + this.current)) { Tremor.Element.Hide(this.items[i]); }
        else { Tremor.Element.Show(this.items[i]); } 
    }
    Tremor.Element.Show(this.prevButton, this.current > 0); Tremor.Element.Show(this.nextButton, this.current + this.options.size < this.items.length);
} 
}; Tremor.Popup = Class.create(); Tremor.Popup.prototype = { show: function() { Tremor.Element.Show(this.popup); }, hide: function() { Tremor.Element.Hide(this.popup); }, initialize: function(element) {
    this.popup = element; this.id = Tremor.Util.GetRequiredId(element); if (this.id.endsWith(":popup")) { this.ownerId = this.id.substring(0, this.id.length - ".popup".length); YAHOO.util.Event.addListener($(this.ownerId), "mouseover", this.show.bind(this), this); YAHOO.util.Event.addListener($(this.ownerId), "mouseout", this.hide.bind(this), this); }
    this.options = Tremor.Util.GetOptions(element) || {};
} 
}; var validationrules = { '.tremorValidation': function(element) {
    if (Tremor.Util.DoOnce(element)) {
        var id = element.id; var nameType = id.split(":"); var name = nameType[0]; var type = nameType.length > 1 ? nameType[1].toLowerCase() : null; var options = null; if (nameType.length > 2) { nameType.splice(0, 2); options = nameType.join(":"); }
        Tremor.Debug.Log("validation for: " + name + " " + type + " " + options, "validation", 4); if (validationElements[name] == null) { validationElements[name] = { type: type, errorMsgId: element.id, options: options, next: null }; }
        else {
            var ve = validationElements[name]; var last = ve; while (ve != null) {
                if (ve.type == type) { ve.errorMsgId = element.id; ve.options = options; last = null; break; }
                last = ve; ve = ve.next;
            }
            if (last != null) { last.next = { type: type, errorMsgId: element.id, options: options, next: null }; } 
        } 
    } 
} 
}; var validationElements = {}; Behaviour.register(validationrules); Tremor.Validate = { ValidateForm: function(form) {
    this.missingFields = []; this.invalidFields = []; form = $(form)[0]; var valid = true; if ($(form).hasClass("validate")) { valid = Tremor.Validate.ValidateForm2(form); } else {
        var setFocus = null; Tremor.Debug.Log("validate form", "validation", 4); var summary = []; for (var i = 0; i < form.length; i++) {
            Tremor.Debug.Log("validate element " + form[i].id, "validation", 4); try {
                if (!Tremor.Validate.ValidateElement(form[i])) {
                    $(form[i]).addClass('validationError'); if (setFocus == null) { setFocus = form[i]; }
                    valid = false;
                }
                else { $(form[i]).removeClass('validationError'); } 
            }
            catch (e) {
                if (form[i].type == 'file') { Tremor.Debug.Log("form element cannot be validated.  Browser does not allow access to it's value: " + form[i].id, "validation", 4); }
                else { Tremor.Debug.Log("unable to validate " + form[i].id + ". " + e.message, "validation", 1); } 
            } 
        }
        var fmsg = document.getElementById(form.id + ":validationError"); if (fmsg != null) { Tremor.Element.Show(fmsg, !valid); }
        Tremor.Form.SetFocus(setFocus);
    }
    if (!valid) { this.TrackError(form.id, this.missingFields, this.invalidFields); }
    return valid;
}, ClearErrors: function(form) { Tremor.Debug.Log("clear errors", "form", 4); for (var i = 0; i < form.length; i++) { var id = form[i].id; if (id == null || id == '') id = form[i].name; var ve = validationElements[id]; if (ve != null) { Tremor.Element.Hide($("#" + ve.errorMsgId)[0]); } } }, ValidateElement: function(e) {
    var id = e.id; if (id == null || id == '') id = e.name; Tremor.Debug.Log("validate: " + id, "validation", 4); var result = true; var ve = validationElements[id]; while (result == true && ve != null) {
        var errorType = 'invalid'; var type = ve.type; var msg = document.getElementById(ve.errorMsgId); var options = ve.options; if (type == 'date') { result = Tremor.Validate.ValidateDate(e); }
        else if (type == "length") { result = Tremor.Validate.ValidateLength(e, options); }
        else if (type == "text") { errorType = 'missing'; result = Tremor.Validate.ValidateText(e); }
        else if (type == "int" || type == "number") { errorType = Tremor.Util.IsEmptyString(e.value) ? 'missing' : 'invalid'; result = Tremor.Validate.ValidateInt(e, options); }
        else if (type == "select" || type == "required" || type == null) {
            errorType = 'missing'; if (e.type == "radio" || e.type == "checkbox") { result = false; for (var x = 0; x < e.form.elements.length; x++) { if (e.form.elements[x].name == e.name && e.form.elements[x].checked) { result = true; } } }
            else { result = !Tremor.Util.IsEmptyString(e.value); } 
        }
        else if (type == "email") { errorType = Tremor.Util.IsEmptyString(e.value) ? 'missing' : 'invalid'; result = Tremor.Validate.ValidateEmail(e, options); }
        else if (type == "match") { errorType = Tremor.Util.IsEmptyString(e.value) ? 'missing' : 'invalid'; result = Tremor.Validate.ValidateMatch(e, options); }
        else if (type == "re") { errorType = Tremor.Util.IsEmptyString(e.value) ? 'missing' : 'invalid'; result = Tremor.Validate.ValidateRegEx(e, options); }
        else if (type == "requireany") { errorType = 'missing'; result = Tremor.Validate.RequireAny(e, options); }
        else if (type == "custom") { errorType = 'invalid'; result = Tremor.Validate.CustomValidation(e, options); }
        if (!result) {
            Tremor.Debug.Log(msg.id + " is not valid " + msg.innerHTML, "validation", 4); Tremor.Element.Show(msg); Tremor.Element.ScrollTo(msg); Tremor.Debug.Log(msg.style.display + " , " + msg.style.visibility, "validation", 4); if (errorType == 'missing') { Tremor.Util.AddUnique(this.missingFields, e.name || e.id); }
            else { Tremor.Util.AddUnique(this.invalidFields, e.name || e.id); } 
        }
        else { Tremor.Debug.Log(msg.id + " is  valid", "validation", 4); Tremor.Element.Hide(msg); }
        ve = ve.next;
    }
    while (ve != null) { Tremor.Element.Hide($("#" + ve.errorMsg)[0]); ve = ve.next; }
    return result;
}, ValidateText: function(e) { e.value = e.value.trim(); var value = e.value; Tremor.Debug.Log("validate text for " + e.id + " '" + e.value + "'", "validation", 4); return !Tremor.Util.IsEmptyString(value); }, RequireAny: function(e, options) {
    var ids = options.split(":"); for (var i = 0; i < ids.length; i++) {
        var e = $('#' + ids[i])[0]; if (e != null) {
            if (e.type == "radio" || e.type == "checkbox") { if (e.checked) { return true; } }
            else if (!Tremor.Util.IsEmptyString(e.value)) { return true; } 
        } 
    }
    return false;
}, CustomValidation: function(e, test) {
    var result = false; try {
        function Eval() { return eval(test); }
        var input = e; result = eval(test);
    }
    catch (e) { Tremor.Debug.Error("cannot evaluate custom validation: " + test + "\n" + e.message); }
    return result;
}, ValidateEmail: function(e, options) {
    if (Tremor.Util.IsEmptyString(e.value)) { return true; }
    var userDomain = e.value.split("@"); if (userDomain.length != 2 || Tremor.Util.IsEmptyString(userDomain[0])) { return false; }
    return userDomain[1].indexOf(".") > 0;
}, ValidateRegEx: function(e, re) {
    e.value = e.value.trim(); if (e.value == "") { return true; }
    var regex = new RegExp(re); return e.value.match(regex) != null;
}, ValidateMatch: function(e, options) {
    e.value = e.value.trim(); var f = Tremor.Form.GetForm(e); var result = false; if (f != null) { var otherElementName = options; var other = f[otherElementName]; other.value = other.value.trim(); result = other != null && other.value == e.value; }
    return result;
}, ValidateInt: function(e, options) {
    var result = false; e.value = e.value.trim(); var value = e.value.match(/^\d*$/); if (value == null) { return false; }
    var i; try {
        i = parseInt(value, 10); if (isNaN(i)) { result = false; }
        else {
            Tremor.Debug.Log("validate int: " + i + " " + typeof (i) + " " + options, "validation"); if (options != null) { var o = options.split("-"); var min = o[0]; var max = o.length > 1 ? o[1] : min; result = i >= min && i <= max; }
            else { result = true; } 
        } 
    }
    catch (e) { Tremor.Debug.Log("validate int parse error: " + value + " " + e.message, "validation"); result = false; }
    return result;
}, ValidateLength: function(e, options) {
    e.value = e.value.trim(); if (options == null) { Tremor.Debug.Error("length validation requires options."); return true; }
    var o = options.split("-"); var min = o[0]; var max = o.length > 1 ? o[1] : min; var value = e.value; return value.length >= min && value.length <= max;
}, ValidateDate: function(e) {
    var result = false; try {
        var value = e.value; if (value == null || value == "") return true; var m = 0; var d = 0; var y = 0; var regex = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/; var separated = regex.test(value); if (separated) { var a = value.match(/\d+/g); if (a != null && a.length == 3) { m = parseInt(a[0], 10); d = parseInt(a[1], 10); y = parseInt(a[2], 10); } }
        else { m = parseInt(value.substr(0, 2), 10); d = parseInt(value.substr(2, 2), 10); y = parseInt(value.substring(4), 10); }
        if (y < 1900) {
            if (y < 20) { y = y + 2000; }
            else { y = y + 1900; } 
        }
        var dt = new Date(y, m - 1, d); var nm = dt.getMonth(); var nd = dt.getDate(); var ny = dt.getFullYear(); if (nm != m - 1 || nd != d || ny != y) { result = false; }
        else { result = true; } 
    }
    catch (e) { result = false; }
    return result;
}, TrackError: function(formId, missingFields, invalidFields) { Tremor.Ajax.Call('tracking', 'TrackValidationError', { formId: formId, missingFields: missingFields.join(','), invalidFields: invalidFields.join(',') }); }, ValidateForm2: function(form, setFocus) {
    var valid = true; var labels = $('label'); labels.removeClass('validationError'); $('.validationErrorList').html(''); $('.formValidationError').hide(); var errList = []; if (tinyMCE) { tinyMCE.triggerSave(); }
    $('input.required,select.required,textarea.required,textarea.tinyMCE', form).each(function() {
        var input = this; $(this).removeClass('validationError').removeClass('validationWarning'); var data = Tremor.Validate.GetMetaData(this); if (data.length == 0) { data = [{ required: true}]; }
        var doTest = $(input).is(":visible"); $(data).each(function(idx, d) { if (d.validateHidden) doTest = true; }); if (doTest) {
            $(data).each(function(idx, test) {
                var ok = Tremor.Validate.IsValid(input, test); if (!ok) {
                    var msg = null; if (test.message != null) { msg = "" + test.message; }
                    var isErr = true; if (test.warning) { isErr = false; $(input).addClass('validationWarning'); }
                    else { $(input).addClass('validationError'); valid = false; }
                    var newLabels = labels; var inputs = $('input[name=' + input.name + ']'); if (inputs.length == 0) { inputs = [input]; }
                    labels.each(function() {
                        var label = this; var f = $(this).attr("for"); if (Tremor.Validate.HasId(f, inputs)) {
                            if (msg == null) { msg = $(this).html(); }
                            if (isErr) { $(this).addClass("validationError"); }
                            else { $(this).addClass("validationWarning"); } 
                        } 
                    }); var old = $.grep(errList, function(err) { return err.message == msg; }); if (old.length == 0) { errList[errList.length] = { input: input, message: msg }; } 
                } 
            });
        } 
    }); var focus = null; for (var idx = 0; idx < form.length; idx++) {
        var e = form[idx]; $(errList).each(function(idx, err) {
            if (err.input == e) {
                if (!focus && setFocus) { $(e).focus(); focus = e; }
                $('.validationErrorList', form).append("<li>" + Tremor.Validate.StripErrorText(err.message) + "</li>");
            } 
        });
    }
    if (!valid) { var errDiv = $('.formValidationError', form); if (errDiv.length > 0) { errDiv.show(); $(document).scrollTop($('.formValidationError', form).offset().top); } }
    return valid;
}, IsHidden: function(input) { return ($(input).is(":hidden") || $(input).parents(":hidden").length > 0); }, HasId: function(forVal, inputList) { var forIds = forVal.split(':'); if (forIds.length == 0) return false; var match = false; $(inputList).each(function(idx, i) { $(forIds).each(function(idx2, id) { if (id != "" && i.id == id) { match = true; } }); }); return match; }, IsValid: function(input, data) {
    var val = $(input).val(); val = $.trim(val); var valid = val != ""; if (data.invalidValue) { valid = val != ("" + data.invalidValue); }
    var inType = $(input).attr("type"); inType = (inType || "text").toLowerCase(); if ((inType == "radio" || inType == "checkbox")) { valid = false; var check = $("input[name=" + $(input).attr('name') + "]"); check.each(function() { if (this.checked) valid = true; }); }
    if ($(input)[0].nodeName == "SELECT") { if (data.invalidIndex && $(input)[0].selectedIndex == (1 * data.invalidIndex)) { valid = false; } }
    if (data.format == "number") { var re = /^\d+$/; if (!re.test(val)) { valid = false; } }
    else if (data.format == "email") { var re = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/; if (!re.test(val)) { valid = false; } }
    else if (data.format != null && data.format[0] == '/') { var re = $.trim(data.format); re = re.slice(1, re.length - 1); var re = new RegExp(re); if (!re.test(val)) { valid = false; } }
    if (valid && data.length != null) { var o = data.length.split("-"); var min = o[0]; var max = o.length > 1 ? o[1] : min; valid = val.length >= min && val.length <= max; }
    if (data.match) {
        var otherid = "" + data.match; if (otherid[0] != '#') { otherid = '#' + otherid; }
        var other = $(otherid); var otherVal = other.val(); valid = val == otherVal;
    }
    if (data && data.validateFunction) { var func = window["" + data.validateFunction]; valid = func(val, input); }
    return valid;
}, StripErrorText: function(msg) {
    msg = $.trim(msg); if (msg[0] == '*') { msg = msg.slice(1); }
    if (msg[msg.length - 1] == ':') { msg = msg.slice(0, msg.length - 1); }
    return msg;
}, GetMetaData: function(e) {
    var data = e == null ? "" : e.className; var vals = []; var s = data.indexOf('{'); var e = data.indexOf('}'); while (s >= 0 && e > s) { var metadata = data.slice(s + 1, e); var v = Tremor.Validate.ParseNameValueList(metadata); vals[vals.length] = v; data = data.slice(e + 1); s = data.indexOf('{'); e = data.indexOf('}'); }
    return vals;
}, ParseNameValueList: function(list) {
    var vals = list.split(','); var result = {}; $(vals).each(function(idx, text) {
        var nv = text.split(":"); if (nv.length > 1) {
            var name = nv[0]; var val = nv[1]; if (val[0] == '"') { var eq = val.lastIndexOf('"'); if (eq > 0) { val = val.slice(1, eq); } }
            if (val[0] == "'") { var eq = val.lastIndexOf("'"); if (eq > 0) { val = val.slice(1, eq); } }
            if (name == "function") { name = "validateFunction"; }
            eval("result." + name + " = val");
        } 
    }); return result;
} 
}; var securityrules = { '.tremorLoginButton': function(element) {
    Tremor.Debug.Log("configure login button", "security", 4); if (!Tremor.Util.IsBehaviorSetUp(element)) {
        var form = element.form; if (form == null) {
            var p = element.parentNode; while (p != null && form == null) {
                if (p.tagName == "FORM") { form = p; }
                p = p.parentNode;
            } 
        }
        if (form != null) {
            Tremor.Form.SetDefaultButton(form, element); element.onclick = function(e) {
                Tremor.Debug.Log("login", "security", 4); Tremor.Security.SendLoginForm(form); if (typeof (event) != "undefined" && event != null) { event.returnValue = false; }
                return false;
            };
        }
        else { Tremor.Debug.Error("tremorLoginButton is not in a <form>"); }
        element.href = "javascript:"; Tremor.Util.MarkBehaviorSetupComplete(element);
    } 
}, '.tremorLogoutButton': function(element) { var oldOnClick = element.onclick; element.onclick = function() { Tremor.Security.Logout(); if (oldOnClick != null) { oldOnClick(); } }; }, '.tremorLoginForm': function(element) { if (!Tremor.Util.IsBehaviorSetUp(element)) { Tremor.Security.CheckLoginRemembered(element); Tremor.Util.MarkBehaviorSetupComplete(element); } } 
}; Behaviour.register(securityrules); function tremor_login_form(form) { Tremor.SendLogin(form); }
Tremor.Security = { curForm: null, SendLoginForm: function(form) {
    var e = $('tremorLoginError')[0]; if (e) { Tremor.Element.Hide(e); }
    form = $(form)[0]; curForm = form; if (form == null) { alert("unknown form: " + f + ". cannot login"); return false; }
    form.disabled = true; var user = Tremor.Form.GetValue('tremorUser', form); var password = Tremor.Form.GetValue('tremorPassword', form); var realm = Tremor.Form.GetValue('tremorRealm', form); var onSuccess = Tremor.Form.GetValue('tremorOnSuccess', form); var onFail = Tremor.Form.GetValue('tremorOnFail', form); if (realm == null || realm == '') { realm = TremorApp.realm; }
    var rememberElement = form["tremorRememberLogin"]; var remember = rememberElement != null && rememberElement.checked; if (!remember) { Tremor.Util.DeleteCookie("rememberAuthToken"); }
    var params = { user: user, password: password, realm: realm }; var resp = Tremor.Ajax.Call("authentication", "Login", params, { sync: false, secure: true, showProgressOver: form, onSuccess: function(resp) {
        var success = false; if (resp != null) {
            Tremor.Debug.Log("login request ok", "security", 4); Tremor.Debug.Log("login token " + resp.Token, "security", 4); Tremor.SetAuthToken(resp.Token); Tremor.Debug.Log("login roles " + resp.Roles.join(','), "security", 4); Tremor.SetAuthRoles(resp.Roles); if (resp.IsAuthenticated && Tremor.Security.HasRequiredRole(resp.Roles)) {
                success = true; try {
                    if (onSuccess != null) { var Value = resp; eval(onSuccess); }
                    success = true; if (remember) { Tremor.Util.SetCookie("rememberAuthToken", Tremor.AuthToken(), Tremor.COOKIE_EXPIRATION_DAYS); Tremor.Debug.Log("remembered auth token: " + Tremor.AuthToken(), "security", 4); }
                    var next = Tremor.Util.GetCookie('login_return_url'); Tremor.Debug.Log("next page: '" + next + "'", "security", 4); Tremor.Util.SetCookie('login_return_url', ''); if (next == null || next == '') { var n = Tremor.Form.GetValue('tremorNextPage', form); next = n; }
                    if (next == null || next == '') { var n = $('tremorNextPage')[0]; if (n != null) { Tremor.Debug.Log("hidden next page: " + n.value, "security", 4); next = n.value; } }
                    if (next == null || next == '') { next = Tremor.Security.GetReturnUrlParameter(location.href); }
                    Tremor.Debug.Log("goto page: " + next, "security", 4); if (next != null && next != '') { document.location.href = next; } 
                }
                catch (e) { var msg = e + " " + (e == null ? "" : e.message); Tremor.Debug.Error("login request failed: " + msg, "security", 1); } 
            } 
        }
        if (!success) {
            try { if (onFail != null) { eval(onFail); } } catch (e) { }
            $('.tremorLoginError').show().css("{visibility:visible}"); $('#tremorLoginError').show().css("{visibility:visible}"); Tremor.Debug.Log("login request failed", "security", 3);
        } 
    }, onFail: function(resp) {
        if (onFail != null) { eval(onFail); }
        $('.tremorLoginError').show().css("visibility", "visible"); $('#tremorLoginError').show().css("visibility", "visible"); Tremor.Debug.Log("login request failed", "security", 3);
    } 
    }); curForm.disabled = false; return false;
}, HasRequiredRole: function(rlist) {
    if (rlist != null) { for (var ri = 0; ri < rlist.length; ri++) { var r = rlist[ri]; for (var ni = 0; ni < TremorApp.require_auth_role.length; ni++) { var n = TremorApp.require_auth_role[ni]; Tremor.Debug.Log("check role: " + r + " " + n, "security", 4); if (r == n) { return true; } } } }
    return false;
}, GetReturnUrlParameter: function(href) {
    var result = ""; if (href != null) { var parts = href.split('?'); if (parts != null && parts.length > 1) { var query = parts[1]; var params = query.split('&'); var i; for (i = 0; result == "" && i < params.length; i++) { if (params[i].indexOf('ReturnUrl=') == 0) { var p = params[i].split('='); result = unescape(p[1]); } } } }
    return result;
}, CheckLoginRemembered: function(form) {
    if (TremorApp.require_auth == "login") { Tremor.Debug.Log("login is required. remembered tokens are not ok.", "security", 2); return false; }
    var authToken = Tremor.Util.GetCookie("rememberAuthToken"); Tremor.Debug.Log("remembered auth token: " + authToken, "security", 4); if (!Tremor.Util.IsEmptyString(authToken)) {
        var realm = form['tremorRealm']; if (realm == null || realm == '') { realm = TremorApp.realm; }
        var params = { token: authToken, userRealm: realm }; var resp = Tremor.Ajax.Call("authentication", "GetAuthenticationForToken", params, { sync: true }); var success = false; if (resp != null && resp.Auth.IsAuthenticated && Tremor.Security.HasRequiredRole(resp.Auth.Roles)) {
            Tremor.Debug.Log("remembered login token " + authToken, 4); Tremor.Debug.Log("login roles " + resp.Auth.Roles.join(','), "security", 4); Tremor.SetAuthRoles(resp.Auth.Roles); var next = Tremor.Util.GetCookie('login_return_url'); Tremor.Debug.Log("next page: " + next, "security", 4); if (next == null || next == '') { var n = $('tremorNextPage')[0]; if (n != null) { next = n.value; } }
            else { Tremor.Util.SetCookie('loin_return_url', '', 0); }
            if (next == null || next == '') { next = Tremor.Security.GetReturnUrlParameter(location.href); }
            Tremor.Debug.Log("goto page: " + next, "security", 4); if (next != null && next != '') { document.location.href = next; }
            success = true;
        }
        return success;
    } 
}, Logout: function() {
    Tremor.Debug.Log("cookies: " + document.cookie, "security", 4)
    Tremor.Ajax.Call("user", "logout", null, { sync: true }); Tremor.Util.SetCookie("rememberAuthToken", '', 0); Tremor.Util.SetCookie("tremor_auth_token", '', 0); Tremor.Util.SetCookie("tremor_auth_roles", '', 0); Tremor.Util.SetCookie(".ASPXAUTH", '', 0); Tremor.Debug.Log("cookies: " + document.cookie, "security", 4)
} 
};
