/**
 *
 *  (c) 2004-2005 Copyright Basis Applied Technology
 *  CONFIDENTIAL INFORMATION
 *  All rights are reserved. Copying or other reproduction of
 *  this program except for archival purposes is prohibited
 *  without the prior written consent of Basis Applied Technology
 *
 *  Basis Applied Technology
 *  Gibsons, BC
 *  604.886.0721
 */

/* array extensions -------------------------------------------------------- */

Array.prototype.indexOf = function(v){for(var i=this.length;i>-1;i--)if((typeof this[i]!='undefined') && (this[i] == v))return i; return -1};
Array.prototype.contains = function(v){return this.indexOf(v) > -1};
Array.prototype.deleteValue = function(v){
  for(var i=this.length-1; i>=0; i--)
    if(this[i] == v)this.deleteItem(i);
};
Array.prototype.deleteItem  = function(i){
  if(i<0||i>(this.length-1))return;
  if(i==(this.length-1))
  {this.length--; return;}
  for(var a=(i+1);a<this.length;a++){this[a-1]=this[a];}
  this.length--;
};
String.prototype.trim = function() {
  var s = this;
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  { s = s.substring(1,s.length); }
  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  { s = s.substring(0,s.length-1); }
  return s;
};
/* platform/browser sniffing  ---------------------------------------------- */
var app = {};

// browser types
app._bt    = ["Unknown","IExplore","Netscape","Mozilla","Chimera","Opera","Safari","Konqueror","Firefox"];
var btUnknown   = 0;
var btIExplore  = 1;
var btNetscape  = 2;
var btMozilla   = 3;
var btChimera   = 4;
var btOpera     = 5;
var btSafari    = 6;
var btKonqueror = 7;
var btFirefox   = 8;

// platform types
app._pt    = ["Unknown","Windows","Macintosh","Linux","Unix"];
var ptUnknown   = 0;
var ptWindows   = 1;
var ptMacintosh = 2;
var ptLinux     = 3;
var ptUnix      = 4;

app.browsersniff = function() {
    var i,n,hasX;
    var u      = navigator.userAgent.toUpperCase();
    var v      = navigator.vendor;
    app.platform = ptUnknown;
    app.browser  = btUnknown;
    app.major    = 0;
    app.minor    = 0;

    // find platform
    var t = navigator.platform.toUpperCase().substr(0,3);
    if(t=="WIN")app.platform = ptWindows;  else
    if(t=="MAC")app.platform = ptMacintosh;else
    if(t=="LIN")app.platform = ptLinux;    else
    if(t=="UNI")app.platform = ptUnix;
    // find browser
    if(typeof window.opera != "undefined")app.browser = btOpera;else // only opera has window.opera object
    if(u.indexOf("KONQUEROR")>0)app.browser = btKonqueror;      else
    if(document.all)            app.browser = btIExplore;       else // most likely IE
    if(u.indexOf("FIREFOX"  )>0)app.browser = btFirefox;        else
    if(u.indexOf("SAFARI"   )>0)app.browser = btSafari;         else
    if(typeof document.implementation != 'undefined' &&
       typeof document.implementation.createDocument != 'undefined')app.browser = btMozilla; else
    if(u.indexOf("CHIMERA"  )>0)app.browser = btChimera;        else
    if(u.indexOf("NETSCAPE" )>0)app.browser = btNetscape;       else
    if(u.indexOf("GECKO"    )>0)app.browser = btMozilla;
    // find version
    var r = new RegExp("[\(\)\/\;\,\:]", "g");
    var uu = u.replace(r," ").split(" ");
    for(i=uu.length-1;i>=0;i--){
      uu[i] = String(uu[i]);
      n    = parseFloat(uu[i]);
      hasX = new RegExp("[xX]+");
      if(uu[i].search(new RegExp("[xX]+")) > -1)uu.deleteItem(i);
      else if(isNaN(n))uu.deleteItem(i);
      else if(n > 19)uu.deleteItem(i);
      else uu[i] = n; // for sorting
    }
    uu.sort();
    if(uu.length > 0){
      i = uu.length-1; // use largest number
      if(app.browser == btMozilla || app.browser == btFirefox)i = 0; // use smallest number
      uu = (app.browser==btFirefox) ? u.substring(u.indexOf('FIREFOX/')+8).split(".") : String(uu[i]).split(".");
      app.major = parseInt(uu[0]);
      if(uu.length>1)
        app.minor = uu[1];
    }
    app.isGecko  = (app.browser == btMozilla || app.browser == btChimera || app.browser == btNetscape || app.browser == btSafari || app.browser == btFirefox);
    app.isKHTML  = (app.browser == btSafari || app.browser == btKonqueror);
    app.isIE     = (app.browser == btIExplore);
    app.isIEMac  = (app.platform == ptMacintosh && app.isIE);
    app.isIE5    = (app.isIE    && app.major == 5);
    app.isIE5Mac = (app.isIEMac && app.major == 5);
};
app.browsersniff();
delete app.browsersniff;
app.strict = function(){
  if(app.isIE5Mac)return true;
  var r = false;
  var d = document.doctype;
  r     = (document.compatMode=="CSS1Compat");
  if(d){
    if(d.systemId)
      r = d.systemId.indexOf("strict")>-1;
    else if(d.publicId)
      r = d.publicId.indexOf("transitional")>-1;
  }
  r     = (d&&d.name.indexOf(".dtd")>-1)?true:r;
  return r;
};
app.isStrict = app.strict();
app.needsBoxFix = (app.isIE5)||(app.isIE60 && !app.isStrict);
delete app.strict;

