if(!CARE2) {
/*********************************************************************************************
    Shortcuts
**/

var $=function(){
    var ls=[];
    for(var l,i=0;l=arguments[i];i++){
        if(typeof l == 'string')l=document.getElementById(l);
        if(arguments.length == 1)return l;
        ls.push(l);
    }
    return (ls.length>0) ? ls : false;
}

if(!''.camelize){String.prototype.camelize=function(){var s=this,x=/-([a-z])/;while(x.test(s)) s=s.replace(x,RegExp.$1.toUpperCase());return s;}}
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}
String.prototype.ltrim=function(){return this.replace(/^\s+/g,"")}
String.prototype.rtrim=function(){return this.replace(/\s+$/g,"")}

Array.prototype.inArray=function(q){
    for(var l,i=0;l=this[i];i++)if(l===q)return true;
    return false;
}

var re = /^(.*\-)?.*/;
var js_www_stage = document.domain.replace(re, "$1");

/*********************************************************************************************
    Global Functions
**/

var setCookie=function(c,v,ex){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+ex);
    document.cookie=c+"="+escape(v)+((ex==null) ? "" : ";expires="+exdate.toGMTString());
}

var getCookie=function(c){
    if(document.cookie.length>0){
        c_start=document.cookie.indexOf(c+"=");
        if(c_start!=-1){
            c_start=c_start+c.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if(c_end==-1)c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return false;
}

/*********************************************************************************************
    SWFObject v2.1 <http://code.google.com/p/swfobject/>
    	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
    	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
**/

if(!swfobject){
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();
}

/*********************************************************************************************
    CARE2 Object
**/

var CARE2={
stage:js_www_stage,
loggedIn:function(){
    return ($('care2_loginlinks').getElementsByTagName('li')[0].className.indexOf('welcome')>=0);
},
bodyReady:false,
appendToBody:function(d){
    if(this.bodyReady){
        document.body.appendChild(d);
    }else{
        document.body.insertBefore(d, document.body.firstChild);
    }
},
debugwin:function(){
    var _self=this;
    var o={
        active:false,
        win:document.createElement('div'),
        put:function(t){
            if(this.active)this.win.innerHTML=t+"<br>"+this.win.innerHTML
        },
        activate:function(){
            if(!this.active)CARE2.appendToBody(this.win);
            this.active=true;
        }
    }
    o.win.style.cssText='padding:3px;border:1px solid #000;background:#fff;width:400px;height:700px;overflow:auto;position:fixed;top:0;right:0';
    return o;
}(),
isIE:navigator.userAgent.match(/MSIE/),
isSafari:navigator.userAgent.match(/safari/i),
isOpera:window.opera,
isFirefox:navigator.userAgent.match(/Firefox/),
isJSON:function(t){
    t=t.replace(/\\\'/g,"'");
    return /^[\],:{}\s]*$/.test(t.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
},

iFrame:function(styles,allBrowsers){
    var iframe = $('care2_dropdown_iframe');
    if(!styles || typeof styles != "object"){
        iframe.style.left = iframe.style.top = iframe.style.width = iframe.style.height = 0;
    }else{
        if(CARE2.isIE||allBrowsers){
            for(var i in styles){
                iframe.style[i] = styles[i];
            }
        }
    }
},

getFlashMovieObject:function(m){
    if(window.document[m])return window.document[m];
    if(navigator.appName.indexOf("Microsoft Internet")==-1){
        if(document.embeds && document.embeds[m])return document.embeds[m];
    }else{
        return $(m);
    }
},

getMousePos:function(e){
    var e=e||window.event;
    if(e.pageX||e.pageY) return {x:e.pageX,y:e.pageY};
    return {x:e.clientX+document.body.scrollLeft-document.body.clientLeft,y:e.clientY+document.body.scrollTop-document.body.clientTop};
},

getPageScroll:function(){
    var x,y;
    if(self.pageYOffset){
        y=self.pageYOffset;x = self.pageXOffset;
    }else if(document.documentElement&&document.documentElement.scrollTop){
        y=document.documentElement.scrollTop;
        x=document.documentElement.scrollLeft;
    }else if(document.body){
        y=document.body.scrollTop;
        x=document.body.scrollLeft;
    }
    return {x:x,y:y};
},

getPageSize:function(){
    var x,y;
    if(window.innerHeight&&window.scrollMaxY){
        x=window.innerWidth+window.scrollMaxX;
        y=window.innerHeight+window.scrollMaxY;
    }else if(document.body.scrollHeight>document.body.offsetHeight){
        x=document.body.scrollWidth;
        y=document.body.scrollHeight;
    }else{
        x=document.body.offsetWidth;
        y=document.body.offsetHeight;
    }
    var ww,wh;
    if(self.innerHeight){
        (document.documentElement.clientWidth)?ww=document.documentElement.clientWidth:ww=self.innerWidth;
        wh=self.innerHeight;
    }else if(document.documentElement&&document.documentElement.clientHeight){
        ww=document.documentElement.clientWidth;
        wh=document.documentElement.clientHeight;
    }else if(document.body){
        ww=document.body.clientWidth;
        wh=document.body.clientHeight;
    }
    (y<wh)?pageHeight=wh:pageHeight=y;
    (x<ww)?pageWidth=x:pageWidth=ww;
    return {pageWidth:pageWidth,pageHeight:pageHeight,windowWidth:ww,windowHeight:wh};
},

backgroundPNG:function(p){
    return (navigator.userAgent.indexOf('MSIE')>=0)?"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (src='"+p+"', sizingMethod='crop');":"background: transparent url("+p+") no-repeat scroll top left;"
},

buildElement:function(t,p){
    var d=document.createElement(t);
    for(var i in p){
        if(i=="style"){
            for(j in p[i]) d.style[j]=p[i][j];
        }else{
            d[i]=p[i]
        }
    }
    return d;
},

setOpacity:function(d,o){
    d=$(d);
    d.style.opacity=o/100;
    d.style.MozOpacity=o/100;
    d.style.KhtmlOpacity=o/100;
    d.style.filter="alpha(opacity="+o+")";
},

prettyDate:function(d){
    var time_formats=[[60,'Just Now'],[90,'1 Minute'],[3600,'Minutes',60],[5400, '1 Hour'],[86400,'Hours',3600],[129600,'1 Day'],[604800,'Days',86400],[907200,'1 Week'],[2628000,'Weeks',604800],[3942000,'1 Month'],[31536000,'Months',2628000],[47304000,'1 Year'],[3153600000,'Years',31536000],[4730400000,'1 Century'],];
    var time=(''+d).replace(/-/g,"/").replace(/[TZ]/g," "),dt=new Date,seconds=((dt-new Date(time))/1000),token=' Ago',i=0,format;
    if(seconds<0){
        seconds=Math.abs(seconds);
        token='';
    }
    while(format=time_formats[i++]){
        if(seconds<format[0]){
            if(format.length==2){
                return format[1]+(i>1?token:'');
            }else{
                return parseInt(seconds/format[2])+' '+format[1]+(i>1?token:'');
            }
        }
    }

    if(seconds > 4730400000)return parseInt(seconds / 4730400000) + ' Centuries' + token;
    return d;
},

cloneObj:function(o){
    if((typeof(o)!='object')||(o==null))return o;
    var n={};
    for(var i in o)n[i]=this.cloneObj(o[i]);
    return n;
},
returnGetVars:function(){
    var o={};
    var q=document.URL.indexOf('?');
    if(q>-1){
        s=document.URL.substring(q+1,document.URL.length);
        var a=s.split('&');
        for(var b,i=0;b=a[i];i++)o[b.split('=')[0]]=b.split('=')[1];
        return o;
    }else{
        return false;
    }
},

hasLayoutToggle:function(el,on){
    el=$(el);
    if(!el||!el.currentStyle) return;
    /*@cc_on @if(@_jscript&&!(@_win32||@_win16)&&(@_jscript_version<5.5)) return; @end @*/
    if(typeof(el.currentStyle.hasLayout)!='undefined'){
        if(on && el.currentStyle.hasLayout)return;
        el.style.zoom=!on?'':'1';
    }else{
        var re=/^auto|0$/,cs=el.currentStyle;
        if(on && (!re.test(cs.height) || !re.test(cs.width))) return;
        if(on) el._oldHeight=el.style.height;
        el.style.height=!on?(el._oldHeight||''):'1px';
        if(!on) el._oldHeight='';
    }
},

Color:function(c){
    var obj={r:0,g:0,b:0,
        set:function(color){
            return (color.indexOf("rgb(")==0)?this.setRGB(color):this.setHex(color);
        },
        setHex:function(h){
            if(h.charAt(0)=="#") h=h.slice(1);
            if(h.length==3){
                var ar=h.split(''),i=-1;
                while(++i<3) ar[i]+=ar[i];
                h=ar.join('');
            }
            this._setValue('r',parseInt(h.slice(0,2),16));
            this._setValue('g',parseInt(h.slice(2,4),16));
            return this._setValue('b',parseInt(h.slice(4,6),16));
        },
        setRGB:function(rgb){
            var colors=rgb.slice(4).split(',');
            this._setValue('r',parseInt(colors[0],10));
            this._setValue('g',parseInt(colors[1],10));
            return this._setValue('b',parseInt(colors[2],10));
        },
        changeColor:function(amount){
            this.changeRed(amount);
            this.changeGreen(amount);
            return this.changeBlue(amount);
        },
        changeRed:function(amount){
            return this._setValue('r',this.r+parseInt(amount));
        },
        changeGreen:function(amount){
            return this._setValue('g',this.g+parseInt(amount));
        },
        changeBlue:function(amount){
            return this._setValue('b',this.b+parseInt(amount));
        },
        getRGB:function(){
            return 'rgb('+this.r+', '+this.g+', '+this.b+')';
        },
        getHex:function(){
            return ('#'+this._toHex(this.r)+this._toHex(this.g)+this._toHex(this.b));
        },
        _toHex:function(n){
            return ((n.toString(16).length==1?'0':'')+n.toString(16).toLowerCase());
        },
        _setValue:function(color,num){
            this[color]=((num<0)?0:((num>255)?255:num));
            return this;
        }
    }
    if(c)obj.set(c);
    return obj;
},

about_rollover:function(args){
    var obj={};
    var _self=this;

    obj.data=args.data||[];
    obj.panels={};
    obj.className = args.className||'care2_about_rollover';
    obj.rightLimit = (args.rightLimit) ? $(args.rightLimit) : false;
    obj.offset = args.offset||[-3,-57];
    obj.overPopup = false;
    obj.overThumb = false;
    obj.curPanel = false;
    obj.intvl = false;
    if(obj.rightLimit) obj.rightLimit = _self.getElementPosition(obj.rightLimit).left + obj.rightLimit.offsetWidth;

    obj.tempWindow=_self.buildElement('div',{id:'care2_rollover_window',className:obj.className});
    obj.tempWindow.appendChild(hotspot = _self.buildElement('div',{className:'care2_rollover_hotspot'}));
    hotspot.appendChild(_self.buildElement('div',{className:'loading'}));

    obj.hidePanel=function(id){
        if(obj.intvl) clearTimeout(obj.intvl);
        setTimeout(function(id){return function(){
            if(((obj.panels[id]&&obj.panels[id].parentNode)||obj.tempWindow.parentNode) && !obj.overPopup && !obj.overThumb) {
                if($('care2_rollover_window'))$('care2_rollover_window').parentNode.removeChild($('care2_rollover_window'));
                CARE2.iFrame();
            }
        }}(id),250);
    }

    obj.hotspotOver = function(e,id) {
        this.overPopup = id;
    }

    obj.hotspotOut = function(e,id) {
        this.overPopup = false;
        this.hidePanel(id);
    }

    obj.displayPanel=function(id,source,imgid){
        if(source=="element"&&!obj.panels[id])obj.panels[id]='init';
        if(!obj.panels[id]){
            for(var i=0;i<obj.data.length;i++)if((obj.data[i].passportID&&obj.data[i].passportID==id)||(obj.data[i].photoID&&obj.data[i].photoID==id))obj.panels[id]=obj.data[i];

            if(!obj.panels[id]){
                obj.setPanel(obj.tempWindow,imgid);
                if(source=="members"){
                    var requrl='/servlets/profile_popup?passportIDs[0]='+id;
                    var request = YAHOO.util.Connect.asyncRequest('GET', requrl, {
                        success: function(o) {
                            if(o.status==200){
                                var json = o.responseText.replace(/(<([^>]+)>)/ig,'').trim();
                                if (_self.isJSON(json)){
                                    var resp=eval("("+json+")");
                                    for(var l,i=0;l=resp[i];i++)obj.data.push(l);
                                    obj.displayPanel(id,source,imgid);
                                }else{
                                    this.failure();
                                }
                            }else{
                                this.failure();
                            }
                        },
                        failure: function(o) {
                            if($('care2_rollover_window')) $('care2_rollover_window').parentNode.removeChild($('care2_rollover_window'));
                            CARE2.iFrame();
                        },
                        timeout: 30000
                    })
                }
            }else{obj.displayPanel(id,source,imgid);}
        }else{
            if(obj.panels[id].passportID||obj.panels[id].photoID||obj.panels[id]=='init'){
                var newpanel = _self.buildElement('div',{id:'care2_rollover_window',className:obj.className});
                var hotspot = _self.buildElement('div',{className:'care2_rollover_hotspot'});
                newpanel.appendChild(hotspot);

                CARE2.addListener(hotspot,"mouseover",obj.hotspotOver,eval(id),obj);
                CARE2.addListener(hotspot,"mouseout",obj.hotspotOut,eval(id),obj);

                if(source=="element"){
                    hotspot.innerHTML=$(obj.sourceId+"_"+id).innerHTML;
                    $(obj.sourceId+"_"+id).parentNode.removeChild($(obj.sourceId+"_"+id));
                }

                if(source=="members"){
                    // build HTML for members
                    hotspot.appendChild(about=_self.buildElement('div',{className:'about'}));
                    about.appendChild(_self.buildElement('span',{className:'tl'}));
                    about.appendChild(_self.buildElement('span',{className:'tr'}));
                    about.appendChild(aboutWrapper=_self.buildElement('div',{className:'about_wrapper'}));
                    aboutWrapper.appendChild(divname=_self.buildElement('div',{className:'name'}));
                    divname.appendChild(aspot=_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/people/profile.html?pid='+id}));
                    aspot.appendChild(_self.buildElement('img',{src:obj.panels[id].thumbnail}));
                    divname.appendChild(_self.buildElement('div',{innerHTML:obj.panels[id].name}));
                    aboutWrapper.appendChild(divname=_self.buildElement('div',{className:'actions'}));
                    divname.appendChild(ul=_self.buildElement('ul'));
                    ul.appendChild(_self.buildElement('li',{innerHTML:"member since "+obj.panels[id].member_since}));
                    if(obj.panels[id].friends_count&&obj.panels[id].friends_count!="0")ul.appendChild(_self.buildElement('li',{innerHTML:obj.panels[id].friends_count+" friends"}));
                    if(obj.panels[id].petitions_signed&&obj.panels[id].petitions_signed!="0")ul.appendChild(_self.buildElement('li',{innerHTML:obj.panels[id].petitions_signed+" petitions signed"}));
                    about.appendChild(ul=_self.buildElement('div',{className:"kudos"}));
                    ul.appendChild(_self.buildElement('div',{className:"background"}));
                    ul.appendChild(_self.buildElement('a',{className:"stars",innerHTML:obj.panels[id].green_stars,href:"http://"+_self.stage+"www.care2.com/c2c/my/kudos_green_stars.html?pid="+id}));
                    ul.appendChild(_self.buildElement('a',{className:"butterflies",innerHTML:obj.panels[id].butterflies,href:"http://"+_self.stage+"www.care2.com/c2c/my/kudos_butterflies.html?pid="+id}));
                    ul.appendChild(_self.buildElement('a',{className:"notes",innerHTML:obj.panels[id].golden_notes,href:"http://"+_self.stage+"www.care2.com/c2c/my/kudos_golden_notes.html?pid="+id}));
                    about.appendChild(_self.buildElement('span',{className:'bl'}));
                    about.appendChild(_self.buildElement('span',{className:'br'}));
                    hotspot.appendChild(about=_self.buildElement('div',{className:'icare',innerHTML:"I care about&#0133;<br/>"}));
                    var total_length=0;
                    if(obj.panels[id].causes){
                        for(var l,i=0;l=obj.panels[id].causes[i];i++){
                            l=l.trim();
                            total_length+=l.length;
                            var newl = (total_length>35) ? l.substr(0,35-(total_length-35))+"&#0133;" : l;
                            about.appendChild(_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/people/tag/causes/'+escape(l),innerHTML:newl}));
                            if(total_length>35){
                                break;
                            }else{
                                if(i<obj.panels[id].causes.length-1)about.appendChild(document.createTextNode(", "));
                            }
                        }
                    }
                    hotspot.appendChild(about=_self.buildElement('ul',{className:'toolbar'}));
                    if(!obj.panels[id].is_friend){
                        about.appendChild(li=_self.buildElement('li',{className:'add'}));
                        li.appendChild(_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/my/add_friend.html?fid='+id+'&sul='+escape(location.href),innerHTML:'Add as friend'}));
                    }else{
                        about.appendChild(li=_self.buildElement('li',{className:'email'}));
                        li.appendChild(_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/pm/compose?pm[recipientID][]='+id,innerHTML:'Send message'}));
                    }
                    about.appendChild(li=_self.buildElement('li',{className:'star'}));
                    li.appendChild(_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/people/greenstar.html?targetID='+id,innerHTML:'Send green star'}));
                }

                if(source=="photos"){
                    // build HTML for photos
                    hotspot.appendChild(about=_self.buildElement('div',{className:'pic'}));
                    about.appendChild(img=_self.buildElement('a',{href:obj.panels[id].photoURL}));
                    img.appendChild(_self.buildElement('img',{src:obj.panels[id].photoSRC}));
                    about.appendChild(author=_self.buildElement('div',{className:'author'}));
                    author.appendChild(document.createTextNode('posted by: '));
                    author.appendChild(_self.buildElement('a',{href:'http://'+_self.stage+'www.care2.com/c2c/people/profile.html?pid='+obj.panels[id].ownerID,innerHTML:obj.panels[id].ownerName}));
                }

                obj.panels[id]=newpanel;
            }

            obj.intvl = setTimeout(function(){
                if(obj.overThumb == id){
                    obj.curPanel = id;
                    obj.setPanel(obj.panels[id],imgid);
                    obj.intvl = false;
                }
            },100);
        }
    }

    obj.setPanel=function(panel,imgid){
        if(CARE2.bodyReady){
            panel.style.visibility = "hidden";CARE2.appendToBody(panel);
            obj.windowWidth = panel.offsetWidth;
            document.body.removeChild(panel);panel.style.visibility = "visible";

            if(imgid.getElementsByTagName&&imgid.getElementsByTagName('img')[0])imgid=imgid.getElementsByTagName('img')[0];
            var pos = _self.getElementPosition(imgid);
            var ofst = {w:imgid.offsetWidth,h:imgid.offsetHeight}
            if(imgid.coords){
                var newimgid = imgid.parentNode.parentNode.getElementsByTagName('img');
                for(var l,i=0;l=newimgid[i];i++){
                    if(l.src.indexOf(imgid.parentNode.id)>=0)pos = _self.getElementPosition(l);
                }
                var coords=imgid.coords.replace(" ",",").split(",");
                pos.top+=parseInt(coords[1]);
                pos.left+=parseInt(coords[0]);
                ofst = {
                    w:parseInt(coords[2])-parseInt(coords[0]),
                    h:parseInt(coords[3])-parseInt(coords[1])
                }
            }

            var newVals = (obj.rightLimit && pos.left+ofst.w+obj.windowWidth > obj.rightLimit) ? {
                className: obj.className+" "+obj.className+"_left",
                top: (pos.top+parseInt(ofst.h/2)+obj.offset[1])+"px",
                left: (pos.left-obj.windowWidth-obj.offset[0])+"px"
            } : {
                className: obj.className,
                top: (pos.top+parseInt(ofst.h/2)+obj.offset[1])+"px",
                left: (pos.left+(ofst.w+obj.offset[0]))+"px"
            };

            panel.className = newVals.className;
            panel.style.top = newVals.top;
            panel.style.left = newVals.left;

            if($('care2_rollover_window')) $('care2_rollover_window').parentNode.removeChild($('care2_rollover_window'));
            CARE2.appendToBody(panel);
            CARE2.iFrame({
                width:panel.offsetWidth+"px",
                height:panel.offsetHeight+"px",
                top:panel.style.top,
                left:panel.style.left
            });
        }
    }

    obj.assignOver = function(e,o) {
        this.overThumb = o.x;
        this.displayPanel(o.x,o.y,o.l);
    }

    obj.assignOut = function(e,o) {
        this.overThumb = false;
        this.hidePanel(o.x);
    }

    obj.assignFunctions=function(l,theID,source){
        CARE2.addListener(l,"mouseover",obj.assignOver,{x:theID,y:source,l:l},obj);
        CARE2.addListener(l,"mouseout",obj.assignOut,{x:theID},obj);
    }

    obj.members=function(l, theID){
        if(!theID) {
            var match = l.href.match(/\d{9}/g);

            if(!match)
            { return null; }

            theID = match.pop();
        }

        obj.assignFunctions(l,theID,"members");
        return theID;
    }

    obj.photos=function(l){
        var theID=l.parentNode.id.split("_").pop();
        obj.assignFunctions(l,theID,"photos");
        return theID;
    }

    obj.element=function(l){
        var theID=l.id.split("_").pop();
        obj.assignFunctions(l,theID,"element");
        return theID;
    }

    obj.mem=function(l, theID){
        l.onmouseover=null;
        var x = obj.members(l, theID);
        obj.overThumb = x;
        obj.displayPanel(x,"members",l);
    }

    obj.init=function(id,args){
        obj.sourceId=args.sourceId||false;
        var thumbs=(args.tag)?$(id).getElementsByTagName(args.tag):[$(id)];
        var preLoad=[];

        for(var l,i=0;l=thumbs[i];i++){
            var theID=l.id.split("_").pop();
            if(args.source)theID=obj[args.source](l);
            preLoad.push(theID);
        }

        if(args.source=="members"&&!args.noPreLoad){
            if(args.preData){
                for(var l,i=0;l=args.preData[i];i++)obj.data.push(l);
            }else{
                for(var l,i=0;l=preLoad[i];i++)preLoad[i]="passportIDs["+i+"]="+l;
                _self.addListener(window,'load',function(x){return function(){
                    var requrl='/servlets/profile_popup?'+x;
                    var request = YAHOO.util.Connect.asyncRequest('GET', requrl, {
                        success: function(o) {
                            if(o.status==200){
                                var resp=eval("("+o.responseText.replace(/(<([^>]+)>)/ig,'').trim()+")");
                                for(var l,i=0;l=resp[i];i++)obj.data.push(l);
                            }else{
                                this.failure();
                            }
                        },
                        failure: function(o) {
                            return false;
                        },
                        timeout: 30000
                    })
                }}(preLoad.join("&")));
            }
        }
    }

    return obj;
},

flashFix:function(v) {
    v=v||"hidden";
    var o=document.getElementsByTagName('embed');
    for(var i=0;i<o.length;i++){
        if((o[i].getAttribute("wmode")&&(o[i].getAttribute("wmode").toLowerCase()!="transparent"&&o[i].getAttribute("wmode").toLowerCase()!="opaque"))||(!o[i].getAttribute("wmode")))o[i].style.visibility=v;
    }
    var o=document.getElementsByTagName('object');
    for(var i=0;i<o.length;i++){
        var wmodeset=false;
        var p=o[i].getElementsByTagName('param');
        for(var j=0;j<p.length;j++){
            if(p[j].getAttribute("name").toLowerCase()=="wmode")wmodeset=true;
            if(p[j].getAttribute("name").toLowerCase()=="wmode"&&(p[j].getAttribute("value").toLowerCase()!="transparent"&&p[j].getAttribute("value").toLowerCase()!="opaque"))o[i].style.visibility=v;
        }
        if(!wmodeset)o[i].style.visibility=v;
    }
},
floaterOverlay:false,
floaterIFrame:false,
floaterOverlayCount:0,
floater:function(html, args) {
    var obj = {};
    var _self = this;

    // function to remove flash if wmode != transparent
    obj.flashFix = function(v) { _self.flashFix(v); }

    // show function
    obj.show = function(html) {
        obj.flashFix();
        obj.createOverlay();

        if(html) obj.insertContent(html);

        obj.box.style.visibility = "hidden"; obj.box.style.display = "block";
        obj.resizeBox();
        obj.box.style.visibility = "visible";

        if(obj._onshow) obj._onshow();
    }

    // hide funtion
    obj.hide = function() {
        obj.flashFix("visible");
        obj.hideOverlay();
        if(obj.removeOnClose){
            obj.box.parentNode.removeChild(obj.box);
        }else{
            obj.box.style.display = "none";
        }
        if(obj._onclose) obj._onclose();
    }

    // resize function
    obj.resizeBox = function(doSize,doPosition) {
        if(typeof doSize=="undefined")doSize=true;
        if(typeof doPosition=="undefined")doPosition=true;
        var pScroll = _self.getPageScroll();
        var pSize = _self.getPageSize();
        obj.content.style.cssText = "float:left;"+obj.content.style.cssText;
        if(doSize){
            var this_width = obj.box_width||obj.content.offsetWidth;
            var this_height = obj.box_height||obj.content.offsetHeight;
            obj.box.style.width = this_width + "px";
            obj.box.style.height = (this_height + obj.header.offsetHeight) + "px";
        }
        if(doPosition){
            var this_top = (obj.box_top) ? pScroll.y+parseFloat(obj.box_top) : pScroll.y + (pSize.windowHeight / 2) - (parseFloat(obj.box.style.height) / 2);
            var this_left = (obj.box_left) ? pScroll.x+parseFloat(obj.box_left) : pScroll.x + (pSize.windowWidth / 2) - (parseFloat(obj.box.style.width) / 2);
            obj.box.style.top = this_top+"px";
            obj.box.style.left = this_left+"px";
        }
        if(_self.floaterOverlay) _self.floaterOverlay.style.height = pSize.pageHeight + "px";
        if(_self.floaterIFrame) _self.floaterIFrame.style.height = pSize.pageHeight + "px";
        if(_self.floaterIFrame) _self.floaterIFrame.style.width = pSize.pageWidth + "px";
    }

    obj.createOverlay = function() {
        if(!obj.disableOverlay) {
            _self.floaterOverlayCount++;
            if(_self.floaterOverlayCount == 1) {
                _self.floaterOverlay = _self.buildElement('div',{className:'care2_floater_overlay'});
                if(!obj.disableOverlayClose && !obj.disableClose) _self.floaterOverlay.onclick = obj.hide;
                CARE2.appendToBody(_self.floaterOverlay);
                if(this.isIE) {
                    _self.floaterIFrame = document.createElement('<iframe frameborder="0">');
                    _self.floaterIFrame.style.position = 'absolute';
                    _self.floaterIFrame.border = '0';
                    _self.floaterIFrame.frameborder = 0;
                    _self.floaterIFrame.className = "care2_floater_iframe";
                    _self.floaterIFrame.style.left = 0;
                    _self.floaterIFrame.style.top = 0;
                    CARE2.appendToBody(_self.floaterIFrame);
                }
            }
        }
    }

    obj.hideOverlay = function() {
        _self.floaterOverlayCount--;
        if(_self.floaterOverlayCount == 0) {
            if(_self.floaterOverlay) _self.floaterOverlay.parentNode.removeChild(_self.floaterOverlay);
            if(_self.floaterIFrame) _self.floaterIFrame.parentNode.removeChild(_self.floaterIFrame);
            _self.floaterIFrame = _self.floaterOverlay = false;
        }
    }

    obj.insertContent = function(html) {
        var content = $(html);
        if(!content) {
            content = document.createElement('div');
            content.innerHTML = html;
        }else if(content.parentNode){
            content.parentNode.removeChild(content);
        }
        obj.content.innerHTML = "";
        obj.content.appendChild(content);
        content.style.display = "block";
    }

    // initialize the floater
    if(!args) args = {};
    obj.box_width = args.width||false;
    obj.box_height = args.height||false;
    obj.box_top = args.top||false;
    obj.box_left = args.left||false;
    obj._onclose = args._onclose||false;
    obj._onload = args._onload||false;
    obj._onshow = args._onshow||false;
    obj.box_id = args.id||false;
    obj.box_className = args.className||'care2_floater_container';
    obj.disableOverlay = args.disableOverlay||false;
    obj.disableOverlayClose = args.disableOverlayClose||false;
    obj.disableClose = args.disableClose||false;
    obj.removeOnClose = args.removeOnClose||false;
    obj.branding = args.branding||'none';
    var titletxt = args.titletxt||"";

    // main box wrapper
    obj.box = _self.buildElement("div",{className:obj.box_className,style:{visibility:'hidden'}});
    if(obj.box_id)obj.box.id = obj.box_id;
    obj.header = _self.buildElement("div",{className:'floater_header branding_none'});
    if(obj.branding) obj.header.className = 'floater_header branding_'+obj.branding;
    obj.title = _self.buildElement("div",{className:'floater_title',innerHTML:titletxt});

    obj.header.appendChild(obj.title);
    obj.box.appendChild(obj.header);

    if(!obj.disableClose) {
        obj.closebox = _self.buildElement("div",{className:'floater_closebox',onclick:obj.hide});
        obj.box.appendChild(obj.closebox);
    }

    obj.content = _self.buildElement("div",{className:'contain_floats floater_content'});
    obj.insertContent(html);
    obj.box.appendChild(obj.content);
    CARE2.appendToBody(obj.box);

    if(obj._onload)obj._onload();
    obj.show();

    return obj;
},

/*********************************************************************************************
    Depreciated CARE2 Object functions
**/

inArray:function(n,h){for(var l,i=0;l=h[i];i++) if(n==l) return true; return false;},
isIdOrHandler:function(h){return $(h);},
domReady:function(f,a){
    var obj = {
        func:f,
        waiting:0,
        wait:function(){
            this.waiting--;
            if(this.waiting<=0) {
                this.func();
            }
        }
    };

    for(var i in a){
        obj.waiting++;
        YAHOO.util.Event.onAvailable(i,function(){obj.wait()},obj);
    }
},
getElementPosition:function(d){
    var c=YAHOO.util.Dom.getXY($(d));
    return {top:c[1],left:c[0]}
},
addClassName:function(d,c){
    YAHOO.util.Dom.addClass(d,c);
    return $(d).className;
},
removeClassName:function(d,c){
    YAHOO.util.Dom.removeClass(d,c);
    return $(d).className;
},
addClass:function(d,c){
    YAHOO.util.Dom.addClass(d,c);
    return $(d).className;
},
removeClass:function(d,c){
    YAHOO.util.Dom.removeClass(d,c);
    return $(d).className;
},
getStyle:function(el,prop,numOnly){
    var s=YAHOO.util.Dom.getStyle(el,prop);
    return (numOnly) ? (parseFloat(s)||0) : s;
},
connect:function(type,requrl,args){
    return YAHOO.util.Connect.asyncRequest(type,requrl,args);
},
preventDefault:function(e){
    YAHOO.util.Event.preventDefault(e);
},
addListener:function(el,type,func,obj,override,prevent){
    obj=obj||$(el);
    var _self = this;
    if(typeof override == "undefined") override = false;
    if(prevent) YAHOO.util.Event.addListener(el,type,_self.preventDefault);
    if(type=="focus") { YAHOO.util.Event.addFocusListener(el,func,obj,override); return false; }
    if(type=="blur") { YAHOO.util.Event.addBlurListener(el,func,obj,override); return false; }
    YAHOO.util.Event.addListener(el,type,func,obj,override);
},
removeListener:function(el,type,func){
    if(type=="focus") { YAHOO.util.Event.removeFocusListener(el,func,obj,override); return false; }
    if(type=="blur") { YAHOO.util.Event.removeBlurListener(el,func,obj,override); return false; }
    YAHOO.util.Event.removeListener(el,type,func,obj,override);
},
fade:function(id, args) {
    var _self = this;
    var obj={
        totalFades:0,
        oncomplete:function(){
            this.totalFades--;
            if(this.totalFades<=0 && this._oncomplete) this._oncomplete();
        }
    }
    obj._oncomplete = args._oncomplete||false;

    obj.objs = (id.constructor != Array) ? [id] : id;
    for(var i=0;i<obj.objs.length;i++) {
        var fadeTo = l.end||(l.direction == 'out' ? 0 : 100);
    	var fadeOut = new YAHOO.util.Anim(l.id, { opacity: { to: fadeTo } }, 0.5);
    	if(obj._oncomplete) fadeOut.onComplete.subscribe(function(){obj.oncomplete()});
    	fadeOut.animate();
    }
},
expand:function(args) {
    var _self = this;
    var obj={totaldivs:0};
    obj.coldiv=$(args.coldiv);
    obj.expdiv=$(args.expdiv);
    obj.colheight=args.colheight||0;
    obj.expheight=args.expheight||false;
    obj.oncomplete=function(){
        this.totaldivs--;
        if(this.totaldivs<=0 && this._oncomplete) this._oncomplete();
    };
    obj._oncomplete=args._oncomplete||false;
    obj.duration = false;

    obj.getSize = function(d,s) {
        s=s||"height";
        if(d.style[s].indexOf('px')<0) {
            var n = (s=="height") ? d.offsetHeight - (parseFloat(_self.getStyle(d,'padding-top')) + parseFloat(_self.getStyle(d,'padding-bottom'))) : d.offsetWidth - (parseFloat(_self.getStyle(d,'padding-left')) + parseFloat(_self.getStyle(d,'padding-right')));
            var b = (s=="height") ? parseFloat(_self.getStyle(d,'border-top-width')) + parseFloat(_self.getStyle(d,'border-bottom-width')) : parseFloat(_self.getStyle(d,'border-left-width')) + parseFloat(_self.getStyle(d,'border-right-width'));
            if(b) n=n-b;
            if(n<=0) return 0;
            return n+"px";
        }else{
            return d.style[s];
        }
    }

    obj.getDuration = function(d,h) {
        var difference = Math.abs(parseInt(this.getSize(d)) - h);
        return (0.25 * (difference/300));
    }

    if(obj.coldiv) {
        obj.totaldivs++;
        obj.coldiv.style.overflow = "hidden";
        var collapse = new YAHOO.util.Anim(obj.coldiv, { height: { to: obj.colheight } }, obj.getDuration(obj.coldiv, obj.colheight));
        collapse.onComplete.subscribe(function(){
            obj.oncomplete();
            if(obj.coldiv.style.height=="0" || obj.coldiv.style.height=="0px") obj.coldiv.style.display="none";
        });
        collapse.animate();
    }

    if(obj.expdiv) {
        obj.totaldivs++;
        obj.expdiv.style.overflow = "hidden";
        if(!obj.expheight) {
            var oldstyle = obj.expdiv.style.cssText;
            obj.expdiv.style.height = "auto";
            if(obj.expdiv.style.display.indexOf("none")>=0||_self.getStyle(obj.expdiv,"display").indexOf("none")>=0){
                obj.expdiv.style.visibility = "hidden";
                obj.expdiv.style.display = "block";
            }
            if(obj.expdiv.offsetWidth>0) obj.expdiv.style.width = (obj.getSize(obj.expdiv,"width"));
            obj.expdiv.style.position = "absolute";
            obj.expheight = (obj.getSize(obj.expdiv)) ? obj.getSize(obj.expdiv).replace('px','') : obj.expdiv.offsetHeight;
            obj.expdiv.style.cssText = oldstyle;
        }
        if(obj.expdiv.style.display.indexOf("none")>=0||_self.getStyle(obj.expdiv,"display").indexOf("none")>=0||obj.expdiv.style.visibility.indexOf("hidden")>=0||_self.getStyle(obj.expdiv,"visibility").indexOf("hidden")>=0){
            obj.expdiv.style.height = 0;
            obj.expdiv.style.visibility = "visible";
            obj.expdiv.style.display = "block";
        }
        var expand = new YAHOO.util.Anim(obj.expdiv, { height: { to: obj.expheight } }, obj.getDuration(obj.expdiv, obj.expheight));
        expand.onComplete.subscribe(function(){ obj.oncomplete() });
        expand.animate();
    }
},

/*********************************************************************************************
    CARE2 Functions that should be un-globalized
**/

delightButtonFunction:function(e,obj) {
    e=e||window.event;
    if(!obj.played){
        this.blur();
        var anch=this;

        if(!obj.appended)CARE2.appendToBody(obj.flare);
        obj.appended=true;
        obj.flare.style.top=(CARE2.getElementPosition(obj.button).top-(obj.swf_height-obj.offset.y))+"px";
        obj.flare.style.left=(CARE2.getElementPosition(obj.button).left-(obj.swf_width-obj.offset.x))+"px";
        obj.flare.style.display="block";
        swfobject.embedSWF(obj.swf, obj.animId, obj.swf_width, obj.swf_height, "6.0.0", "expressInstall.swf", false, {wMode:'transparent'});
        if(obj.removeTime){
            setTimeout(function(){
                while(obj.flare.firstChild)obj.flare.removeChild(obj.flare.firstChild);
                obj.flare.appendChild(CARE2.buildElement('div',{id:obj.animId}));
                obj.flare.style.display="none";
            },obj.removeTime);
        }
        obj.played=true;
        if(obj.ignoreLink){
            if (obj.oldfunc) {
                obj.oldfunc();
            }
            obj.ignoreLink(this,obj);
        }else{
            setTimeout(function(){
                if(anch.href){
                    if(obj.oldfunc)this[obj.eventType]=obj.oldfunc;
                    location.href=anch.href;
                    return;
                }
                if(anch.nodeName=="INPUT"){
                    if(obj.oldfunc) this[obj.eventType]=obj.oldfunc;
                    var buttonParent=anch;
                    while(buttonParent.parentNode){
                        buttonParent=buttonParent.parentNode;
                        if(buttonParent.nodeName=="FORM"){
                            var newInput = CARE2.buildElement('input', {'type':'hidden','name':anch.name,'value':anch.value});
                            buttonParent.appendChild(newInput);
                            buttonParent.submit();
                            break;
                        }
                    }
                    return;
                }
                if(anch.click){
                    if(obj.oldfunc) this[obj.eventType]=obj.oldfunc;
                    anch.click();
                    return;
                }
            },obj.timeout);
        }

        return false;
    }
},
delightButton:function(id, args){
    var _self=this;
    var obj={};

    obj.button=$(id);
    obj.idle=args.idle;
    obj.appended=false;
    obj.swf=args.swf;
    obj.swf_width=args.width;
    obj.swf_height=args.height;
    obj.animId='delightAnim_'+Math.floor(Math.random()*100);
    obj.offset=args.offset||{x:0,y:0};
    obj.timeout=args.timeout||1000;
    obj.removeTime=args.removeTime||false;
    obj.played=false;
    obj.ignoreLink=args.ignoreLink||false;
    obj.eventType=args.eventType||"click";
    if(obj.eventType.indexOf('on') == 0) obj.eventType = obj.eventType.replace("on", "");

    obj.flare=_self.buildElement('div',{style:{display:"none",position:'absolute',overflow:'hidden',width:obj.swf_width+"px",height:obj.swf_height+"px",top:(_self.getElementPosition(obj.button).top-(obj.swf_height-obj.offset.y))+"px",left:(_self.getElementPosition(obj.button).left-(obj.swf_width-obj.offset.x))+"px"}});
    var img = new Image();img.src=obj.swf;
    obj.flare.appendChild(_self.buildElement('div',{id:obj.animId}));

    if(obj.button.nodeName=="INPUT"){
        var buttonParent=obj.button;
        while(buttonParent.parentNode){
            buttonParent=buttonParent.parentNode;
            if(buttonParent.nodeName=="FORM"){
                _self.addListener(buttonParent,"submit",function(){if(!obj.played)return false;});
                break;
            }
        }
    }

    if(obj.idle){
        if(!obj.appended)CARE2.appendToBody(obj.flare);
        obj.appended=true;
        obj.flare.style.display="block";
        swfobject.embedSWF(obj.idle, obj.animId, obj.swf_width, obj.swf_height, "6.0.0", "expressInstall.swf", false, {wMode:'transparent'});
    }

    var doOldFunc = (typeof(args.skipOldFunc) == 'undefined') || (!args.skipOldFunc);
    if (doOldFunc && obj.button[obj.eventType]) {
        obj.oldfunc=obj.button[obj.eventType];
    } else {
        obj.oldfunc = false;
    }

    CARE2.addListener(obj.button,obj.eventType,CARE2.delightButtonFunction,obj,false,true);
},

dragDrop:function(i,args){
    if(!(i=$(i))) return;
    if(!(args.handle=$(args.handle))) args.handle = i;

    var obj={};
    obj.dragObject=null;
    obj.mouseOffset=null;
    obj.onDrop=args.onDrop||false;
    obj.onMove=args.onMove||false;
    obj.onGrab=args.onGrab||false;
    obj.manual=args.manualAssign||false;
    obj.item=i;
    obj.handle=args.handle;

    obj.getMouseOffset = function(target, ev) {
        ev = ev || window.event;

        var docPos = obj.getPosition(target);
        var mousePos = obj.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    }

    obj.getPosition = function(e) {
        var left = 0;
        var top  = 0;

        while (e.offsetParent){
            left += e.offsetLeft;
            top += e.offsetTop;
            e = e.offsetParent;
        }

        left += e.offsetLeft;
        top += e.offsetTop;

        return {x:left, y:top};
    }

    obj.mouseMove = function(ev) {
        if(obj.dragObject){
            ev = ev || window.event;
            var mousePos = obj.mouseCoords(ev);

            obj.dragObject.style.position = 'absolute';
            obj.dragObject.style.top = (mousePos.y - obj.mouseOffset.y) + "px";
            obj.dragObject.style.left = (mousePos.x - obj.mouseOffset.x) + "px";

            if(obj.onMove) obj.onMove();

            return false;
        }
    }

    obj.mouseCoords = function(ev) {
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop - document.body.clientTop
        };
    }

    obj.mouseDown = function(ev) {
        obj.dragObject=obj.item;
        obj.mouseOffset=obj.getMouseOffset(obj.item,ev);
        if(obj.onGrab) obj.onGrab();
        return false;
    }

    obj.mouseUp = function() {
        if(obj.dragObject&&obj.onDrop) obj.onDrop();
        obj.dragObject = null;
    }

    this.addListener(document,"mousemove",obj.mouseMove);
    if(!obj.manual){
        this.addListener(obj.handle,"mousedown",obj.mouseDown);
        this.addListener(document,"mouseup",obj.mouseUp);
    }

    return obj;
},

/*********************************************************************************************
    CLOSING THE CARE2 OBJECT DECLARATION
**/

closeCare2:0}

/*********************************************************************************************
    Legacy Care2.js code
**/

// create references to CARE2 object
var Care2 = _Care2 = CARE2;

/* basic namespaces - utility, ajax, gui, dom, libraries */
CARE2.util=CARE2.ajax=CARE2.gui=CARE2.dom=CARE2.libraries={};

/**
 * create and/or retrieve a namespace.
 */
CARE2.namespace=function() {
    var namespace = CARE2;
    for(var i=0;i<arguments.length;++i) {
        var ptr = arguments[i];
        if(!namespace[ptr]) {
            namespace[ptr] = {};
        }
        namespace = namespace[ptr];
    }
    return namespace;
};

CARE2.parseLib=function(src) {
    var parsed = src.replace(/http:\/\//, '');
    var pieces = parsed.split(/\//);
    if(pieces[0] == 'js') {
        // relative, shared url
        pieces.shift();
    } else if(pieces[1] == 'js') {
        // check if care2 url
        var domain = pieces[0].split('.').reverse();
        var sld = domain[1].tolower();
        if(domain[1] == 'care2' || domain[1] == 'thepetitionsite') {
            // care2 url
            pieces.shift();
            pieces.shift();
        }
    }
    return pieces.join('/');
};

CARE2.include=function(src) {
    document.write('<script type="text/javascript" src="'+src+'"></script>');
};
CARE2.include_once=function(src) {
    var unq = this.parseLib(src);
    if(!this.libraries[unq]) {
        this.require(src);
        this.libraries[unq] = true;
    }
};
CARE2.gui.DefaultText = function (el, explicitDefault) {
    if(el) el = $(el); // allow id or element
    if(!el) {
        // we can create a faux one
        el = document.createElement('div');
        el.innerHTML = 'click to reset';
    }
    if(el.nodeName == 'INPUT' || el.nodeName == 'TEXTAREA') {
        this.ptr = 'value';
    } else {
        this.ptr = 'innerHTML';
    }
    this.el = el;
    if (typeof explicitDefault == 'string') {
        this.initialValue = explicitDefault;
    } else {
        this.initialValue = this.getValue();
    }
    YAHOO.util.Event.addListener(el, 'focus', this.clearDefault, this, true);
    YAHOO.util.Event.addListener(el, 'blur', this.resetIfEmpty, this, true);

    if(this.getValue() == this.initialValue) {
        CARE2.addClass(this.el, 'default_entry');
    }

    // We don't want to submit the default value to a form!
    if (typeof el.form == 'object') {
        YAHOO.util.Event.addListener(el.form, 'submit', this.clearDefault, this, true);
    }
}
CARE2.gui.DefaultText.prototype = {
    getValue: function() {
        return this.el[this.ptr];
    },
    resetIfEmpty: function(e, obj) {
        if('' == this.getValue()) {
            this.reset(e, obj);
            CARE2.addClass(this.el, 'default_entry');
        }
    },
    reset: function(e, obj) {
        this.setValue(this.initialValue);
    },
    clearDefault: function(e, obj) {
        if(this.getValue() == this.initialValue) {
            this.setValue('');
            CARE2.removeClass(this.el, 'default_entry');
        }
    },
    setValue: function(value) {

        this.el[this.ptr] = value;
    }
}

CARE2.defaultEntry = function(el, en) {
    return new CARE2.gui.DefaultText(el, en);
}

/**
 * general XML to Javascript parser
 */
CARE2.util.JsFromXml = function() { }
CARE2.util.JsFromXml.prototype.objects = {};
CARE2.util.JsFromXml.prototype.parse = function(xml) {
    if(!xml) {
        return false;
    }
    var type = xml.nodeName;
    var val = false;
    if(type == 'true') {
        val = true;
    } else if(type == 'false') {
        val = false;
    } else if(type == 'array') {
        val = [];

        var c = xml.childNodes.length;
        for(var i=0;i<c;++i) {
            var node = xml.childNodes[i];
            var index = node.getAttribute("index");
            if ( (typeof index != 'undefined') && index ) {
                val[index] = this.parse(node);
            } else {
                val[i] = this.parse(node);
            }
        }
    } else if(type == 'hash') {
        var c = xml.childNodes.length;
        val = {};
        for(var i=0;i<c;++i) {
            var node = xml.childNodes[i];
            var mykey = node.getAttribute("key");
            val[ mykey ] = this.parse(node);
        }
    } else if(type == 'value') {
        val = this.parse(xml.firstChild);
    } else if(type == '#text') {
        val = xml.textContent || xml.text || xml.nodeValue;
    } else if(type == 'resource') {
        val = false;
    } else if(type == 'datetime') {
        val = new Date();

        var unixTimestamp = xml.getAttribute("unixTimestamp");
        if (typeof unixTimestamp != 'undefined') {
            val.setTime(parseInt(unixTimestamp) * 1000);

        } else {
            // perhaps add other methods of date storage/transfer here...?
        }
    } else if(type == 'object') {
        // check for a registered constructor
        var className = xml.getAttribute("className");

        if(className && this.objects[className]) {

            // we've got one; parse data packets, which are constructor arguments
            var c = xml.childNodes.length;
            var constructorArgs = [];
            for(var i=0;i<c;++i) {
                constructorArgs.push(this.parse(xml.childNodes[i]));
            }
           val = this.objects[className].apply(this, constructorArgs);

        } else {

            // a hash is a good default
            val = {};

        }
    } else if(type == 'error') {
        val = new CARE2.util.Error(this.parse(xml.firstChild));
    } else {
        // noop
    }
    return val;
}
CARE2.util.JsFromXml.prototype.addObject = function(name, constructor) {
    this.objects[name] = constructor;
}
/**
 * examples
 *

 *
 * register a custom function
 *
faultHandler.registerHandler(3,
  function(errno, error, fault) {
      window.alert('Error: '+error+' ['+errno + ']')
  }
);

 *
 * register a built-in function
 *
faultHandler.registerHandler(0, faultHandler.display);

 *
 */
CARE2.util.FaultHandler = function() {
        this.error = '';
        this.errno = 0;
        this.handlers = [];
        this.handlers[0] = this.noop;

        // default for 'display'
        this.node = YAHOO.util.Dom.get('status');
   };
CARE2.util.FaultHandler.prototype = {
   update: function(fault) {
      var errno = fault.errno;
      var error = fault.error;
      if(this.handlers[errno]) {
          this.handlers[errno](errno, error, fault);
      } else {
          // default handler is for errno 0
          this.handlers[0](errno, error, fault);
      }
   },

   alert: function(errno, error, fault) {
      window.alert('Error: ' + error + ' [' + errno + ']');
   },

   noop: function(errno, error, fault) {
      // do nothing
   },

   display: function(errno, error, fault) {
      if(this.node) {
          node.innerHTML = error + ' [' + errno + ']';
      } else {
        // noop
      }
   },

   registerHandler: function(errno, handler) {
       this.handlers[ errno ] = handler;
   },

    singleton: false,
    instance: function() {
        if(!CARE2.util.FaultHandler.prototype.singleton) {
            CARE2.util.FaultHandler.prototype.singleton = new CARE2.util.FaultHandler();
        }
        return CARE2.util.FaultHandler.prototype.singleton;
    },
    handle: function(fault) {
        var handler = this.instance().update(fault);
    }

};
/**
 * Exception model
 */
CARE2.util.Fault = function(error, errno, backtrace) {
    this.error = error;
    this.errno = errno;
    this.backtrace = backtrace;
    CARE2.util.FaultHandler.handle(this);
}

/**
 * manage the location bar
 */
CARE2.util.LocationHandler = function() {
        this.location = this.parseLocation();
    };
CARE2.util.LocationHandler.prototype = {

    parseLocation: function() {
        var data = {};
        var junk = window.location.href.split('#');
        if(!junk.length) {
            junk = Array(junk);
        }
        data.search = junk[1];
        var items = junk[0].split('?');
        if(!items.length) {
            items = Array(items);
        }
        data.baseURL = items[0];
        data.params = {};
        if(items.length < 2) {
            return data;
        }
        var params = items[1].split('&');
        var param = null;
        for(i=0;i<params.length;++i) {
            param = params[i].split('=');
            if(!param.length) {
                data.params[ param ] = null;
            } else {
                data.params[ param[0] ] = unescape(param[1]);
            }
        }
        return data;
    },

    /**
     * create a url
     * @param string hostname
     * @param string path
     * @param string get info (any number)
     */
    createURL: function() {
        // no parametes - use the current value
        if(0 == arguments.length) {
            var loc = this.parseLocation();
            return loc.baseUrl;
        }
        // host only
        if(1 == arguments.length) {
            return arguments[0];
        }
        // host
        var url = arguments[0] + '?'+ arguments[1];
        if(2 == arguments.length) {
            return url;
        }
        for(i=2;i<arguments.length;++i) {
            url = url + '&' + arguments[i];
        }
        return url;
    },

    redirectToURL: function(url) {
        window.location = url;
    },

    getURL: function() {
        var url = this.location.baseURL;
        var params = [];
        for(key in this.location.params) {
            var val = this.location.params[key];
            if(typeof(val) != 'function') {
                params.push( key + '=' + escape(val) );
            }
        }
        if(params.length) {
            url += '?' + params.join('&');
        }
        if(this.location.search) {
            url += '#' + this.location.search;
        }
        return url;
    },

    redirectToLocation: function() {
        this.redirectToURL( this.getURL() );
    }
}

/**
 * Singleton cookie jar
 */
CARE2.util.CookieJar = function() {

    var cookie = document.cookie;
    var crumbs = cookie.split(';');
    var crumb = null;
    for(i=0;i<crumbs.length;++i) {
        crumb = crumbs[i].split('=');
        var name = crumb[0].replace(/^\s*/,'');
        this.jar[name] = unescape(crumb[1]);
    }
}
CARE2.util.CookieJar.prototype = {
    jar: {},
    get: function(name) {
        return this.jar[name];
    },
    set: function(name, value) {
        this.jar[name] = value;
        var cookie = name + '=' + escape(value);
        if(arguments.length > 2) {
            cookie = cookie + ';';
            for(i=2;i<arguments.length;++i) {
               cookie = cookie + arguments[i] + ';';
            }
        }
        document.cookie = cookie;
    },
    unset: function(name) {
        document.cookie = name + "=" + escape(this.jar[name]) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
    }
}

CARE2.util.popupWindow = {
    create: function(o) {
        var opt = ['status', 'toolbar', 'location',
                    'menubar', 'resizable', 'height', 'width'];

        var options = [];
        for(var i=0;i<opt.length;++i) {
            var key = opt[i];
            var val = parseInt(o[key]);
            if(isNaN(val)) val = this.defaults[key];
            options.push(''+key+'='+val);
        }
        var url = o.url || '';
        ++this.opened;
        var id = o.id || 'popup'+this.opened;
        var w = window.open(url, id, options.join(','));
        this.windows.push(w);
        return w;
    },
    windows: [],
    opened: 0,
    defaults: {
        status:     0,
        toolbar:    0,
        location:   0,
        menubar:    0,
        resizable:  1,
        height:     400,
        width:      400
    }
}

/**
 * a simple data source
 * that can be given a callback and sends it javascript data
 */

CARE2.ajax.SimpleDataSource = function(ini) {
    if(!ini) ini = {};
    this.name = ini.name?ini.name:'default';
    this.servletPath = ini.servletPath?ini.servletPath:'/servlets/';
    this.servlet = ini.servlet?ini.servlet:'default.php';
    this.scope = this;
    this.ini = ini;
};
CARE2.ajax.SimpleDataSource.prototype = {
    noop: function(data) {
        // do nothing
    },
    startRequest: function(paramStr) {
        var servlet = this.servletPath + this.servlet;
        YAHOO.util.Connect.asyncRequest('POST', servlet, this, paramStr);

    },
    xmlParser: new CARE2.util.JsFromXml,
    success: function(yahooResp) {
        var data;
        if(yahooResp.responseXML) {
            var xml = yahooResp.responseXML;
            try{
                xml.documentElement.normalize();
            }
            catch(e){}
            try{
                xml.firstChild.normalize();
            }
            catch(e){}

            data = this.xmlParser.parse(xml.documentElement||xml.firstChild);
        } else {
            data = yahooResp.responseText;
        }
        var scope = this.ini.scope?this.ini.scope:this;
        if(this.ini.handleSuccess) this.ini.handleSuccess.apply(scope, [data, yahooResp]);
    },
    failure: function(yahooResp) {
        var scope = this.ini.scope?this.ini.scope:this;
        if(this.ini.handleFailure) this.ini.handleFailure.apply(scope, [yahooResp]);
    },
    toQueryString: function(data, prefix) {
        var dataType = typeof data;

        if ((dataType == 'object') || (dataType == 'array')) {
            var chunks = [];
            var thisPrefix;
            for (var key in data) {
                if (typeof prefix == 'string') {
                    thisPrefix = prefix + '[' + key + ']';
                } else {
                    thisPrefix = key;
                }
                chunks.push(this.toQueryString(data[key], thisPrefix));
            }
            return chunks.join('&');
        } else {
            var name = escape(prefix);
            var value;
            if (dataType == 'boolean') {
                value = data? '1' : '0';
            } else {
                value = escape(data);
            }
            return name + '=' + value;
        }
    }
}

/**
 * HTML updater
 */
CARE2.ajax.HTMLDataSource = function (ini) {
    if(!ini) ini = {};
    if(ini.container) {
        ini.container = YAHOO.util.Dom.get(ini.container);
    } else {
        ini.container = document.createElement('div');
    }
    this.dataSource = new CARE2.ajax.SimpleDataSource(ini);
    this.dataSource.success = function(yahooResp) {
        this.ini.container.innerHTML = yahooResp.responseText;
      };
    if(ini.params) {
        this.startRequest(this.dataSource.toQueryString(ini.params));
    }
}
CARE2.ajax.HTMLDataSource.prototype = {
    toQueryString: function(data, prefix) {
        return this.dataSource.toQueryString(data, prefix);
    },
    startRequest: function(paramStr) {
        this.dataSource.startRequest(paramStr);
    }
}

/**
 * a periodically refreshing data source
 */
CARE2.ajax.PeriodicDataSource = function(ini) {
    this.dataSource = new CARE2.ajax.SimpleDataSource(ini);
    this.paramStr = ini.paramStr?ini.paramStr:'';

    // people supply interval in seconds
    var interval = parseInt(ini.interval) * 1000;
    this.interval = interval || 60000; // default to one minute

    this.iterations = 0;
    this.iterationLimit = parseInt(ini.iterationLimit);
}
CARE2.ajax.PeriodicDataSource.prototype = {
    startRequest: function(now) {
        if(now) this.sendRequest();
        var clo = this;
        this.repeater = window.setInterval(function() {
                clo.dataSource.startRequest(clo.paramStr);
                ++clo.iterations;
                if(clo.iterations == clo.iterationLimit) {
                    clo.stop();
                }
            }, this.interval);
    },
    stop: function() {
        if(this.repeater) {
            clearInterval(this.repeater);
            this.repeater = false;
        }
    }
}

/**
 * manipulate forms
 */
var ns = CARE2.namespace('dom', 'form');
ns.elements = ['submit', 'hidden', 'password', 'text', 'checkbox', 'radio', 'button', 'input'];
ns.wrap = function(el) {
        switch (el.type.toLowerCase()) {
          case 'hidden':
          case 'password':
          case 'text':
          case 'textarea':
            return new CARE2.dom.form.FormInput(el);
          case 'checkbox':
          case 'radio':
            return new CARE2.dom.form.OptionFormInput(el);
          case 'select':
          case 'select-one':
          case 'select-multiple':
            return new CARE2.dom.form.SelectFormInput(el);
          case 'button':
          case 'submit':
            // skip these
            return false;
        }
        return false;
    };

/** simple .value elements **/
ns.FormInput = function(el) {
    this.el = YAHOO.util.Dom.get(el);
}
ns.FormInput.prototype = {
    getValue: function() {
        return this.el.value;
    },
    setValue: function(value) {
        this.el.value = value;
    },
    isCollection: false,
    isMultivalued: function() {
        return false;
    }
}

/**
 * option elements (on or off)
 * get value doesn't get the value, it gets it if the input is active
 * set value doesn't set the value, it determines if the input is active
 */
ns.OptionFormInput = function(el) {
    this.el = YAHOO.util.Dom.get(el);
}
ns.OptionFormInput.prototype = {
    getValue: function() {
        return this.el.checked?this.el.value:false;
    },
    setValue: function(value) {
        if(!value) {
            this.el.checked = false;
        } else {
            this.el.checked = value == this.el.value;
        }
    },
    isCollection: false,
    isMultivalued: function() {
        return false;
    }
}

/** collection of option elements, which can be treated as one element **/
ns.FormInputCollection = function(els) {
    this.els = els || [];
}
ns.FormInputCollection.prototype = {
    add: function(formInput) {
        this.els.push(formInput);
    },
    getValue: function() {
        var c = this.els.length;
        var values = [];
        for(var i=0; i<c; ++i) {
            var value = this.els[i].getValue();
            if(value) {
                 values.push(value);
            }
        }
        if(values.length == 0) {
            return false;
        }
        return values;
    },
    setValue: function(value) {
        var c = this.els.length;
        for(var i=0; i<c; ++i) {
            this.els[i].setValue(value);
        }
    },
    isCollection: true,
    isMultivalued: function() {
        return true;
    }
}

/** selects, single or multiple */
ns.SelectFormInput = function(el) {
    this.el = YAHOO.util.Dom.get(el);
}
ns.SelectFormInput.prototype = {
    getValue: function() {
        if(!this.el.multiple) {
            return this.el.options[this.el.selectedIndex].value;
        }
        var value = [];
        var c = this.el.options.length;
        for(var i=0;i<c;++i) {
            var opt = this.el.options[i];
            if(opt.selected) {
                value.push(opt.value);
            }
        }
        if(value.length == 0) {
            return false;
        }
        return value;
    },
    setValue: function(value) {
        var c = this.el.options.length;
        for(var i=0;i<c;++i) {
            var opt = this.el.options[i];
            if(opt.value == value) {
                opt.selected = true;
                if(!this.el.multiple) {
                    break;
                }
            }
        }
    },
    isMultivalued: function() {
        return this.el.multiple;
    },
    isCollection: false

}

ns.FormManager = function(form, helper) {
    form = YAHOO.util.Dom.get(form);
    this.form = form;
    this.helper = helper || {};
    this.helper.formManager = this;
    this.valueNames = [];  // names for form data inputs
    this.valueElements = {}; // wrapped form data inputs (FormInput)
    var c = form.elements.length;
    for(var i=0; i<c; ++i) {
        var el = form.elements[i];
        var name = el.name;
        var wrap = CARE2.dom.form.wrap(el);
        if(wrap) {
            var current = this.valueElements[name];
            if(current) {
                if(current.isCollection) {
                    current.add(wrap);
                } else {
                    this.valueElements[name] = new CARE2.dom.form.FormInputCollection([current, wrap]);
                }
            } else {
                this.valueElements[name] = wrap;
                this.valueNames.push(name);
            }
        } else {
            // not a value element; submit, button, etc
            YAHOO.util.Event.addListener(el, 'click', this.handle, this, true);
        }
    }
    YAHOO.util.Event.addListener(form, 'submit', this.handle, this, true);
    if(!this.helper.defaultController) {
        this.helper.defaultController = this.noop;
    }

    // Add click handlers to image inputs, which don't show up in the form.elements
    // array for some reason
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'image') {
            YAHOO.util.Event.addListener(inputs[i], 'click', this.handle, this, true);
        }
    }

    var actions = form.getAttribute('action').split('/');
    var servlet = actions.pop();
    var ini = {
            name: form.name,
            servletPath: actions.join('/'),
            servlet: '/' + servlet,
            scope: this
    };

    if(this.helper.handleSuccess) {
        ini.handleSuccess = this.helper.handleSuccess;
    } else {
        ini.handleSuccess = this.handleSuccess;
    }
    if(this.helper.handleFailure) {
        ini.handleFailure = this.helper.handleFailure;
    } else {
        ini.handleFailure = this.handleFailure;
    }
    this.servlet = new CARE2.ajax.SimpleDataSource(ini);
    if(this.helper.initialize) {
        this.helper.initialize.apply(this, []);
    }
};

ns.FormManager.prototype = {
    handle: function(event, obj) {
        var el = YAHOO.util.Event.getTarget(event);
        if( this.helper.controllers[el.id] ) {
            this.helper.controllers[el.id].apply(this, [event]);
        } else {
            this.helper.defaultController.apply(this, [event]);
        }
        YAHOO.util.Event.stopEvent(event);
    },
    setController: function(el, ctr) {
        el = YAHOO.util.Dom.get(el);
        this.helper.controllers[el.id] = ctr;
    },
    setDefaultController: function(ctr) {
        this.helper.defaultController = ctr;
    },
    noop: function(event) {
        // do nothing
    },
    collectValues: function(collector) {
        var values = {};
        var c = this.valueNames.length;
        for(var i=0;i<c;++i) {
            var name = this.valueNames[i];
            var value = this.valueElements[name].getValue();
            // could be multivalued
            if(collector) {
                collector(name, value);
            } else {
                values[name] = value;
            }
        }
        return values;
    },
    getValue: function(name) {
        return this.valueElements[name].getValue();
    },
    setValue: function(name, value) {
        this.valueElements[name].setValue(value);
    },
    collectForURL: function() {
        var get = '';
        var clo = this;
        var collector = function(name, value) {
            if(value.join) {
                // multivalued array
                for(var i=0;i<value.length;++i) {
                    get = get + '&' + name + '=' + clo.escape(value[i]);
                }
            } else {
                get = get + '&' + name + '=' + clo.escape(value);
            }
        }
        this.collectValues(collector);
        return get;
    },
    /**
     * escape values
     * return '' for boolean false,
     * else url escape
     */
    escape: function(value) {
        if(value == false) {
            return '';
        }
        return escape(value);
    },
    handleSuccess: function(data, yahooResp) {
        // noop
    },
    handleFailure: function(yahooResp) {
        // noop
    }
}

/**
 * Object for preloading images on a page
 */
CARE2.util.ImagePreloader = function() {
    this.timeout = 30;

    this.addImage = function(url) {
        if ( (this.getState() != 'ready') || this._already(url) ) {
            return;
        }

        this._urls.push(url);
    };

    this.addImages = function(urls) {
        if (this.getState() != 'ready') {
            return;
        }

        for (var i = 0; i < urls.length; i++) {
            if (!this._already(urls[i])) {
                this._urls.push(urls[i]);
            }
        }
    };

    this.getState = function() {
        return this._state;
    };

    this.stateChanged = new YAHOO.util.CustomEvent('stateChanged', this);

    this.getAllDone = function() {
        return this._allDone;
    }

    this.load = function() {
        this._nImages = this._urls.length;
        this._nImagesDone = 0;

        this._setState('loading');

        if (this.timeout > 0) {
            this._timeoutID = setTimeout(this._giveUp, Math.round(this.timeout * 1000));
        }

        for (i = 0; i < this._nImages; i++) {
            var img = new Image();
            YAHOO.util.Event.addListener(img, 'load', this._imageLoaded, this);
            img.src = this._urls[i];
        }
    };

    this.getUrls = function() {
        var urls = [];
        for (var i = 0; i < this._urls.length; i++) {
            urls[i] = this._urls[i];
        }
        return urls;
    };

    this._setState = function(newState) {
        this._state = newState;
        this.stateChanged.fire();
    };

    this._already = function(url) {
        for(var i = 0; i < this._urls.length; i++) {
            if(this._urls[i] == url) {
                return true;
            }
        }

        return false;
    };

    // We need kludgy scoping, since this is called via setTimeout
    var _me = this;
    this._giveUp = function() {
        _me._setState('done');
    };

    this._imageLoaded = function(e, obj) {
        _me._nImagesDone++;

        if (_me._nImagesDone == _me._nImages) {
            clearTimeout(_me._timeoutID);
            _me._allDone = true;
            _me._setState('done');
        }
    }

    this._urls = [];
    this._state = 'ready';
    this._allDone = false;
}

CARE2.util.numberFormat = function(number, decimals, decPoint, thousandsSep) {
    if (typeof number != 'number') {
        number = parseFloat(number);
    }
    if (typeof decimals == 'undefined') {
        decimals = false;
    }
    if (typeof decPoint == 'undefined') {
        decPoint = '.';
    }
    if (typeof thousnadsSep == 'undefined') {
        thousandsSep = ',';
    }

    var negative = (number < 0);
    number = Math.abs(number);
    var intPart = Math.floor(number);
    var fraction = number - intPart;

    string = '';

    intChunks = [];
    while (intPart >= 1000) {
        mod = intPart % 1000;
        intPart = (intPart - mod) / 1000;

        if (mod < 10) {
            intChunks.unshift('00' + mod);
        } else if (mod < 100) {
            intChunks.unshift('0' + mod);
        } else {
            intChunks.unshift('' + mod);
        }
    }
    intChunks.unshift(intPart);
    string = intChunks.join(thousandsSep);

    if (decimals == false) {
        if (fraction > 0) {
            decStr = '' + fraction;
            string += decPoint + decStr.substring(2);
        }
    } else if (decimals > 0) {
        var factor = Math.pow(10, decimals);
        var magicString = (factor + (factor * fraction)).toString();
        string += decPoint + magicString.substr(1, decimals);
    }

    return negative? '-' + string : string;
}

/**
 * Convert special characters to HTML entities.
 * Mimics this: http://www.php.net/htmlspecialchars
 * quote styles: ENT_COMPAT (default) converts double quotes, and leaves single quotes alone.
 *               ENT_QUOTES converts both double and single quotes.
 *               ENT_NOQUOTES converts no quotes.
 */
CARE2.util.htmlspecialchars = function(string, quote_style) {
    if (typeof quote_style == 'undefined') {
        quote_style = 'ENT_COMPAT';
    }

    string = string.replace(/\&/, "&amp;");
    string = string.replace(/\</, "&lt;");
    string = string.replace(/\>/, "&gt;");

    if (quote_style != 'ENT_NOQUOTES') {
        if (quote_style == 'ENT_QUOTES') {
            string = string.replace(/'/, "&#039;");
        }
        string = string.replace(/"/, "&quot;");
    }
    return string;
}


/**
 * Convert special HTML entities back to characters.
 * Mimics this: http://www.php.net/manual/en/function.htmlspecialchars-decode.php
 * quote styles: ENT_COMPAT (default) converts double quotes, and leaves single quotes alone.
 *               ENT_QUOTES converts both double and single quotes.
 *               ENT_NOQUOTES converts no quotes.
 */
CARE2.util.htmlspecialchars_decode = function(string, quote_style) {
    if (typeof quote_style == 'undefined') {
        quote_style = 'ENT_COMPAT';
    }

    string = string.replace(/\&amp;/, "&");
    string = string.replace(/\&lt;/, "<");
    string = string.replace(/\&gt;/, ">");

    if (quote_style != 'ENT_NOQUOTES') {
        if (quote_style == 'ENT_QUOTES') {
            string = string.replace(/\&#039;/, "'");
        }
        string = string.replace(/\&quot;/, "\"");
    }
    return string;
}


// Flash Player Version Detection - Rev 1.5.hacked - wrapped in an object, for namespace goodness
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
//
// See http://www.adobe.com/products/flashplayer/download/detection_kit/
//

CARE2.util.FlashDetect = {
    isIE: (navigator.appVersion.indexOf("MSIE") != -1) ? true : false,
    isWin: (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false,
    isOpera: (navigator.userAgent.indexOf("Opera") != -1) ? true : false,

    ControlVersion: function() {
        var version;
        var axo;
        var e;

        // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

        try {
            // version will be set for 7.X or greater players
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
            version = axo.GetVariable("$version");
        } catch (e) {
        }

        if (!version)
        {
            try {
                // version will be set for 6.X players only
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

                // installed player is some revision of 6.0
                // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
                // so we have to be careful.

                // default to the first public version
                version = "WIN 6,0,21,0";

                // throws if AllowScripAccess does not exist (introduced in 6.0r47)
                axo.AllowScriptAccess = "always";

                // safe to call for 6.0r47 or greater
                version = axo.GetVariable("$version");

            } catch (e) {
            }
        }

        if (!version)
        {
            try {
                // version will be set for 4.X or 5.X player
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
                version = axo.GetVariable("$version");
            } catch (e) {
            }
        }

        if (!version)
        {
            try {
                // version will be set for 3.X player
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
                version = "WIN 3,0,18,0";
            } catch (e) {
            }
        }

        if (!version)
        {
            try {
                // version will be set for 2.X player
                axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                version = "WIN 2,0,0,11";
            } catch (e) {
                version = -1;
            }
        }

        return version;
    },

    // JavaScript helper required to detect Flash Player PlugIn version information
    GetSwfVer: function() {
        // NS/Opera version >= 3 check for Flash plugin in plugin array
        var flashVer = -1;

        if (navigator.plugins != null && navigator.plugins.length > 0) {
            if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
                var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
                var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
                var descArray = flashDescription.split(" ");
                var tempArrayMajor = descArray[2].split(".");
                var versionMajor = tempArrayMajor[0];
                var versionMinor = tempArrayMajor[1];
                if ( descArray[3] != "" ) {
                    tempArrayMinor = descArray[3].split("r");
                } else {
                    tempArrayMinor = descArray[4].split("r");
                }
                var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
                var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
            }
        }
        // MSN/WebTV 2.6 supports Flash 4
        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
        // WebTV 2.5 supports Flash 3
        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
        // older WebTV supports Flash 2
        else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
        else if ( CARE2.util.FlashDetect.isIE && CARE2.util.FlashDetect.isWin && !CARE2.util.FlashDetect.isOpera ) {
            flashVer = CARE2.util.FlashDetect.ControlVersion();
        }
        return flashVer;
    },

    // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
    DetectFlashVer: function(reqMajorVer, reqMinorVer, reqRevision) {
        versionStr = CARE2.util.FlashDetect.GetSwfVer();
        if (versionStr == -1 ) {
            return false;
        } else if (versionStr != 0) {
            if(CARE2.util.FlashDetect.isIE && CARE2.util.FlashDetect.isWin && !CARE2.util.FlashDetect.isOpera) {
                // Given "WIN 2,0,0,11"
                tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
                tempString        = tempArray[1];			// "2,0,0,11"
                versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
            } else {
                versionArray      = versionStr.split(".");
            }
            var versionMajor      = versionArray[0];
            var versionMinor      = versionArray[1];
            var versionRevision   = versionArray[2];

                // is the major.revision >= requested major.revision AND the minor version >= requested minor
            if (versionMajor > parseFloat(reqMajorVer)) {
                return true;
            } else if (versionMajor == parseFloat(reqMajorVer)) {
                if (versionMinor > parseFloat(reqMinorVer))
                    return true;
                else if (versionMinor == parseFloat(reqMinorVer)) {
                    if (versionRevision >= parseFloat(reqRevision))
                        return true;
                }
            }
            return false;
        }
    },

    AC_AddExtension: function(src, ext) {
      if (src.indexOf('?') != -1)
        return src.replace(/\?/, ext+'?');
      else
        return src + ext;
    },

    AC_Generateobj: function(objAttrs, params, embedAttrs) {
        var str = '';
        if (CARE2.util.FlashDetect.isIE && CARE2.util.FlashDetect.isWin && !CARE2.util.FlashDetect.isOpera) {
            str += '<object ';
            for (var i in objAttrs)
                str += i + '="' + objAttrs[i] + '" ';
            for (var i in params)
                str += '><param name="' + i + '" value="' + params[i] + '" /> ';
            str += '></object>';
        } else {
            str += '<embed ';
            for (var i in embedAttrs)
                str += i + '="' + embedAttrs[i] + '" ';
            str += '> </embed>';
        }

        // XXX: This will blow up if called after pageload is done!
        document.write(str);
    },

    AC_FL_RunContent: function() {
      var ret =
        CARE2.util.FlashDetect.AC_GetArgs
        (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
         , "application/x-shockwave-flash"
        );
      CARE2.util.FlashDetect.AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
    },

    AC_GetArgs: function(args, ext, srcParamName, classid, mimeType){
      var ret = new Object();
      ret.embedAttrs = new Object();
      ret.params = new Object();
      ret.objAttrs = new Object();
      for (var i=0; i < args.length; i=i+2){
        var currArg = args[i].toLowerCase();

        switch (currArg){
          case "classid":
            break;
          case "pluginspage":
            ret.embedAttrs[args[i]] = args[i+1];
            break;
          case "src":
          case "movie":
            args[i+1] = CARE2.util.FlashDetect.AC_AddExtension(args[i+1], ext);
            ret.embedAttrs["src"] = args[i+1];
            ret.params[srcParamName] = args[i+1];
            break;
          case "onafterupdate":
          case "onbeforeupdate":
          case "onblur":
          case "oncellchange":
          case "onclick":
          case "ondblClick":
          case "ondrag":
          case "ondragend":
          case "ondragenter":
          case "ondragleave":
          case "ondragover":
          case "ondrop":
          case "onfinish":
          case "onfocus":
          case "onhelp":
          case "onmousedown":
          case "onmouseup":
          case "onmouseover":
          case "onmousemove":
          case "onmouseout":
          case "onkeypress":
          case "onkeydown":
          case "onkeyup":
          case "onload":
          case "onlosecapture":
          case "onpropertychange":
          case "onreadystatechange":
          case "onrowsdelete":
          case "onrowenter":
          case "onrowexit":
          case "onrowsinserted":
          case "onstart":
          case "onscroll":
          case "onbeforeeditfocus":
          case "onactivate":
          case "onbeforedeactivate":
          case "ondeactivate":
          case "type":
          case "codebase":
          case "id":
            ret.objAttrs[args[i]] = args[i+1];
            break;
          case "width":
          case "height":
          case "align":
          case "vspace":
          case "hspace":
          case "class":
          case "title":
          case "accesskey":
          case "name":
          case "tabindex":
            ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
            break;
          default:
            ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
        }
      }
      ret.objAttrs["classid"] = classid;
      if (mimeType) ret.embedAttrs["type"] = mimeType;
      return ret;
    }
};

function blert(stuff) {
    var pre = document.createElement('pre');
    pre.innerHTML = stuff;
    document.body.appendChild(pre);
}

/**
 * AJAX email checker with cookie-based caching
 *
 * @param callback Function to be called once we know how many messages the user has
 * @param int secondsUntilStale how old can the cache get before we refresh it with another AJAX request
 * @param bool getPMCount Should we also fetch a count of personal messages?
 *
 * The callback function should accept one integer argument for the number of emails the current
 * user has, unless getPMCount is true, in which case, it should accept a second integer argument
 * for the number of unread personal messages
 */
CARE2.util.checkMail = function(callback, secondsUntilStale, getPMCount) {
    var jar = new CARE2.util.CookieJar();
    var mailCookie = jar.get('c2mc');
    var tsNow = CARE2.util.unixTimestamp();

    if (typeof getPMCount == 'undefined') {
        getPMCount = false;
    }

    // See if we're even supposed to use the cookie
    var useCookie = (typeof secondsUntilStale != 'undefined') && (secondsUntilStale > 0);

    // See if we even have a cookie
    if ( useCookie && (typeof mailCookie != 'undefined') && mailCookie ) {

        // Try and parse the cookie
        var cookieArr = mailCookie.split('-');
        if (cookieArr.length == 4) {
            var passportID = parseInt(cookieArr[0]);
            var tsUpdated = parseInt(cookieArr[1]);
            var nEmails = cookieArr[2];
            var nPersonalMessages = cookieArr[3];
            var tsExpires = tsUpdated + secondsUntilStale;

            // See if the cookie's for this user, and has been updated recently enough
            if ( (tsExpires > tsNow) && CARE2.user && (passportID == CARE2.user.passportID) ) {

                // Cleared all the hoops? Run the callback on the cached count(s).
                if (getPMCount) {
                    callback(nEmails, nPersonalMessages);
                } else {
                    callback(nEmails);
                }
                return;
            } else {
                //blert("cookie is expired!");
            }
        } else {
            //blert("cookie '" + mailCookie + "' isn't valid!");
        }
    } else {
        //blert("no cookie!");
    }

    // No (valid) cached count? kick off an AJAX call to fetch the "real" count and cache
    // and return the result once the call comes back.
    //
    // Note that we always ask for the PM count, even if this particular run of checkMail
    // call doesn't need it, so that we can make sure the cache has the correct figure in
    // case the next checkMail call does want the PM count
    YAHOO.util.Connect.asyncRequest("GET", "/servlets/check_mail.php?get_personal_messages=1", {
        timeout: 15000,
        success: function (resp) {
            // Good response from the server? Cache as a cookie and run callback
            // We have to use a regex, instead of just presuming the response consists of the
            // two numbers we asked for, because various other code sticks crap on the end
            var matches = /^\s*(\d+)\s+(\d+)/.exec(resp.responseText);

            // We only cache if we got a valid response
            if (matches && CARE2.user) {
                var nEmails = matches[1];
                var nPersonalMessages = matches[2];
                var tsNow = CARE2.util.unixTimestamp();

                if (useCookie) {
                    var jar = new CARE2.util.CookieJar();
                    var cookieText = CARE2.user.passportID + '-' + tsNow + '-'
                                   + nEmails + '-' + nPersonalMessages;
                    jar.set('c2mc', cookieText, 'path=/');
                }
            } else {
                var nEmails = 0;
                var nPersonalMessages = 0;
            }

            if (getPMCount) {
                callback(nEmails, nPersonalMessages);
            } else {
                callback(nEmails);
            }
        },
        failure: function (resp) {
            // Bad response? Run call back for zero messages, but don't cache
            if (getPMCount) {
                callback(0, 0);
            } else {
                callback(0);
            }
        }
    });
};

CARE2.util.unixTimestamp = function(d) {
    if (typeof d == 'undefined') {
        d = new Date();
    }

    ms = d.getTime();
    return Math.round(ms / 1000);
};

Care2.ajax.objectToQueryString = function(obj, paramName) {
    if (typeof paramName == 'undefined') {
        var params = Care2.ajax.objectToQueryParams(obj);
    } else {
        var params = Care2.ajax.objectToQueryParams(obj, escape(paramName));
    }
    return params.join('&');
};
Care2.ajax.objectToQueryParams = function(obj, prefix) {
    var params = [];
    var keyPrefix;

    if (typeof prefix == 'undefined') {
        prefix = '';
    }

    for (var key in obj) {
        if (prefix == '') {
            keyPrefix = escape(key);
        } else {
            keyPrefix = prefix + '[' + escape(key) + ']';
        }

        switch (typeof obj[key]) {
            case 'number':
            case 'string':
                // scalars are easy
                params.push(keyPrefix + '=' + escape(obj[key]));
                break;

            case 'boolean':
                // booleans need some processing
                params.push(keyPrefix + '=' + (obj[key]? '1' : '0'));
                break;

            case 'object':
                // recurse on objects
                var these_params = Care2.ajax.objectToQueryParams(obj[key], keyPrefix);
                params = params.concat(these_params);
                break;

            default:
                // skip all others
                break;
        }
    }

    return params;
};

/**
 * Allow one-liner Ajax requests
 *
 * The provided callback is passed the result of the AJAX request as its first argument, and
 * a helper object with the following public members as its second:
 *   - requestUrl: string; the URL the AJAX request ran against
 *   - requestParams: string; the paramater string sent along with the AJAX request
 *   - finished: bool; whether or not the AJAX request has come back yet
 *   - succeeded: bool; whether or not the AJAX request was successful
 *   - yahooResponse: object; the response handed back by the YUI AJAX library
 *   - simpleDataSource: object; the Care2 SimpleDataSource object that wrapped this request
 *
 * @param string requestUrl The URL the AJAX request should be made against
 * @param mixed requestParams Paramater string, or object to be translated into a parameter string
 * @param function callback The callback function which should run when the request comes back
 * @param object callbackScope Option scope against which the callback function should be run
 * @param object args Doesn't do anything yet; may eventually allow finer-grained control
 */
Care2.ajax.simpleRequest = function(requestUrl, requestParams, callback, callbackScope, args) {

    var helper = new Care2.ajax._simpleRequestHelper(
        requestUrl, requestParams, callback, callbackScope, args);

    helper.exec();
};

Care2.ajax._simpleRequestHelper =
        function(requestUrl, requestParams, callback, callbackScope, args) {

    this.requestUrl = requestUrl;

    if (typeof(requestParams) == 'object') {
        this.requestParams = Care2.ajax.objectToQueryString(requestParams);
    } else if (typeof(requestParams) == 'string') {
        this.requestParams = requestParams;
    } else {
        this.requestParams = '';
    }

    this._callback = (typeof callback == 'undefined')? false : callback;
    this._callbackScope = (typeof callbackScope == 'undefined')? null : callbackScope;

    this.finished = false;
};
Care2.ajax._simpleRequestHelper.prototype = {
    exec: function() {
        var dataSourceSpec = {
            name: 'simpleRequest',
            scope: this,

            // XXX: ugly hack to avoid annoying default behavior on empty servletPath argument
            servletPath: this.requestUrl.substr(0, 1),
            servlet: this.requestUrl.substr(1),

            handleSuccess: this._handleSuccess,
            handleFailure: this._handleFailure
        };

        this.simpleDataSource = new Care2.ajax.SimpleDataSource(dataSourceSpec);
        this.simpleDataSource.startRequest(this.requestParams);
    },

    _handleSuccess: function(data, yahooResp) {
        this.finished = true;
        this.succeeded = true;
        this.yahooResponse = yahooResp;

        this._runCallback(data);
    },

    _handleFailure: function(yahooResp) {
        this.finished = true;
        this.succeeded = false;
        this.yahooResponse = yahooResp;

        this._runCallback(false);
    },

    _runCallback: function(result) {
        if (this._callback) {
            this._callback.apply(this._callbackScope, [result, this]);
        }
    }
}


function blert(stuff) {
    var pre = document.createElement('pre');
    pre.innerHTML = stuff;
    document.body.appendChild(pre);
}

function blert_r(stuff, depth) {
    if (typeof depth == 'undefined') {
        depth = 1;
    }

    crap = '';
    for (var key in stuff) {
        crap += key + ": " + typeof(stuff[key]) + "\n";
    }

    blert(crap);
}

CARE2.watermark = {
    add:function(e,el){
        if(el.value == ""){
            el.style.cssText = "";
        }else{
            this.remove(e,el);
        }
    },
    remove:function(e,el){
        el.style.cssText = "background-image: none";
    },
    init:function(d){
        d=$(d);
        CARE2.addListener(d,'blur',this.add,d,this);
        CARE2.addListener(d,'focus',this.remove,d,this);
    }
}

/*********************************************************************************************
    JS for the navbar/footer
**/

var memberRollover=CARE2.about_rollover({rightLimit:'care2_wrapper'});


YAHOO.util.Event.onDOMReady(function(){
    CARE2.bodyReady=true;
});

CARE2.searchTabs = {
    init:function(wrapper, func) {
        this.func = func;
        this.wrapper = $(wrapper);
        var a = this.wrapper.getElementsByTagName('a');

        for(var l,i=0;l=a[i];i++){
            CARE2.addListener(l, 'click', func, this, false, true);
        }
    }
}

CARE2.domReady(function(){
    CARE2.watermark.init('care2MainSearchQuery');
    CARE2.searchTabs.init('care2_search_tabs', function(e,obj) {
        this.blur();
        var a = obj.wrapper.getElementsByTagName('li');
        for(var l,i=0;l=a[i];i++)l.className="";
        this.parentNode.className="active";
        $('care2MainSearchParameter').value=this.className.replace('search_tabs_','');
    });
},{'care2_search_tabs':'id'});

CARE2.footerFlies=function(){
    var _self=this;
    var obj={
        swfId:'footerbutterflies',
        frogswf:"http://dingo.care2.com/c2/swf/footer_frog.swf",
        frogswfId:'footerfrog',
        frogWrapper:_self.buildElement('div',{style:{position:'absolute'}}),
        width:75,
        height:78,
        frogwidth:420,
        frogheight:150,
        intvl:false,
        mouseOver:function(e,obj){
            obj.top=CARE2.getElementPosition($('care2_footer')).top+$('care2_footer').offsetHeight-obj.height-23;
            obj.left=CARE2.getElementPosition($('care2_footer')).left+$('care2_footer').offsetWidth-obj.width-10;
            CARE2.appendToBody(obj.frogWrapper);
            obj.frogWrapper.appendChild(CARE2.buildElement('div',{id:obj.frogswfId}));
            obj.frogWrapper.style.top=(obj.top-50)+"px";
            obj.frogWrapper.style.left=(obj.left-obj.frogwidth+obj.width+10)+"px";
            swfobject.embedSWF(obj.frogswf, obj.frogswfId, obj.frogwidth, obj.frogheight, "6.0.0", "expressInstall.swf", false, {wMode:'transparent'});
            setTimeout(function(){
                obj.frogWrapper.removeChild(obj.frogWrapper.firstChild);
                obj.frogWrapper.parentNode.removeChild(obj.frogWrapper);
            },5000);
        }
    }

    obj.wrapper=$(obj.swfId+'_wrapper');

    _self.addListener(obj.wrapper,"mouseover",obj.mouseOver,obj);

    return obj;
}

CARE2.domReady(function(){CARE2.footerFlies()},{'footerbutterflies_wrapper':'id'});

//////////////////////////////
// Added in for Easter Eggs //
//////////////////////////////
CARE2.easterEggs = [];

CARE2.addEasterEggCallback = function (callback)
{
    CARE2.easterEggs[CARE2.easterEggs.length] = callback;
}

CARE2.easterEggCallback = function ()
{
    for (var i=0; i<CARE2.easterEggs.length; i++)
    {
        CARE2.easterEggs[i]();
    }
}

CARE2.captureKeys = function (ev) {
    var ev = window.event || ev;             // gets the event in ie or ns
    kCode = ev.keyCode || ev.which;   // gets the keycode in ie or ns
    // alert(kCode); // debug

    if (ev.ctrlKey && ev.altKey && kCode == 101) { // ctrl+alt+e
        alert("Care2 Easter Eggs Enabled!");
        CARE2.easterEggCallback(); // or whatever you call your function
        return false;  // now make the browser ignore the key combo
    }
}

/*
    Sample Usage:

    var easterEggHandle = function () {
        // Your code here
    };
    var easterEggHandle2 = function () {
        // Your code here
    };
    CARE2.addEasterEggCallback(easterEggHandle);
    CARE2.addEasterEggCallback(easterEggHandle2);
    CARE2.addListener(window, 'load', function () { document.onkeypress=CARE2.captureKeys; } );
*/

////////////////////////
// End of Easter Eggs //
////////////////////////

CARE2.domReady(function(){CARE2.footerFlies()},{'footerbutterflies_wrapper':'id'});

CARE2.myCare2Tab = function(){
    var obj = {
        tab: $('mycare2tab'),
        drop: $('mycare2tab_drop'),
        zIndex: 10,
        hovering: false,
        mouseOver:function(e, skipShowing){
            var _self = this;
            CARE2.addClassName(_self.tab, "mycare2tab_hover");
            _self.hovering = true;
            if(!skipShowing.show){
                setTimeout(function(){
                    _self.showMenu();
                },5);
            }
        },
        mouseOut:function(e, obj){
            obj.hovering = false;
            setTimeout(function(){
                if(!obj.hovering) obj.hideMenu();
            },100);
        },
        showMenu: function(){
            var _self = this;
            this.position = CARE2.getElementPosition(this.tab);
            this.position.top += this.tab.offsetHeight;
            if(CARE2.isIE) {
                obj.position.top -= 2;
                obj.position.left -= 2;
            }
            this.drop.style.visibility = "visible";
            this.drop.style.zIndex = _self.zIndex;
            this.drop.style.top = _self.position.top+"px";
            this.drop.style.left = _self.position.left+"px";
            this.drop.style.width = _self.width+"px";
            this.drop.style.height = _self.height+"px";
            CARE2.flashFix();
            CARE2.iFrame({
                zIndex:_self.zIndex-1,
                top:_self.position.top+"px",
                left:_self.position.left+"px",
                width:_self.width+"px",
                height:_self.height+"px"
            });
        },
        hideMenu: function(skipFixes){
            var _self = this;
            CARE2.removeClassName(_self.tab, "mycare2tab_hover");
            _self.drop.style.visibility = "hidden";
            _self.drop.style.width = _self.drop.style.height = _self.drop.style.top = _self.drop.style.left = 0;
            if(!skipFixes){
                CARE2.flashFix('visible');
                CARE2.iFrame();
            }
        }
    }
    obj.position = CARE2.getElementPosition(obj.tab);
    obj.position.top += obj.tab.offsetHeight;
    obj.width = obj.drop.offsetWidth;
    obj.height = obj.drop.offsetHeight;

    obj.drop.parentNode.removeChild(obj.drop);
    obj.hideMenu(true);
    obj.drop.style.position = "absolute";
    CARE2.appendToBody(obj.drop);

    CARE2.addListener(obj.tab, 'mouseover', obj.mouseOver, {show:false}, obj);
    CARE2.addListener(obj.tab, 'mouseout', obj.mouseOut, obj);
    CARE2.addListener(obj.drop, 'mouseover', obj.mouseOver, {show:true}, obj);
    CARE2.addListener(obj.drop, 'mouseout', obj.mouseOut, obj);

    return obj;
}

CARE2.domReady(CARE2.myCare2Tab,{'mycare2tab_drop':'id'});

CARE2.menuNavRendered=false;
CARE2.menuNav=function(){
    if(!CARE2.menuNavRendered){
        CARE2.menuNavRendered=true;
    	var obj={
    		hover:false,
    		dropWin:false,
    		dropWins:{},
    		li:$('care2_main_nav').getElementsByTagName('ul')[0].getElementsByTagName('li'),
    		hotspot_over:function(e,obj){
                this.className="hotspot_hover";
                if(CARE2.isIE){
                    this.parentNode.ref=this.parentNode.href;
                    this.parentNode.href="javascript:";
                }
    		},
    		hotspot_out:function(e,obj){
                if(CARE2.isIE) this.parentNode.href=this.parentNode.ref;
                obj.hover=false;
                var _self=this;
                _self.className="hotspot";
                setTimeout(function(){
                    if(obj.hover!=_self.parentNode.parentNode.className)_self.parentNode.className="";
                    if(!obj.hover){
                        _self.parentNode.className="";
                        obj.dropWin.style.visibility="hidden";
                        obj.dropWin.style.width=obj.dropWin.style.top=obj.dropWin.style.left=0;
                        obj.dropWin.style.height="auto";
                        obj.dropWin.className="";
                        obj.fixIE(true);
                    }
                },500);
    		},
    		hotspot_click:function(e,obj){
                this.parentNode.blur();
    		    if(obj.dropWin.className.indexOf('care2_dropdown_'+this.parentNode.parentNode.className) < 0) {
                    obj.hover=this.parentNode.parentNode.className;
                    var _self=this;
                    var x = obj.hover;
                    obj.dropWin.innerHTML="";
                    _self.parentNode.className="hover";
                    if(CARE2.isIE) {
                        obj.dropWin.innerHTML = obj.dropWins[obj.hover].outerHTML;
                    }else{
                        obj.dropWin.appendChild(obj.dropWins[obj.hover]);
                    }

                    CARE2.addListener([obj.dropWin,_self.parentNode],'mouseover',obj.dropwin_mouseover,x,obj);
                    CARE2.addListener([obj.dropWin,_self.parentNode],'mouseout',obj.hotspot_out,obj,_self);

                    obj.dropWin.style.visibility="hidden";
                    obj.dropWin.style.top = (CARE2.getElementPosition(_self.parentNode).top+_self.parentNode.offsetHeight)+"px";
                    obj.dropWin.style.left = (CARE2.getElementPosition(_self.parentNode).left)+"px";
                    obj.dropWin.style.width = _self.parentNode.offsetWidth+"px";
                    obj.dropWin.className = 'care2_dropdown_'+obj.hover;

                    CARE2.expand({expdiv:obj.dropWin,_oncomplete:obj.fixIE});
                }
    		},
    		dropwin_mouseover:function(e,x){
    		    this.hover=x;
    		}
    	}

        if(!CARE2.loggedIn()) swfobject.createCSS("#care2_dropdown .members_only", "display: none;");

    	obj.fixIE=function(killFrame){
    	    if(CARE2.isIE){
    	        if(killFrame||!obj.dropWin){
    	            CARE2.iFrame();
    	        }else{
    	            CARE2.iFrame({
    	                zIndex:49,
    	                left:obj.dropWin.style.left,
    	                top:obj.dropWin.style.top,
    	                width:obj.dropWin.style.width,
    	                height:obj.dropWin.style.height
    	            },true);
    	        }
    	    }
    	    CARE2.flashFix((killFrame)?'visible':false);
    	}

    	obj.dropWin=CARE2.buildElement('div',{
    	    id:'care2_dropdown',
    	    style:{visibility:"hidden",height:"auto"}
    	});
    	obj.dropWin.style.width=obj.dropWin.style.top=obj.dropWin.style.left=0;
    	CARE2.appendToBody(obj.dropWin);

    	for(var l,i=0;l=obj.li[i];i++){
    		if($('dropdown_data_'+l.className)){
    		    obj.dropWins[l.className]=$('dropdown_data_'+l.className);
    			var a=l.getElementsByTagName('a')[0];
    			a.appendChild(sp=CARE2.buildElement('span',{className:'hotspot'}));
    			CARE2.addListener(sp,'mouseover',obj.hotspot_over,obj);
    			CARE2.addListener(sp,'mouseout',obj.hotspot_out,obj);
    			CARE2.addListener(sp,'click',obj.hotspot_click,obj,false,true);
    		}
    	}
    }
}
}