/* common utility stuff ---------------------------------------------------- */

app.clamp = function(_x,_min,_max){_x=Number(_x);if(_x<_min)_x=_min;if(_x>_max)_x=_max;return _x;}

app.inherit = function(o, p) {for(var a in p)o[a]=p[a];};

app.padString = function(s,n,p){
  s = String(s);
  while(s.length<n)s=p+s;
  return s;
};
app.createdate = function(d) {
    if(!d)d=new Date();
    return (d.getFullYear() + '-' + app.padString(d.getMonth()+1,2,'0') + '-' + app.padString(d.getDate(),2,'0') + ' ' + app.padString(d.getHours(),2,'0') + ':' + app.padString(d.getMinutes(),2,'0') + ':' + app.padString(d.getSeconds(),2,'0'));
};

app.addEvent = function(obj,evt,fn,capture)
{
  if(obj.addEventListener)
  {obj.addEventListener(evt,fn,capture);}
  else if(obj.attachEvent)
  {obj.attachEvent("on"+evt,fn);}
  else
  {obj["on"+evt] = fn;}
};
app.preventBubble = function(E){
  if(app.isIE){
    event.cancelBubble = true;
    event.returnValue  = false;
  }else{
    if(E.stopPropagation)E.stopPropagation();
    else E.preventBubble();
  }
};
app.removeEvent = function(obj,evt,fn,capture) {
  if(obj.removeEventListener)
  {obj.removeEventListener(evt,fn,capture);}
  else if(obj.detachEvent)
  {obj.detachEvent("on"+evt,fn);}
  else
  {obj["on"+evt] = null;}
};

var $ = function(s) { return document.getElementById(s); }
app.el = function(el) {
    return document.getElementById(el);
};

app.include = function(scriptURL) {
    if (app.isLoaded) {
        return app.loadScript(scriptURL, null, false);
    } else if (!app.scriptExists(scriptURL)) {
        app.__scripts.push(scriptURL);
        document.writeln('<script type="text\/javascript" src="'+scriptURL+'"><\/script>');
        return true;
    }
    return false;
};
app.loadScript = function(scriptURL, overwrite) {
    var exists = app.scriptExists(scriptURL);
    if (!exists || overwrite) {
        var result = app.xmlrpc.loadFile(scriptURL);
        if (!app.xmlrpc.fault(result,true)) {
            return app.applyScript(result, scriptURL, overwrite);
        }
    }
    return false;
};
app.scriptExists = function(scriptURL) {
    if (!app.__scripts) { app.__scripts = [];}

    if (app.__scripts.indexOf(scriptURL) != -1) {
        return true;
    }
    if (document.scripts) {
        for (var i=0;i<document.scripts.length;i++) {
            var src = unescape(document.scripts[i].src);
            if (src == scriptURL) {
                return true;
            }
        }
    }

    return false;
};
app.loggedin = function() {
    return BF_USERID != BF_VISITORID;
};
app.applyScript = function(sScript, scriptID, overwrite) {
    if (scriptID) {
        var exists = app.scriptExists(scriptID);
        if (!exists || overwrite) {
            if (!exists) {app.__scripts.push(scriptID);}
        } else {
            return false;
        }
    }
    var scriptNode  = document.createElement('script');
    scriptNode.type = 'text/javascript';
    scriptNode.text = sScript;
    document.getElementsByTagName("head")[0].appendChild(scriptNode);
    return true;
};

app.isNull     = function(n)  {return n==null || !String(n).length};
app.rInt       = function(n,d){return(app.isNull(n)||isNaN(n))?((app.isNull(d)||isNaN(d))?0:d):parseInt(n)};
app.rFloat     = function(n,d){return(app.isNull(n)||isNaN(n))?((app.isNull(d)||isNaN(d))?0:d):parseFloat(n)};
app.isFunction = function(a) { return typeof a == 'function';};
app.isInt      = function(x) {var y=parseInt(x); if(isNaN(y))return false;return x==y&&x.toString()==y.toString();}
app.isObject   = function (a) { return (a && typeof a == 'object') || app.isFunction(a); };
app.isArray    = function(a) { return app.isObject(a) && a.constructor == Array;};
app.isA        = function(e,t) { if (e && app.isArray(e.CLS_TYPE) && e.CLS_TYPE.indexOf(t)>-1) { return true; } return false; };
app.rVal       = function(s,d){return(app.isNull(s)?(app.isNull(d)?"":d):s)};                                 // return value if not nil else default
app.luid       = function()   {return "L"+new Date().getTime()+Math.floor(1000 * Math.random());};
app.isString   = function(s) {if(typeof s=='string')return true;if (!s===null&&typeof s=='object') {var c=s.constructor.toString().match(/string/i);return (c!=null);}return false;}
app.rString    = function(s,d) {return (app.isString(s) ? s : (app.isString(d) ? d : ""));}

app.boxValuesOut = function(s){
  if(app.isNull(s) || isNaN(parseInt(s)))return [0,0,0,0];
  var a=s.split(" ");
  for(var i=0;i<a.length;i++)a[i]=parseInt(a[i]);
  switch(a.length){
    case 1:a[1]=a[0];a[2]=a[0];a[3]=a[0];break;
    case 2:a[2]=a[0];a[3]=a[1];break;
    case 3:a[3]=a[1];break;
  }
  return a;
};

app.IFrameDoc = function(o) {
    if (typeof o == "string") o = app.el(o);
    var d;
    if(app.isIE5)d = o.document;
    else d = app.isIE?o.contentWindow.document:o.contentDocument;
    return d;
};

app.getTarget = function(E){return app.isGecko?E.target:event.srcElement};
app.findTarget = function(E,k){return app.findParent(app.getTarget(E),k)};
app.findParent = function(n,k){try{while(n){if(n.nodeName == k)return n;if(app.isA(n, k))return n;if(n == k)return n;n = n.parentNode;}return null;}finally{n = null;}};
app._noselect = function(E) { E = E || event; E.returnValue = false; return false; }
app._nullfunc = function(){;}
app.purevirtual = function(){alert("Illegal Pure Virtual Function Call!");}
app.disallowselect = function(el){el.onmousedown = app._noselect; el.onselectstart = app._noselect;}

app.scrollTop  = function(){return app.isIE?(app.isStrict?document.documentElement.scrollTop :document.body.scrollTop ):pageYOffset};
app.scrollLeft = function(){return app.isIE?(app.isStrict?document.documentElement.scrollLeft:document.body.scrollLeft):pageXOffset};
app.bodyWidth  = function(){return parseInt(app.isIE?(!app.isStrict?document.body.clientWidth: document.documentElement.clientWidth ):window.innerWidth)};
app.bodyHeight = function(){return parseInt(app.isIE?(!app.isStrict?document.body.clientHeight:document.documentElement.clientHeight):window.innerHeight)};


if(app.isGecko||app.isIE5Mac)app.include(BF_SCRIPTDIR+"mozillaext.js");

app.getNodeIndex = function(n){
  if(!n)return null;
  r = 0;
  var t = n.previousSibling;
  while(t){
    r++;
    t = t.previousSibling;
  }
  return r;
};
app.transferElm = function(e,t){
  var temp = e.parentNode ? e.parentNode.removeChild(e) : e;
  t.insertAdjacentElement("beforeEnd",temp);
};
app.insertElm = function(e,t,w){
  if(!e)return;
  e.moveTo();
  e.setPosition("relative");
  if(!t)return;
  if(app.isIE5Mac){
    t.insertAdjacentElement = insertAdj_El;
    t.insert__Adj           = insert__Adj;
  }
  t.insertAdjacentElement(app.rVal(w,"afterBegin"),e);
};
app.getTrueOffset = function(e){
  var x=0; var y=0;
  if(!e)return [x,y];
  while(e && (e.style.position=="relative" || e.style.position=="absolute")){
    x+=app.rInt(e.offsetLeft);
    y+=app.rInt(e.offsetTop);
    e=e.parentNode;
  }
  return [x,y];
};
app.getParams = function() {
  var idx = location.href.indexOf('?');
  var params = new Object();
  if (idx != -1) {
    var pairs = location.href.substring(idx+1, location.href.length).split('&');
    for (var i=0; i<pairs.length; i++) {
      nameVal = pairs[i].split('=');
      params[nameVal[0]] = nameVal[1];
    }
  }
  return params;
};
app.getParam = function(param) {
  if (!app.__params){app.__params = app.getParams();}
  return app.__params[param];
};
app.findRule = function(rule) {
    var sheet, rules, ruleobj;
    for(var i = document.styleSheets.length-1 ; i>=0 ; --i)
    {
        sheet = document.styleSheets[i];
        rules = app.isIE?sheet.rules:sheet.cssRules;
        for(var j = rules.length-1 ; j>=0 ; --j) {
            ruleobj = rules[j];
            if (ruleobj.selectorText.toUpperCase()==rule.toUpperCase())
            { return ruleobj.style; }
        }
    }
    return false;
}
app.cssValue = function(el, s) {
    if(app.isIE) {
        return el.currentStyle[s];
    } else {
        return document.defaultView.getComputedStyle(el, '').getPropertyValue(s);
    }
};
app.getrect = function(tng, _global) {
    var tmp;
    var left, top, right, bottom;
    tmp = tng;
    left = top = 0;
    while (tmp)
    {
        left += tmp.offsetLeft;
        top += tmp.offsetTop;
        if (_global) { tmp = tmp.offsetParent; }
        else { break; }
    }
    right  = left + tng.offsetWidth;
    bottom = top  + tng.offsetHeight;
    return [left,top,right,bottom];
};
/* IE png alpha replacement ------------------------------------------------ */

if (app.isIE && app.major<7 && (app.major>5 || (app.major>=5 && app.minor>=5))) {
    app.pngFixAdd = function() {
        if (!app._pngList) {
            app._pngList = new Array();
            app.addEvent(window,'load',app.pngFixCorrectList);
        }
        for(var i=0;i<arguments.length;i++) {
            var el = app.el(arguments[i]);
            el.style.visibility = 'hidden';
            app._pngList.push(el);
        }
    };
    app.pngFixCorrectList = function() {
        if (app._pngList) {
            for(var i=0;i<app._pngList.length;i++)
            {app.pngFixCorrect(app._pngList[i],true);}
            delete app._pngList;
        }
    };
    app.pngFixCorrect = function(img, set_visible) {
        if (typeof img == "string")
        {img = app.el(img);}
        if (img) {
            var imgID = (img.id) ? "id='" + img.id + "' " : "";
            var imgClass = (img.className) ? "class='" + img.className + "' " : "";
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
            var imgStyle = "display:inline-block;" + img.style.cssText;
            if (img.align == "left") imgStyle = "float:left;" + imgStyle;
            if (img.align == "right") imgStyle = "float:right;" + imgStyle;
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
            img.outerHTML = "<span "+ imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"+ (set_visible?"visibility:inherit;":"") + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
            return true;
        }
        return false;
    };
    app.pngAlphaFix = function() {
        for(var i=(document.images.length-1); i>=0; i--)
        {if (document.images[i].className.indexOf('alpha_fix') > -1){ app.pngFixCorrect(document.images[i], true); }}
    };
    app.addEvent(window,'load',app.pngAlphaFix);
    app.setPNG = function(el,src){el.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;};
}
else {
    app.setPNG = function(el,src){el.src = src;};
    app.pngFixAdd = app.pngFixCorrect = app.pngFixCorrectList = app.pngFixAll = app.pngAlphaFix = app._nullfunc;
}

app.getAlpha = function(el){
  if(app.isMac && app.isIE)return 100;
  if(app.isGecko){
    var a = el.style.getPropertyValue("-moz-opacity");
    if(app.isNull(a))return 100;
    return parseInt(a*100);
  }
  if(app.isIE){
    var a = 100;
    var tmp = el.style.filter.split("(");
    if (tmp.length>1){
      var pairs = tmp[1].split(",");
      var props = {opacity:100};
      var tmp;
      for(var i=0;i<pairs.length;i++) {
          tmp = pairs[i].split("=");
          props[tmp[0]]=app.rInt(parseInt(tmp[1]),100);
      }
      a = props.opacity;
    }
    return a;
  }
  return app.rInt(parseInt(el.style.opacity*100),100);
};
app.setAlpha = function(el, a){
    if (typeof el == "string")
    {el = app.el(el);}
    if(app.isMac && app.isIE)return;
    if(!String(a).indexOf("%"))a=parseInt(a)*100;
    a=parseInt(a);
    if(a<0)a=0; if(a>100)a=100;
    if(app.isGecko) {
        el.style.setProperty("-moz-opacity", (a==100 ? "" : a/100), "");
    } else if(app.isIE) {
        el.style.filter = ((a==100) ? "alpha(enabled=0)" : "alpha(opacity="+a+",enabled=1)");
    } else {
        el.style.setProperty("opacity", (a==100 ? "" : a/100), "");
    }
};
app.ieActivate = function(el) {
    if(app.isIE && app.major>5)
    { el.outerHTML = el.outerHTML; }
};
app.validate_email = function(str){
    return (null !== str.match(/^((\\"[^\\"\f\n\r\t\v\b]+\\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/));
    /*
    var at="@"; var dot="."; var lat=str.indexOf(at); var lstr=str.length; var ldot=str.indexOf(dot);
	if (   (str.indexOf(at)==-1)|| (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)|| (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)|| (str.indexOf(at,(lat+1))!=-1)|| (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)|| (str.indexOf(dot,(lat+2))==-1)|| (str.indexOf(" ")!=-1)) {
        return false;
	}
	return true;
    */
};
app.ietablewidthhack = function(el) {
    return (el.offsetParent.offsetWidth-17)+'px';
};
app.isuuid = function(uuid) {
    return (app.isString(uuid) && uuid.length > 0 && (uuid.toLowerCase().search(/^{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}}$/)!=-1));
};
app.uuidval = function(uuid) {
    return app.isuuid(uuid)?uuid:EMPTY_UUID;
};

app.getrect = function(tng, _global) {
    var tmp;
    var left, top, right, bottom;
    tmp = tng;
    left = top = 0;
    while (tmp)
    {
        left += tmp.offsetLeft;
        top += tmp.offsetTop;
        if (_global) { tmp = tmp.offsetParent; }
        else { break; }
    }
    right  = left + tng.offsetWidth;
    bottom = top  + tng.offsetHeight;
    return [left,top,right,bottom];
};
app.proxy = function() {
    return app.xmlrpc.getProxy('Application', BF_KEY);
};

app._callbacks = {};
app.register_callback = function(_luid, _functor) { app._callbacks[_luid] = _functor; };
app.unregister_callback = function(_luid, _functor) { app._callbacks[_luid] = null; };
app.global_callback = function(_luid, _args) {
    var _functor = app._callbacks[_luid];
    if (_functor && app.isFunction(_functor.fire))
    {
        _functor.fire([_args]);
    }
};

app.ui = {};
app.ui.ui_proto = {};

var EMPTY_UUID   = '';
var RIGHT_READ   = 1;
var RIGHT_EMBED  = 2;
var RIGHT_UPDATE = 3;
var RIGHT_DELETE = 4;
var RIGHT_GRANT  = 5;
var RIGHT_TYPE_MIN = RIGHT_READ;
var RIGHT_TYPE_MAX = RIGHT_GRANT;
var RIGHT_NO_ALLOW = RIGHT_TYPE_MIN - 1;
var RIGHT_NO_DENY  = RIGHT_TYPE_MAX + 1;

// --------------------------------------------

app.isLoaded=false;
app.addEvent(window,'load', function(){app.isLoaded=true;});
