

//prototype.js
var Prototype={Version:'1.6.0.2',Browser:{IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,Gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1,MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:document.createElement('div').__proto__&&document.createElement('div').__proto__!==document.createElement('form').__proto__},ScriptFragment:'<script[^>]*>([\\S\\s]*?)<\/script>',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}};if(Prototype.Browser.MobileSafari)Prototype.BrowserFeatures.SpecificElementExtensions=false;var Class={create:function(){var a=null,properties=$A(arguments);if(Object.isFunction(properties[0]))a=properties.shift();function klass(){this.initialize.apply(this,arguments)}Object.extend(klass,Class.Methods);klass.superclass=a;klass.subclasses=[];if(a){var b=function(){};b.prototype=a.prototype;klass.prototype=new b;a.subclasses.push(klass)}for(var i=0;i<properties.length;i++)klass.addMethods(properties[i]);if(!klass.prototype.initialize)klass.prototype.initialize=Prototype.emptyFunction;klass.prototype.constructor=klass;return klass}};Class.Methods={addMethods:function(a){var b=this.superclass&&this.superclass.prototype;var c=Object.keys(a);if(!Object.keys({toString:true}).length)c.push("toString","valueOf");for(var i=0,length=c.length;i<length;i++){var d=c[i],value=a[d];if(b&&Object.isFunction(value)&&value.argumentNames().first()=="$super"){var e=value,value=Object.extend((function(m){return function(){return b[m].apply(this,arguments)}})(d).wrap(e),{valueOf:function(){return e},toString:function(){return e.toString()}})}this.prototype[d]=value}return this}};var Abstract={};Object.extend=function(a,b){for(var c in b)a[c]=b[c];return a};Object.extend(Object,{inspect:function(a){try{if(Object.isUndefined(a))return'undefined';if(a===null)return'null';return a.inspect?a.inspect():String(a)}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(a){var b=typeof a;switch(b){case'undefined':case'function':case'unknown':return;case'boolean':return a.toString()}if(a===null)return'null';if(a.toJSON)return a.toJSON();if(Object.isElement(a))return;var c=[];for(var d in a){var e=Object.toJSON(a[d]);if(!Object.isUndefined(e))c.push(d.toJSON()+': '+e)}return'{'+c.join(', ')+'}'},toQueryString:function(a){return $H(a).toQueryString()},toHTML:function(a){return a&&a.toHTML?a.toHTML():String.interpret(a)},keys:function(a){var b=[];for(var c in a)b.push(c);return b},values:function(a){var b=[];for(var c in a)b.push(a[c]);return b},clone:function(a){return Object.extend({},a)},isElement:function(a){return a&&a.nodeType==1},isArray:function(a){return a!=null&&typeof a=="object"&&'splice'in a&&'join'in a},isHash:function(a){return a instanceof Hash},isFunction:function(a){return typeof a=="function"},isString:function(a){return typeof a=="string"},isNumber:function(a){return typeof a=="number"},isUndefined:function(a){return typeof a=="undefined"}});Object.extend(Function.prototype,{argumentNames:function(){var a=this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");return a.length==1&&!a[0]?[]:a},bind:function(){if(arguments.length<2&&Object.isUndefined(arguments[0]))return this;var a=this,args=$A(arguments),object=args.shift();return function(){return a.apply(object,args.concat($A(arguments)))}},bindAsEventListener:function(){var b=this,args=$A(arguments),object=args.shift();return function(a){return b.apply(object,[a||window.event].concat(args))}},curry:function(){if(!arguments.length)return this;var a=this,args=$A(arguments);return function(){return a.apply(this,args.concat($A(arguments)))}},delay:function(){var a=this,args=$A(arguments),timeout=args.shift()*1000;return window.setTimeout(function(){return a.apply(a,args)},timeout)},wrap:function(a){var b=this;return function(){return a.apply(this,[b.bind(this)].concat($A(arguments)))}},methodize:function(){if(this._methodized)return this._methodized;var a=this;return this._methodized=function(){return a.apply(null,[this].concat($A(arguments)))}}});Function.prototype.defer=Function.prototype.delay.curry(0.01);Date.prototype.toJSON=function(){return'"'+this.getUTCFullYear()+'-'+(this.getUTCMonth()+1).toPaddedString(2)+'-'+this.getUTCDate().toPaddedString(2)+'T'+this.getUTCHours().toPaddedString(2)+':'+this.getUTCMinutes().toPaddedString(2)+':'+this.getUTCSeconds().toPaddedString(2)+'Z"'};var Try={these:function(){var a;for(var i=0,length=arguments.length;i<length;i++){var b=arguments[i];try{a=b();break}catch(e){}}return a}};RegExp.prototype.match=RegExp.prototype.test;RegExp.escape=function(a){return String(a).replace(/([.*+?^=!:${}()|[\]\/\\])/g,'\\$1')};var PeriodicalExecuter=Class.create({initialize:function(a,b){this.callback=a;this.frequency=b;this.currentlyExecuting=false;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000)},execute:function(){this.callback(this)},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.execute()}finally{this.currentlyExecuting=false}}}});Object.extend(String,{interpret:function(a){return a==null?'':String(a)},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(a,b){var c='',source=this,match;b=arguments.callee.prepareReplacement(b);while(source.length>0){if(match=source.match(a)){c+=source.slice(0,match.index);c+=String.interpret(b(match));source=source.slice(match.index+match[0].length)}else{c+=source,source=''}}return c},sub:function(b,c,d){c=this.gsub.prepareReplacement(c);d=Object.isUndefined(d)?1:d;return this.gsub(b,function(a){if(--d<0)return a[0];return c(a)})},scan:function(a,b){this.gsub(a,b);return String(this)},truncate:function(a,b){a=a||30;b=Object.isUndefined(b)?'...':b;return this.length>a?this.slice(0,a-b.length)+b:String(this)},strip:function(){return this.replace(/^\s+/,'').replace(/\s+$/,'')},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,'')},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'')},extractScripts:function(){var b=new RegExp(Prototype.ScriptFragment,'img');var c=new RegExp(Prototype.ScriptFragment,'im');return(this.match(b)||[]).map(function(a){return(a.match(c)||['',''])[1]})},evalScripts:function(){return this.extractScripts().map(function(a){return eval(a)})},escapeHTML:function(){var a=arguments.callee;a.text.data=this;return a.div.innerHTML},unescapeHTML:function(){var c=new Element('div');c.innerHTML=this.stripTags();return c.childNodes[0]?(c.childNodes.length>1?$A(c.childNodes).inject('',function(a,b){return a+b.nodeValue}):c.childNodes[0].nodeValue):''},toQueryParams:function(e){var f=this.strip().match(/([^?#]*)(#.*)?$/);if(!f)return{};return f[1].split(e||'&').inject({},function(a,b){if((b=b.split('='))[0]){var c=decodeURIComponent(b.shift());var d=b.length>1?b.join('='):b[0];if(d!=undefined)d=decodeURIComponent(d);if(c in a){if(!Object.isArray(a[c]))a[c]=[a[c]];a[c].push(d)}else a[c]=d}return a})},toArray:function(){return this.split('')},succ:function(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)},times:function(a){return a<1?'':new Array(a+1).join(this)},camelize:function(){var a=this.split('-'),len=a.length;if(len==1)return a[0];var b=this.charAt(0)=='-'?a[0].charAt(0).toUpperCase()+a[0].substring(1):a[0];for(var i=1;i<len;i++)b+=a[i].charAt(0).toUpperCase()+a[i].substring(1);return b},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()},underscore:function(){return this.gsub(/::/,'/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase()},dasherize:function(){return this.gsub(/_/,'-')},inspect:function(c){var d=this.gsub(/[\x00-\x1f\\]/,function(a){var b=String.specialChar[a[0]];return b?b:'\\u00'+a[0].charCodeAt().toPaddedString(2,16)});if(c)return'"'+d.replace(/"/g,'\\"')+'"';return"'"+d.replace(/'/g,'\\\'')+"'"},toJSON:function(){return this.inspect(true)},unfilterJSON:function(a){return this.sub(a||Prototype.JSONFilter,'#{1}')},isJSON:function(){var a=this;if(a.blank())return false;a=this.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(a)},evalJSON:function(a){var b=this.unfilterJSON();try{if(!a||b.isJSON())return eval('('+b+')')}catch(e){}throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(a){return this.indexOf(a)>-1},startsWith:function(a){return this.indexOf(a)===0},endsWith:function(a){var d=this.length-a.length;return d>=0&&this.lastIndexOf(a)===d},empty:function(){return this==''},blank:function(){return/^\s*$/.test(this)},interpolate:function(a,b){return new Template(this,b).evaluate(a)}});if(Prototype.Browser.WebKit||Prototype.Browser.IE)Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')},unescapeHTML:function(){return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>')}});String.prototype.gsub.prepareReplacement=function(b){if(Object.isFunction(b))return b;var c=new Template(b);return function(a){return c.evaluate(a)}};String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement('div'),text:document.createTextNode('')});with(String.prototype.escapeHTML)div.appendChild(text);var Template=Class.create({initialize:function(a,b){this.template=a.toString();this.pattern=b||Template.Pattern},evaluate:function(f){if(Object.isFunction(f.toTemplateReplacements))f=f.toTemplateReplacements();return this.template.gsub(this.pattern,function(a){if(f==null)return'';var b=a[1]||'';if(b=='\\')return a[2];var c=f,expr=a[3];var d=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;a=d.exec(expr);if(a==null)return b;while(a!=null){var e=a[1].startsWith('[')?a[2].gsub('\\\\]',']'):a[1];c=c[e];if(null==c||''==a[3])break;expr=expr.substring('['==a[3]?a[1].length:a[0].length);a=d.exec(expr)}return b+String.interpret(c)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable={each:function(b,c){var d=0;b=b.bind(c);try{this._each(function(a){b(a,d++)})}catch(e){if(e!=$break)throw e;}return this},eachSlice:function(a,b,c){b=b?b.bind(c):Prototype.K;var d=-a,slices=[],array=this.toArray();while((d+=a)<array.length)slices.push(array.slice(d,d+a));return slices.collect(b,c)},all:function(c,d){c=c?c.bind(d):Prototype.K;var e=true;this.each(function(a,b){e=e&&!!c(a,b);if(!e)throw $break;});return e},any:function(c,d){c=c?c.bind(d):Prototype.K;var e=false;this.each(function(a,b){if(e=!!c(a,b))throw $break;});return e},collect:function(c,d){c=c?c.bind(d):Prototype.K;var e=[];this.each(function(a,b){e.push(c(a,b))});return e},detect:function(c,d){c=c.bind(d);var e;this.each(function(a,b){if(c(a,b)){e=a;throw $break;}});return e},findAll:function(c,d){c=c.bind(d);var e=[];this.each(function(a,b){if(c(a,b))e.push(a)});return e},grep:function(c,d,e){d=d?d.bind(e):Prototype.K;var f=[];if(Object.isString(c))c=new RegExp(c);this.each(function(a,b){if(c.match(a))f.push(d(a,b))});return f},include:function(b){if(Object.isFunction(this.indexOf))if(this.indexOf(b)!=-1)return true;var c=false;this.each(function(a){if(a==b){c=true;throw $break;}});return c},inGroupsOf:function(b,c){c=Object.isUndefined(c)?null:c;return this.eachSlice(b,function(a){while(a.length<b)a.push(c);return a})},inject:function(c,d,e){d=d.bind(e);this.each(function(a,b){c=d(c,a,b)});return c},invoke:function(b){var c=$A(arguments).slice(1);return this.map(function(a){return a[b].apply(a,c)})},max:function(c,d){c=c?c.bind(d):Prototype.K;var e;this.each(function(a,b){a=c(a,b);if(e==null||a>=e)e=a});return e},min:function(c,d){c=c?c.bind(d):Prototype.K;var e;this.each(function(a,b){a=c(a,b);if(e==null||a<e)e=a});return e},partition:function(c,d){c=c?c.bind(d):Prototype.K;var e=[],falses=[];this.each(function(a,b){(c(a,b)?e:falses).push(a)});return[e,falses]},pluck:function(b){var c=[];this.each(function(a){c.push(a[b])});return c},reject:function(c,d){c=c.bind(d);var e=[];this.each(function(a,b){if(!c(a,b))e.push(a)});return e},sortBy:function(e,f){e=e.bind(f);return this.map(function(a,b){return{value:a,criteria:e(a,b)}}).sort(function(c,d){var a=c.criteria,b=d.criteria;return a<b?-1:a>b?1:0}).pluck('value')},toArray:function(){return this.map()},zip:function(){var c=Prototype.K,args=$A(arguments);if(Object.isFunction(args.last()))c=args.pop();var d=[this].concat(args).map($A);return this.map(function(a,b){return c(d.pluck(b))})},size:function(){return this.toArray().length},inspect:function(){return'#<Enumerable:'+this.toArray().inspect()+'>'}};Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,filter:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray,every:Enumerable.all,some:Enumerable.any});function $A(a){if(!a)return[];if(a.toArray)return a.toArray();var b=a.length||0,results=new Array(b);while(b--)results[b]=a[b];return results}if(Prototype.Browser.WebKit){$A=function(a){if(!a)return[];if(!(Object.isFunction(a)&&a=='[object NodeList]')&&a.toArray)return a.toArray();var b=a.length||0,results=new Array(b);while(b--)results[b]=a[b];return results}}Array.from=$A;Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse)Array.prototype._reverse=Array.prototype.reverse;Object.extend(Array.prototype,{_each:function(a){for(var i=0,length=this.length;i<length;i++)a(this[i])},clear:function(){this.length=0;return this},first:function(){return this[0]},last:function(){return this[this.length-1]},compact:function(){return this.select(function(a){return a!=null})},flatten:function(){return this.inject([],function(a,b){return a.concat(Object.isArray(b)?b.flatten():[b])})},without:function(){var b=$A(arguments);return this.select(function(a){return!b.include(a)})},reverse:function(a){return(a!==false?this:this.toArray())._reverse()},reduce:function(){return this.length>1?this:this[0]},uniq:function(d){return this.inject([],function(a,b,c){if(0==c||(d?a.last()!=b:!a.include(b)))a.push(b);return a})},intersect:function(c){return this.uniq().findAll(function(b){return c.detect(function(a){return b===a})})},clone:function(){return[].concat(this)},size:function(){return this.length},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']'},toJSON:function(){var c=[];this.each(function(a){var b=Object.toJSON(a);if(!Object.isUndefined(b))c.push(b)});return'['+c.join(', ')+']'}});if(Object.isFunction(Array.prototype.forEach))Array.prototype._each=Array.prototype.forEach;if(!Array.prototype.indexOf)Array.prototype.indexOf=function(a,i){i||(i=0);var b=this.length;if(i<0)i=b+i;for(;i<b;i++)if(this[i]===a)return i;return-1};if(!Array.prototype.lastIndexOf)Array.prototype.lastIndexOf=function(a,i){i=isNaN(i)?this.length:(i<0?this.length+i:i)+1;var n=this.slice(0,i).reverse().indexOf(a);return(n<0)?n:i-n-1};Array.prototype.toArray=Array.prototype.clone;function $w(a){if(!Object.isString(a))return[];a=a.strip();return a?a.split(/\s+/):[]}if(Prototype.Browser.Opera){Array.prototype.concat=function(){var a=[];for(var i=0,length=this.length;i<length;i++)a.push(this[i]);for(var i=0,length=arguments.length;i<length;i++){if(Object.isArray(arguments[i])){for(var j=0,arrayLength=arguments[i].length;j<arrayLength;j++)a.push(arguments[i][j])}else{a.push(arguments[i])}}return a}}Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16)},succ:function(){return this+1},times:function(a){$R(0,this,true).each(a);return this},toPaddedString:function(a,b){var c=this.toString(b||10);return'0'.times(a-c.length)+c},toJSON:function(){return isFinite(this)?this.toString():'null'}});$w('abs round ceil floor').each(function(a){Number.prototype[a]=Math[a].methodize()});function $H(a){return new Hash(a)};var Hash=Class.create(Enumerable,(function(){function toQueryPair(a,b){if(Object.isUndefined(b))return a;return a+'='+encodeURIComponent(String.interpret(b))}return{initialize:function(a){this._object=Object.isHash(a)?a.toObject():Object.clone(a)},_each:function(a){for(var b in this._object){var c=this._object[b],pair=[b,c];pair.key=b;pair.value=c;a(pair)}},set:function(a,b){return this._object[a]=b},get:function(a){return this._object[a]},unset:function(a){var b=this._object[a];delete this._object[a];return b},toObject:function(){return Object.clone(this._object)},keys:function(){return this.pluck('key')},values:function(){return this.pluck('value')},index:function(b){var c=this.detect(function(a){return a.value===b});return c&&c.key},merge:function(a){return this.clone().update(a)},update:function(c){return new Hash(c).inject(this,function(a,b){a.set(b.key,b.value);return a})},toQueryString:function(){return this.map(function(a){var b=encodeURIComponent(a.key),values=a.value;if(values&&typeof values=='object'){if(Object.isArray(values))return values.map(toQueryPair.curry(b)).join('&')}return toQueryPair(b,values)}).join('&')},inspect:function(){return'#<Hash:{'+this.map(function(a){return a.map(Object.inspect).join(': ')}).join(', ')+'}>'},toJSON:function(){return Object.toJSON(this.toObject())},clone:function(){return new Hash(this)}}})());Hash.prototype.toTemplateReplacements=Hash.prototype.toObject;Hash.from=$H;var ObjectRange=Class.create(Enumerable,{initialize:function(a,b,c){this.start=a;this.end=b;this.exclusive=c},_each:function(a){var b=this.start;while(this.include(b)){a(b);b=b.succ()}},include:function(a){if(a<this.start)return false;if(this.exclusive)return a<this.end;return a<=this.end}});var $R=function(a,b,c){return new ObjectRange(a,b,c)};var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest()},function(){return new ActiveXObject('Msxml2.XMLHTTP')},function(){return new ActiveXObject('Microsoft.XMLHTTP')})||false},activeRequestCount:0};Ajax.Responders={responders:[],_each:function(a){this.responders._each(a)},register:function(a){if(!this.include(a))this.responders.push(a)},unregister:function(a){this.responders=this.responders.without(a)},dispatch:function(b,c,d,f){this.each(function(a){if(Object.isFunction(a[b])){try{a[b].apply(a,[c,d,f])}catch(e){}}})}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(a){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:'',evalJSON:true,evalJS:true};Object.extend(this.options,a||{});this.options.method=this.options.method.toLowerCase();if(Object.isString(this.options.parameters))this.options.parameters=this.options.parameters.toQueryParams();else if(Object.isHash(this.options.parameters))this.options.parameters=this.options.parameters.toObject()}});Ajax.Request=Class.create(Ajax.Base,{_complete:false,initialize:function($super,b,c){$super(c);this.transport=Ajax.getTransport();this.request(b)},request:function(a){this.url=a;this.method=this.options.method;var b=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){b['_method']=this.method;this.method='post'}this.parameters=b;if(b=Object.toQueryString(b)){if(this.method=='get')this.url+=(this.url.include('?')?'&':'?')+b;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))b+='&_='}try{var c=new Ajax.Response(this);if(this.options.onCreate)this.options.onCreate(c);Ajax.Responders.dispatch('onCreate',this,c);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)this.respondToReadyState.bind(this).defer(1);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||b):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)this.onStateChange()}catch(e){this.dispatchException(e)}},onStateChange:function(){var a=this.transport.readyState;if(a>1&&!((a==4)&&this._complete))this.respondToReadyState(this.transport.readyState)},setRequestHeaders:function(){var b={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){b['Content-type']=this.options.contentType+(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005)b['Connection']='close'}if(typeof this.options.requestHeaders=='object'){var c=this.options.requestHeaders;if(Object.isFunction(c.push))for(var i=0,length=c.length;i<length;i+=2)b[c[i]]=c[i+1];else $H(c).each(function(a){b[a.key]=a.value})}for(var d in b)this.transport.setRequestHeader(d,b[d])},success:function(){var a=this.getStatus();return!a||(a>=200&&a<300)},getStatus:function(){try{return this.transport.status||0}catch(e){return 0}},respondToReadyState:function(a){var b=Ajax.Request.Events[a],response=new Ajax.Response(this);if(b=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(response,response.headerJSON)}catch(e){this.dispatchException(e)}var c=response.getHeader('Content-type');if(this.options.evalJS=='force'||(this.options.evalJS&&this.isSameOrigin()&&c&&c.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))this.evalResponse()}try{(this.options['on'+b]||Prototype.emptyFunction)(response,response.headerJSON);Ajax.Responders.dispatch('on'+b,this,response,response.headerJSON)}catch(e){this.dispatchException(e)}if(b=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction}},isSameOrigin:function(){var m=this.url.match(/^\s*https?:\/\/[^\/]*/);return!m||(m[0]=='#{protocol}//#{domain}#{port}'.interpolate({protocol:location.protocol,domain:document.domain,port:location.port?':'+location.port:''}))},getHeader:function(a){try{return this.transport.getResponseHeader(a)||null}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON())}catch(e){this.dispatchException(e)}},dispatchException:function(a){(this.options.onException||Prototype.emptyFunction)(this,a);Ajax.Responders.dispatch('onException',this,a)}});Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Response=Class.create({initialize:function(a){this.request=a;var b=this.transport=a.transport,readyState=this.readyState=b.readyState;if((readyState>2&&!Prototype.Browser.IE)||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(b.responseText);this.headerJSON=this._getHeaderJSON()}if(readyState==4){var c=b.responseXML;this.responseXML=Object.isUndefined(c)?null:c;this.responseJSON=this._getResponseJSON()}},status:0,statusText:'',getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||''}catch(e){return''}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(e){return null}},getResponseHeader:function(a){return this.transport.getResponseHeader(a)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var a=this.getHeader('X-JSON');if(!a)return null;a=decodeURIComponent(escape(a));try{return a.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}},_getResponseJSON:function(){var a=this.request.options;if(!a.evalJSON||(a.evalJSON!='force'&&!(this.getHeader('Content-type')||'').include('application/json'))||this.responseText.blank())return null;try{return this.responseText.evalJSON(a.sanitizeJSON||!this.request.isSameOrigin())}catch(e){this.request.dispatchException(e)}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,d,e,f){this.container={success:(d.success||d),failure:(d.failure||(d.success?null:d))};f=Object.clone(f);var g=f.onComplete;f.onComplete=(function(a,b){this.updateContent(a.responseText);if(Object.isFunction(g))g(a,b)}).bind(this);$super(e,f)},updateContent:function(a){var b=this.container[this.success()?'success':'failure'],options=this.options;if(!options.evalScripts)a=a.stripScripts();if(b=$(b)){if(options.insertion){if(Object.isString(options.insertion)){var c={};c[options.insertion]=a;b.insert(c)}else options.insertion(b,a)}else b.update(a)}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,b,c,d){$super(d);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=b;this.url=c;this.start()},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent()},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments)},updateComplete:function(a){if(this.options.decay){this.decay=(a.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=a.responseText}this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});function $(a){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)elements.push($(arguments[i]));return elements}if(Object.isString(a))a=document.getElementById(a);return Element.extend(a)}if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(a,b){var c=[];var d=document.evaluate(a,$(b)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=d.snapshotLength;i<length;i++)c.push(Element.extend(d.snapshotItem(i)));return c}}if(!window.Node)var Node={};if(!Node.ELEMENT_NODE){Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12})}(function(){var d=this.Element;this.Element=function(a,b){b=b||{};a=a.toLowerCase();var c=Element.cache;if(Prototype.Browser.IE&&b.name){a='<'+a+' name="'+b.name+'">';delete b.name;return Element.writeAttribute(document.createElement(a),b)}if(!c[a])c[a]=Element.extend(document.createElement(a));return Element.writeAttribute(c[a].cloneNode(false),b)};Object.extend(this.Element,d||{})}).call(window);Element.cache={};Element.Methods={visible:function(a){return $(a).style.display!='none'},toggle:function(a){a=$(a);Element[Element.visible(a)?'hide':'show'](a);return a},hide:function(a){$(a).style.display='none';return a},show:function(a){$(a).style.display='';return a},remove:function(a){a=$(a);a.parentNode.removeChild(a);return a},update:function(a,b){a=$(a);if(b&&b.toElement)b=b.toElement();if(Object.isElement(b))return a.update().insert(b);b=Object.toHTML(b);a.innerHTML=b.stripScripts();b.evalScripts.bind(b).defer();return a},replace:function(a,b){a=$(a);if(b&&b.toElement)b=b.toElement();else if(!Object.isElement(b)){b=Object.toHTML(b);var c=a.ownerDocument.createRange();c.selectNode(a);b.evalScripts.bind(b).defer();b=c.createContextualFragment(b.stripScripts())}a.parentNode.replaceChild(b,a);return a},insert:function(a,b){a=$(a);if(Object.isString(b)||Object.isNumber(b)||Object.isElement(b)||(b&&(b.toElement||b.toHTML)))b={bottom:b};var c,insert,tagName,childNodes;for(var d in b){c=b[d];d=d.toLowerCase();insert=Element._insertionTranslations[d];if(c&&c.toElement)c=c.toElement();if(Object.isElement(c)){insert(a,c);continue}c=Object.toHTML(c);tagName=((d=='before'||d=='after')?a.parentNode:a).tagName.toUpperCase();childNodes=Element._getContentFromAnonymousElement(tagName,c.stripScripts());if(d=='top'||d=='after')childNodes.reverse();childNodes.each(insert.curry(a));c.evalScripts.bind(c).defer()}return a},wrap:function(a,b,c){a=$(a);if(Object.isElement(b))$(b).writeAttribute(c||{});else if(Object.isString(b))b=new Element(b,c);else b=new Element('div',b);if(a.parentNode)a.parentNode.replaceChild(b,a);b.appendChild(a);return b},inspect:function(d){d=$(d);var e='<'+d.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(a){var b=a.first(),attribute=a.last();var c=(d[b]||'').toString();if(c)e+=' '+attribute+'='+c.inspect(true)});return e+'>'},recursivelyCollect:function(a,b){a=$(a);var c=[];while(a=a[b])if(a.nodeType==1)c.push(Element.extend(a));return c},ancestors:function(a){return $(a).recursivelyCollect('parentNode')},descendants:function(a){return $(a).select("*")},firstDescendant:function(a){a=$(a).firstChild;while(a&&a.nodeType!=1)a=a.nextSibling;return $(a)},immediateDescendants:function(a){if(!(a=$(a).firstChild))return[];while(a&&a.nodeType!=1)a=a.nextSibling;if(a)return[a].concat($(a).nextSiblings());return[]},previousSiblings:function(a){return $(a).recursivelyCollect('previousSibling')},nextSiblings:function(a){return $(a).recursivelyCollect('nextSibling')},siblings:function(a){a=$(a);return a.previousSiblings().reverse().concat(a.nextSiblings())},match:function(a,b){if(Object.isString(b))b=new Selector(b);return b.match($(a))},up:function(a,b,c){a=$(a);if(arguments.length==1)return $(a.parentNode);var d=a.ancestors();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},down:function(a,b,c){a=$(a);if(arguments.length==1)return a.firstDescendant();return Object.isNumber(b)?a.descendants()[b]:a.select(b)[c||0]},previous:function(a,b,c){a=$(a);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(a));var d=a.previousSiblings();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},next:function(a,b,c){a=$(a);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(a));var d=a.nextSiblings();return Object.isNumber(b)?d[b]:Selector.findElement(d,b,c)},select:function(){var a=$A(arguments),element=$(a.shift());return Selector.findChildElements(element,a)},adjacent:function(){var a=$A(arguments),element=$(a.shift());return Selector.findChildElements(element.parentNode,a).without(element)},identify:function(a){a=$(a);var b=a.readAttribute('id'),self=arguments.callee;if(b)return b;do{b='anonymous_element_'+self.counter++}while($(b));a.writeAttribute('id',b);return b},readAttribute:function(a,b){a=$(a);if(Prototype.Browser.IE){var t=Element._attributeTranslations.read;if(t.values[b])return t.values[b](a,b);if(t.names[b])b=t.names[b];if(b.include(':')){return(!a.attributes||!a.attributes[b])?null:a.attributes[b].value}}return a.getAttribute(b)},writeAttribute:function(a,b,c){a=$(a);var d={},t=Element._attributeTranslations.write;if(typeof b=='object')d=b;else d[b]=Object.isUndefined(c)?true:c;for(var e in d){b=t.names[e]||e;c=d[e];if(t.values[e])b=t.values[e](a,c);if(c===false||c===null)a.removeAttribute(b);else if(c===true)a.setAttribute(b,b);else a.setAttribute(b,c)}return a},getHeight:function(a){return $(a).getDimensions().height},getWidth:function(a){return $(a).getDimensions().width},classNames:function(a){return new Element.ClassNames(a)},hasClassName:function(a,b){if(!(a=$(a)))return;var c=a.className;return(c.length>0&&(c==b||new RegExp("(^|\\s)"+b+"(\\s|$)").test(c)))},addClassName:function(a,b){if(!(a=$(a)))return;if(!a.hasClassName(b))a.className+=(a.className?' ':'')+b;return a},removeClassName:function(a,b){if(!(a=$(a)))return;a.className=a.className.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)"),' ').strip();return a},toggleClassName:function(a,b){if(!(a=$(a)))return;return a[a.hasClassName(b)?'removeClassName':'addClassName'](b)},cleanWhitespace:function(a){a=$(a);var b=a.firstChild;while(b){var c=b.nextSibling;if(b.nodeType==3&&!/\S/.test(b.nodeValue))a.removeChild(b);b=c}return a},empty:function(a){return $(a).innerHTML.blank()},descendantOf:function(b,c){b=$(b),c=$(c);var d=c;if(b.compareDocumentPosition)return(b.compareDocumentPosition(c)&8)===8;if(b.sourceIndex&&!Prototype.Browser.Opera){var e=b.sourceIndex,a=c.sourceIndex,nextAncestor=c.nextSibling;if(!nextAncestor){do{c=c.parentNode}while(!(nextAncestor=c.nextSibling)&&c.parentNode)}if(nextAncestor&&nextAncestor.sourceIndex)return(e>a&&e<nextAncestor.sourceIndex)}while(b=b.parentNode)if(b==d)return true;return false},scrollTo:function(a){a=$(a);var b=a.cumulativeOffset();window.scrollTo(b[0],b[1]);return a},getStyle:function(a,b){a=$(a);b=b=='float'?'cssFloat':b.camelize();var c=a.style[b];if(!c){var d=document.defaultView.getComputedStyle(a,null);c=d?d[b]:null}if(b=='opacity')return c?parseFloat(c):1.0;return c=='auto'?null:c},getOpacity:function(a){return $(a).getStyle('opacity')},setStyle:function(a,b){a=$(a);var c=a.style,match;if(Object.isString(b)){a.style.cssText+=';'+b;return b.include('opacity')?a.setOpacity(b.match(/opacity:\s*(\d?\.?\d*)/)[1]):a}for(var d in b)if(d=='opacity')a.setOpacity(b[d]);else c[(d=='float'||d=='cssFloat')?(Object.isUndefined(c.styleFloat)?'cssFloat':'styleFloat'):d]=b[d];return a},setOpacity:function(a,b){a=$(a);a.style.opacity=(b==1||b==='')?'':(b<0.00001)?0:b;return a},getDimensions:function(a){a=$(a);var b=$(a).getStyle('display');if(b!='none'&&b!=null)return{width:a.offsetWidth,height:a.offsetHeight};var c=a.style;var d=c.visibility;var e=c.position;var f=c.display;c.visibility='hidden';c.position='absolute';c.display='block';var g=a.clientWidth;var h=a.clientHeight;c.display=f;c.position=e;c.visibility=d;return{width:g,height:h}},makePositioned:function(a){a=$(a);var b=Element.getStyle(a,'position');if(b=='static'||!b){a._madePositioned=true;a.style.position='relative';if(window.opera){a.style.top=0;a.style.left=0}}return a},undoPositioned:function(a){a=$(a);if(a._madePositioned){a._madePositioned=undefined;a.style.position=a.style.top=a.style.left=a.style.bottom=a.style.right=''}return a},makeClipping:function(a){a=$(a);if(a._overflow)return a;a._overflow=Element.getStyle(a,'overflow')||'auto';if(a._overflow!=='hidden')a.style.overflow='hidden';return a},undoClipping:function(a){a=$(a);if(!a._overflow)return a;a.style.overflow=a._overflow=='auto'?'':a._overflow;a._overflow=null;return a},cumulativeOffset:function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;a=a.offsetParent}while(a);return Element._returnOffset(valueL,b)},positionedOffset:function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;a=a.offsetParent;if(a){if(a.tagName=='BODY')break;var p=Element.getStyle(a,'position');if(p!=='static')break}}while(a);return Element._returnOffset(valueL,b)},absolutize:function(a){a=$(a);if(a.getStyle('position')=='absolute')return;var b=a.positionedOffset();var c=b[1];var d=b[0];var e=a.clientWidth;var f=a.clientHeight;a._originalLeft=d-parseFloat(a.style.left||0);a._originalTop=c-parseFloat(a.style.top||0);a._originalWidth=a.style.width;a._originalHeight=a.style.height;a.style.position='absolute';a.style.top=c+'px';a.style.left=d+'px';a.style.width=e+'px';a.style.height=f+'px';return a},relativize:function(a){a=$(a);if(a.getStyle('position')=='relative')return;a.style.position='relative';var b=parseFloat(a.style.top||0)-(a._originalTop||0);var c=parseFloat(a.style.left||0)-(a._originalLeft||0);a.style.top=b+'px';a.style.left=c+'px';a.style.height=a._originalHeight;a.style.width=a._originalWidth;return a},cumulativeScrollOffset:function(a){var b=0,valueL=0;do{b+=a.scrollTop||0;valueL+=a.scrollLeft||0;a=a.parentNode}while(a);return Element._returnOffset(valueL,b)},getOffsetParent:function(a){if(a.offsetParent)return $(a.offsetParent);if(a==document.body)return $(a);while((a=a.parentNode)&&a!=document.body)if(Element.getStyle(a,'position')!='static')return $(a);return $(document.body)},viewportOffset:function(a){var b=0,valueL=0;var c=a;do{b+=c.offsetTop||0;valueL+=c.offsetLeft||0;if(c.offsetParent==document.body&&Element.getStyle(c,'position')=='absolute')break}while(c=c.offsetParent);c=a;do{if(!Prototype.Browser.Opera||c.tagName=='BODY'){b-=c.scrollTop||0;valueL-=c.scrollLeft||0}}while(c=c.parentNode);return Element._returnOffset(valueL,b)},clonePosition:function(a,b){var c=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});b=$(b);var p=b.viewportOffset();a=$(a);var d=[0,0];var e=null;if(Element.getStyle(a,'position')=='absolute'){e=a.getOffsetParent();d=e.viewportOffset()}if(e==document.body){d[0]-=document.body.offsetLeft;d[1]-=document.body.offsetTop}if(c.setLeft)a.style.left=(p[0]-d[0]+c.offsetLeft)+'px';if(c.setTop)a.style.top=(p[1]-d[1]+c.offsetTop)+'px';if(c.setWidth)a.style.width=b.offsetWidth+'px';if(c.setHeight)a.style.height=b.offsetHeight+'px';return a}};Element.Methods.identify.counter=1;Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:'class',htmlFor:'for'},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(d,e,f){switch(f){case'left':case'top':case'right':case'bottom':if(d(e,'position')==='static')return null;case'height':case'width':if(!Element.visible(e))return null;var g=parseInt(d(e,f),10);if(g!==e['offset'+f.capitalize()])return g+'px';var h;if(f==='height'){h=['border-top-width','padding-top','padding-bottom','border-bottom-width']}else{h=['border-left-width','padding-left','padding-right','border-right-width']}return h.inject(g,function(a,b){var c=d(e,b);return c===null?a:a-parseInt(c,10)})+'px';default:return d(e,f)}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(a,b,c){if(c==='title')return b.title;return a(b,c)})}else if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(a,b){b=$(b);var c=b.getStyle('position');if(c!=='static')return a(b);b.setStyle({position:'relative'});var d=a(b);b.setStyle({position:c});return d});$w('positionedOffset viewportOffset').each(function(f){Element.Methods[f]=Element.Methods[f].wrap(function(a,b){b=$(b);var c=b.getStyle('position');if(c!=='static')return a(b);var d=b.getOffsetParent();if(d&&d.getStyle('position')==='fixed')d.setStyle({zoom:1});b.setStyle({position:'relative'});var e=a(b);b.setStyle({position:c});return e})});Element.Methods.getStyle=function(a,b){a=$(a);b=(b=='float'||b=='cssFloat')?'styleFloat':b.camelize();var c=a.style[b];if(!c&&a.currentStyle)c=a.currentStyle[b];if(b=='opacity'){if(c=(a.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/))if(c[1])return parseFloat(c[1])/100;return 1.0}if(c=='auto'){if((b=='width'||b=='height')&&(a.getStyle('display')!='none'))return a['offset'+b.capitalize()]+'px';return null}return c};Element.Methods.setOpacity=function(b,c){function stripAlpha(a){return a.replace(/alpha\([^\)]*\)/gi,'')}b=$(b);var d=b.currentStyle;if((d&&!d.hasLayout)||(!d&&b.style.zoom=='normal'))b.style.zoom=1;var e=b.getStyle('filter'),style=b.style;if(c==1||c===''){(e=stripAlpha(e))?style.filter=e:style.removeAttribute('filter');return b}else if(c<0.00001)c=0;style.filter=stripAlpha(e)+'alpha(opacity='+(c*100)+')';return b};Element._attributeTranslations={read:{names:{'class':'className','for':'htmlFor'},values:{_getAttr:function(a,b){return a.getAttribute(b,2)},_getAttrNode:function(a,b){var c=a.getAttributeNode(b);return c?c.value:""},_getEv:function(a,b){b=a.getAttribute(b);return b?b.toString().slice(23,-2):null},_flag:function(a,b){return $(a).hasAttribute(b)?b:null},style:function(a){return a.style.cssText.toLowerCase()},title:function(a){return a.title}}}};Element._attributeTranslations.write={names:Object.extend({cellpadding:'cellPadding',cellspacing:'cellSpacing'},Element._attributeTranslations.read.names),values:{checked:function(a,b){a.checked=!!b},style:function(a,b){a.style.cssText=b?b:''}}};Element._attributeTranslations.has={};$w('colSpan rowSpan vAlign dateTime accessKey tabIndex '+'encType maxLength readOnly longDesc').each(function(a){Element._attributeTranslations.write.names[a.toLowerCase()]=a;Element._attributeTranslations.has[a.toLowerCase()]=a});(function(v){Object.extend(v,{href:v._getAttr,src:v._getAttr,type:v._getAttr,action:v._getAttrNode,disabled:v._flag,checked:v._flag,readonly:v._flag,multiple:v._flag,onload:v._getEv,onunload:v._getEv,onclick:v._getEv,ondblclick:v._getEv,onmousedown:v._getEv,onmouseup:v._getEv,onmouseover:v._getEv,onmousemove:v._getEv,onmouseout:v._getEv,onfocus:v._getEv,onblur:v._getEv,onkeypress:v._getEv,onkeydown:v._getEv,onkeyup:v._getEv,onsubmit:v._getEv,onreset:v._getEv,onselect:v._getEv,onchange:v._getEv})})(Element._attributeTranslations.read.values)}else if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1)?0.999999:(b==='')?'':(b<0.00001)?0:b;return a}}else if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1||b==='')?'':(b<0.00001)?0:b;if(b==1)if(a.tagName=='IMG'&&a.width){a.width++;a.width--}else try{var n=document.createTextNode(' ');a.appendChild(n);a.removeChild(n)}catch(e){}return a};Element.Methods.cumulativeOffset=function(a){var b=0,valueL=0;do{b+=a.offsetTop||0;valueL+=a.offsetLeft||0;if(a.offsetParent==document.body)if(Element.getStyle(a,'position')=='absolute')break;a=a.offsetParent}while(a);return Element._returnOffset(valueL,b)}}if(Prototype.Browser.IE||Prototype.Browser.Opera){Element.Methods.update=function(b,c){b=$(b);if(c&&c.toElement)c=c.toElement();if(Object.isElement(c))return b.update().insert(c);c=Object.toHTML(c);var d=b.tagName.toUpperCase();if(d in Element._insertionTranslations.tags){$A(b.childNodes).each(function(a){b.removeChild(a)});Element._getContentFromAnonymousElement(d,c.stripScripts()).each(function(a){b.appendChild(a)})}else b.innerHTML=c.stripScripts();c.evalScripts.bind(c).defer();return b}}if('outerHTML'in document.createElement('div')){Element.Methods.replace=function(b,c){b=$(b);if(c&&c.toElement)c=c.toElement();if(Object.isElement(c)){b.parentNode.replaceChild(c,b);return b}c=Object.toHTML(c);var d=b.parentNode,tagName=d.tagName.toUpperCase();if(Element._insertionTranslations.tags[tagName]){var e=b.next();var f=Element._getContentFromAnonymousElement(tagName,c.stripScripts());d.removeChild(b);if(e)f.each(function(a){d.insertBefore(a,e)});else f.each(function(a){d.appendChild(a)})}else b.outerHTML=c.stripScripts();c.evalScripts.bind(c).defer();return b}}Element._returnOffset=function(l,t){var a=[l,t];a.left=l;a.top=t;return a};Element._getContentFromAnonymousElement=function(a,b){var c=new Element('div'),t=Element._insertionTranslations.tags[a];if(t){c.innerHTML=t[0]+b+t[1];t[2].times(function(){c=c.firstChild})}else c.innerHTML=b;return $A(c.childNodes)};Element._insertionTranslations={before:function(a,b){a.parentNode.insertBefore(b,a)},top:function(a,b){a.insertBefore(b,a.firstChild)},bottom:function(a,b){a.appendChild(b)},after:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},tags:{TABLE:['<table>','</table>',1],TBODY:['<table><tbody>','</tbody></table>',2],TR:['<table><tbody><tr>','</tr></tbody></table>',3],TD:['<table><tbody><tr><td>','</td></tr></tbody></table>',4],SELECT:['<select>','</select>',1]}};(function(){Object.extend(this.tags,{THEAD:this.tags.TBODY,TFOOT:this.tags.TBODY,TH:this.tags.TD})}).call(Element._insertionTranslations);Element.Methods.Simulated={hasAttribute:function(a,b){b=Element._attributeTranslations.has[b]||b;var c=$(a).getAttributeNode(b);return c&&c.specified}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement('div').__proto__){window.HTMLElement={};window.HTMLElement.prototype=document.createElement('div').__proto__;Prototype.BrowserFeatures.ElementExtensions=true}Element.extend=(function(){if(Prototype.BrowserFeatures.SpecificElementExtensions)return Prototype.K;var c={},ByTag=Element.Methods.ByTag;var d=Object.extend(function(a){if(!a||a._extendedByPrototype||a.nodeType!=1||a==window)return a;var b=Object.clone(c),tagName=a.tagName,property,value;if(ByTag[tagName])Object.extend(b,ByTag[tagName]);for(property in b){value=b[property];if(Object.isFunction(value)&&!(property in a))a[property]=value.methodize()}a._extendedByPrototype=Prototype.emptyFunction;return a},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(c,Element.Methods);Object.extend(c,Element.Methods.Simulated)}}});d.refresh();return d})();Element.hasAttribute=function(a,b){if(a.hasAttribute)return a.hasAttribute(b);return Element.Methods.Simulated.hasAttribute(a,b)};Element.addMethods=function(f){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!f){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods)})}if(arguments.length==2){var g=f;f=arguments[1]}if(!g)Object.extend(Element.Methods,f||{});else{if(Object.isArray(g))g.each(extend);else extend(g)}function extend(a){a=a.toUpperCase();if(!Element.Methods.ByTag[a])Element.Methods.ByTag[a]={};Object.extend(Element.Methods.ByTag[a],f)}function copy(a,b,c){c=c||false;for(var d in a){var e=a[d];if(!Object.isFunction(e))continue;if(!c||!(d in b))b[d]=e.methodize()}}function findDOMClass(a){var b;var c={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow","TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(c[a])b='HTML'+c[a]+'Element';if(window[b])return window[b];b='HTML'+a+'Element';if(window[b])return window[b];b='HTML'+a.capitalize()+'Element';if(window[b])return window[b];window[b]={};window[b].prototype=document.createElement(a).__proto__;return window[b]}if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true)}if(F.SpecificElementExtensions){for(var h in Element.Methods.ByTag){var i=findDOMClass(h);if(Object.isUndefined(i))continue;copy(T[h],i.prototype)}}Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh)Element.extend.refresh();Element.cache={}};document.viewport={getDimensions:function(){var a={};var B=Prototype.Browser;$w('width height').each(function(d){var D=d.capitalize();a[d]=(B.WebKit&&!document.evaluate)?self['inner'+D]:(B.Opera)?document.body['client'+D]:document.documentElement['client'+D]});return a},getWidth:function(){return this.getDimensions().width},getHeight:function(){return this.getDimensions().height},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};var Selector=Class.create({initialize:function(a){this.expression=a.strip();this.compileMatcher()},shouldUseXPath:function(){if(!Prototype.BrowserFeatures.XPath)return false;var e=this.expression;if(Prototype.Browser.WebKit&&(e.include("-of-type")||e.include(":empty")))return false;if((/(\[[\w-]*?:|:checked)/).test(this.expression))return false;return true},compileMatcher:function(){if(this.shouldUseXPath())return this.compileXPathMatcher();var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return}this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(Object.isFunction(c[i])?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],'');break}}}this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join('\n'));Selector._cache[this.expression]=this.matcher},compileXPathMatcher:function(){var e=this.expression,ps=Selector.patterns,x=Selector.xpath,le,m;if(Selector._cache[e]){this.xpath=Selector._cache[e];return}this.matcher=['.//*'];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){if(m=e.match(ps[i])){this.matcher.push(Object.isFunction(x[i])?x[i](m):new Template(x[i]).evaluate(m));e=e.replace(m[0],'');break}}}this.xpath=this.matcher.join('');Selector._cache[this.expression]=this.xpath},findElements:function(a){a=a||document;if(this.xpath)return document._getElementsByXPath(this.xpath,a);return this.matcher(a)},match:function(a){this.tokens=[];var e=this.expression,ps=Selector.patterns,as=Selector.assertions;var b,p,m;while(e&&b!==e&&(/\S/).test(e)){b=e;for(var i in ps){p=ps[i];if(m=e.match(p)){if(as[i]){this.tokens.push([i,Object.clone(m)]);e=e.replace(m[0],'')}else{return this.findElements(document).include(a)}}}}var c=true,name,matches;for(var i=0,token;token=this.tokens[i];i++){name=token[0],matches=token[1];if(!Selector.assertions[name](a,matches)){c=false;break}}return c},toString:function(){return this.expression},inspect:function(){return"#<Selector:"+this.expression.inspect()+">"}});Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:'/following-sibling::*',tagName:function(m){if(m[1]=='*')return'';return"[local-name()='"+m[1].toLowerCase()+"' or local-name()='"+m[1].toUpperCase()+"']"},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:function(m){m[1]=m[1].toLowerCase();return new Template("[@#{1}]").evaluate(m)},attr:function(m){m[1]=m[1].toLowerCase();m[3]=m[5]||m[6];return new Template(Selector.xpath.operators[m[2]]).evaluate(m)},pseudo:function(m){var h=Selector.xpath.pseudos[m[1]];if(!h)return'';if(Object.isFunction(h))return h(m);return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m)},operators:{'=':"[@#{1}='#{3}']",'!=':"[@#{1}!='#{3}']",'^=':"[starts-with(@#{1}, '#{3}')]",'$=':"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",'*=':"[contains(@#{1}, '#{3}')]",'~=':"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",'|=':"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{'first-child':'[not(preceding-sibling::*)]','last-child':'[not(following-sibling::*)]','only-child':'[not(preceding-sibling::* or following-sibling::*)]','empty':"[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",'checked':"[@checked]",'disabled':"[@disabled]",'enabled':"[not(@disabled)]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,v;var a=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in p){if(m=e.match(p[i])){v=Object.isFunction(x[i])?x[i](m):new Template(x[i]).evaluate(m);a.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break}}}return"[not("+a.join(" and ")+")]"},'nth-child':function(m){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",m)},'nth-last-child':function(m){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",m)},'nth-of-type':function(m){return Selector.xpath.pseudos.nth("position() ",m)},'nth-last-of-type':function(m){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",m)},'first-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-of-type'](m)},'last-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-last-of-type'](m)},'only-of-type':function(m){var p=Selector.xpath.pseudos;return p['first-of-type'](m)+p['last-of-type'](m)},nth:function(c,m){var d,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(d=formula.match(/^(\d+)$/))return'['+c+"= "+d[1]+']';if(d=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(d[1]=="-")d[1]=-1;var a=d[1]?Number(d[1]):1;var b=d[2]?Number(d[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:c,a:a,b:b})}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);      c = false;',className:'n = h.className(n, r, "#{1}", c);    c = false;',id:'n = h.id(n, r, "#{1}", c);           c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}", c); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m)},pseudo:function(m){if(m[6])m[6]=m[6].replace(/"/g,'\\"');return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m)},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,attrPresence:/^\[([\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/},assertions:{tagName:function(a,b){return b[1].toUpperCase()==a.tagName.toUpperCase()},className:function(a,b){return Element.hasClassName(a,b[1])},id:function(a,b){return a.id===b[1]},attrPresence:function(a,b){return Element.hasAttribute(a,b[1])},attr:function(a,b){var c=Element.readAttribute(a,b[1]);return c&&Selector.operators[b[2]](c,b[5]||b[6])}},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)a.push(node);return a},mark:function(a){var b=Prototype.emptyFunction;for(var i=0,node;node=a[i];i++)node._countedByPrototype=b;return a},unmark:function(a){for(var i=0,node;node=a[i];i++)node._countedByPrototype=undefined;return a},index:function(a,b,c){a._countedByPrototype=Prototype.emptyFunction;if(b){for(var d=a.childNodes,i=d.length-1,j=1;i>=0;i--){var e=d[i];if(e.nodeType==1&&(!c||e._countedByPrototype))e.nodeIndex=j++}}else{for(var i=0,j=1,d=a.childNodes;e=d[i];i++)if(e.nodeType==1&&(!c||e._countedByPrototype))e.nodeIndex=j++}},unique:function(a){if(a.length==0)return a;var b=[],n;for(var i=0,l=a.length;i<l;i++)if(!(n=a[i])._countedByPrototype){n._countedByPrototype=Prototype.emptyFunction;b.push(Element.extend(n))}return Selector.handlers.unmark(b)},descendant:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)h.concat(results,node.getElementsByTagName('*'));return results},child:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++){for(var j=0,child;child=node.childNodes[j];j++)if(child.nodeType==1&&child.tagName!='!')results.push(child)}return results},adjacent:function(a){for(var i=0,results=[],node;node=a[i];i++){var b=this.nextElementSibling(node);if(b)results.push(b)}return results},laterSibling:function(a){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)h.concat(results,Element.nextSiblings(node));return results},nextElementSibling:function(a){while(a=a.nextSibling)if(a.nodeType==1)return a;return null},previousElementSibling:function(a){while(a=a.previousSibling)if(a.nodeType==1)return a;return null},tagName:function(a,b,c,d){var e=c.toUpperCase();var f=[],h=Selector.handlers;if(a){if(d){if(d=="descendant"){for(var i=0,node;node=a[i];i++)h.concat(f,node.getElementsByTagName(c));return f}else a=this[d](a);if(c=="*")return a}for(var i=0,node;node=a[i];i++)if(node.tagName.toUpperCase()===e)f.push(node);return f}else return b.getElementsByTagName(c)},id:function(a,b,c,d){var e=$(c),h=Selector.handlers;if(!e)return[];if(!a&&b==document)return[e];if(a){if(d){if(d=='child'){for(var i=0,node;node=a[i];i++)if(e.parentNode==node)return[e]}else if(d=='descendant'){for(var i=0,node;node=a[i];i++)if(Element.descendantOf(e,node))return[e]}else if(d=='adjacent'){for(var i=0,node;node=a[i];i++)if(Selector.handlers.previousElementSibling(e)==node)return[e]}else a=h[d](a)}for(var i=0,node;node=a[i];i++)if(node==e)return[e];return[]}return(e&&Element.descendantOf(e,b))?[e]:[]},className:function(a,b,c,d){if(a&&d)a=this[d](a);return Selector.handlers.byClassName(a,b,c)},byClassName:function(a,b,c){if(!a)a=Selector.handlers.descendant([b]);var d=' '+c+' ';for(var i=0,results=[],node,nodeClassName;node=a[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==c||(' '+nodeClassName+' ').include(d))results.push(node)}return results},attrPresence:function(a,b,c,d){if(!a)a=b.getElementsByTagName("*");if(a&&d)a=this[d](a);var e=[];for(var i=0,node;node=a[i];i++)if(Element.hasAttribute(node,c))e.push(node);return e},attr:function(a,b,c,d,e,f){if(!a)a=b.getElementsByTagName("*");if(a&&f)a=this[f](a);var g=Selector.operators[e],results=[];for(var i=0,node;node=a[i];i++){var h=Element.readAttribute(node,c);if(h===null)continue;if(g(h,d))results.push(node)}return results},pseudo:function(a,b,c,d,e){if(a&&e)a=this[e](a);if(!a)a=d.getElementsByTagName("*");return Selector.pseudos[b](a,c,d)}},pseudos:{'first-child':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node)}return results},'last-child':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node)}return results},'only-child':function(a,b,c){var h=Selector.handlers;for(var i=0,results=[],node;node=a[i];i++)if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))results.push(node);return results},'nth-child':function(a,b,c){return Selector.pseudos.nth(a,b,c)},'nth-last-child':function(a,b,c){return Selector.pseudos.nth(a,b,c,true)},'nth-of-type':function(a,b,c){return Selector.pseudos.nth(a,b,c,false,true)},'nth-last-of-type':function(a,b,c){return Selector.pseudos.nth(a,b,c,true,true)},'first-of-type':function(a,b,c){return Selector.pseudos.nth(a,"1",c,false,true)},'last-of-type':function(a,b,c){return Selector.pseudos.nth(a,"1",c,true,true)},'only-of-type':function(a,b,c){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](a,b,c),b,c)},getIndices:function(a,b,d){if(a==0)return b>0?[b]:[];return $R(1,d).inject([],function(c,i){if(0==(i-b)%a&&(i-b)/a>=0)c.push(i);return c})},nth:function(c,d,e,f,g){if(c.length==0)return[];if(d=='even')d='2n+0';if(d=='odd')d='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(c);for(var i=0,node;node=c[i];i++){if(!node.parentNode._countedByPrototype){h.index(node.parentNode,f,g);indexed.push(node.parentNode)}}if(d.match(/^\d+$/)){d=Number(d);for(var i=0,node;node=c[i];i++)if(node.nodeIndex==d)results.push(node)}else if(m=d.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(m[1]=="-")m[1]=-1;var a=m[1]?Number(m[1]):1;var b=m[2]?Number(m[2]):0;var k=Selector.pseudos.getIndices(a,b,c.length);for(var i=0,node,l=k.length;node=c[i];i++){for(var j=0;j<l;j++)if(node.nodeIndex==k[j])results.push(node)}}h.unmark(c);h.unmark(indexed);return results},'empty':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++){if(node.tagName=='!'||(node.firstChild&&!node.innerHTML.match(/^\s*$/)))continue;results.push(node)}return results},'not':function(a,b,c){var h=Selector.handlers,selectorType,m;var d=new Selector(b).findElements(c);h.mark(d);for(var i=0,results=[],node;node=a[i];i++)if(!node._countedByPrototype)results.push(node);h.unmark(d);return results},'enabled':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(!node.disabled)results.push(node);return results},'disabled':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(node.disabled)results.push(node);return results},'checked':function(a,b,c){for(var i=0,results=[],node;node=a[i];i++)if(node.checked)results.push(node);return results}},operators:{'=':function(a,v){return a==v},'!=':function(a,v){return a!=v},'^=':function(a,v){return a.startsWith(v)},'$=':function(a,v){return a.endsWith(v)},'*=':function(a,v){return a.include(v)},'~=':function(a,v){return(' '+a+' ').include(' '+v+' ')},'|=':function(a,v){return('-'+a.toUpperCase()+'-').include('-'+v.toUpperCase()+'-')}},split:function(a){var b=[];a.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){b.push(m[1].strip())});return b},matchElements:function(a,b){var c=$$(b),h=Selector.handlers;h.mark(c);for(var i=0,results=[],element;element=a[i];i++)if(element._countedByPrototype)results.push(element);h.unmark(c);return results},findElement:function(a,b,c){if(Object.isNumber(b)){c=b;b=false}return Selector.matchElements(a,b||'*')[c||0]},findChildElements:function(a,b){b=Selector.split(b.join(','));var c=[],h=Selector.handlers;for(var i=0,l=b.length,selector;i<l;i++){selector=new Selector(b[i].strip());h.concat(c,selector.findElements(a))}return(l>1)?h.unique(c):c}});if(Prototype.Browser.IE){Object.extend(Selector.handlers,{concat:function(a,b){for(var i=0,node;node=b[i];i++)if(node.tagName!=="!")a.push(node);return a},unmark:function(a){for(var i=0,node;node=a[i];i++)node.removeAttribute('_countedByPrototype');return a}})}function $$(){return Selector.findChildElements(document,$A(arguments))}var Form={reset:function(a){$(a).reset();return a},serializeElements:function(c,d){if(typeof d!='object')d={hash:!!d};else if(Object.isUndefined(d.hash))d.hash=true;var e,value,submitted=false,submit=d.submit;var f=c.inject({},function(a,b){if(!b.disabled&&b.name){e=b.name;value=$(b).getValue();if(value!=null&&(b.type!='submit'||(!submitted&&submit!==false&&(!submit||e==submit)&&(submitted=true)))){if(e in a){if(!Object.isArray(a[e]))a[e]=[a[e]];a[e].push(value)}else a[e]=value}}return a});return d.hash?f:Object.toQueryString(f)}};Form.Methods={serialize:function(a,b){return Form.serializeElements(Form.getElements(a),b)},getElements:function(c){return $A($(c).getElementsByTagName('*')).inject([],function(a,b){if(Form.Element.Serializers[b.tagName.toLowerCase()])a.push(Element.extend(b));return a})},getInputs:function(a,b,c){a=$(a);var d=a.getElementsByTagName('input');if(!b&&!c)return $A(d).map(Element.extend);for(var i=0,matchingInputs=[],length=d.length;i<length;i++){var e=d[i];if((b&&e.type!=b)||(c&&e.name!=c))continue;matchingInputs.push(Element.extend(e))}return matchingInputs},disable:function(a){a=$(a);Form.getElements(a).invoke('disable');return a},enable:function(a){a=$(a);Form.getElements(a).invoke('enable');return a},findFirstElement:function(b){var c=$(b).getElements().findAll(function(a){return'hidden'!=a.type&&!a.disabled});var d=c.findAll(function(a){return a.hasAttribute('tabIndex')&&a.tabIndex>=0}).sortBy(function(a){return a.tabIndex}).first();return d?d:c.find(function(a){return['input','select','textarea'].include(a.tagName.toLowerCase())})},focusFirstElement:function(a){a=$(a);a.findFirstElement().activate();return a},request:function(a,b){a=$(a),b=Object.clone(b||{});var c=b.parameters,action=a.readAttribute('action')||'';if(action.blank())action=window.location.href;b.parameters=a.serialize(true);if(c){if(Object.isString(c))c=c.toQueryParams();Object.extend(b.parameters,c)}if(a.hasAttribute('method')&&!b.method)b.method=a.method;return new Ajax.Request(action,b)}};Form.Element={focus:function(a){$(a).focus();return a},select:function(a){$(a).select();return a}};Form.Element.Methods={serialize:function(a){a=$(a);if(!a.disabled&&a.name){var b=a.getValue();if(b!=undefined){var c={};c[a.name]=b;return Object.toQueryString(c)}}return''},getValue:function(a){a=$(a);var b=a.tagName.toLowerCase();return Form.Element.Serializers[b](a)},setValue:function(a,b){a=$(a);var c=a.tagName.toLowerCase();Form.Element.Serializers[c](a,b);return a},clear:function(a){$(a).value='';return a},present:function(a){return $(a).value!=''},activate:function(a){a=$(a);try{a.focus();if(a.select&&(a.tagName.toLowerCase()!='input'||!['button','reset','submit'].include(a.type)))a.select()}catch(e){}return a},disable:function(a){a=$(a);a.blur();a.disabled=true;return a},enable:function(a){a=$(a);a.disabled=false;return a}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(a,b){switch(a.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(a,b);default:return Form.Element.Serializers.textarea(a,b)}},inputSelector:function(a,b){if(Object.isUndefined(b))return a.checked?a.value:null;else a.checked=!!b},textarea:function(a,b){if(Object.isUndefined(b))return a.value;else a.value=b},select:function(a,b){if(Object.isUndefined(b))return this[a.type=='select-one'?'selectOne':'selectMany'](a);else{var c,value,single=!Object.isArray(b);for(var i=0,length=a.length;i<length;i++){c=a.options[i];value=this.optionValue(c);if(single){if(value==b){c.selected=true;return}}else c.selected=b.include(value)}}},selectOne:function(a){var b=a.selectedIndex;return b>=0?this.optionValue(a.options[b]):null},selectMany:function(a){var b,length=a.length;if(!length)return null;for(var i=0,b=[];i<length;i++){var c=a.options[i];if(c.selected)b.push(this.optionValue(c))}return b},optionValue:function(a){return Element.extend(a).hasAttribute('value')?a.value:a.text}};Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,b,c,d){$super(d,c);this.element=$(b);this.lastValue=this.getValue()},execute:function(){var a=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(a)?this.lastValue!=a:String(this.lastValue)!=String(a)){this.callback(this.element,a);this.lastValue=a}}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});Abstract.EventObserver=Class.create({initialize:function(a,b){this.element=$(a);this.callback=b;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=='form')this.registerFormCallbacks();else this.registerCallback(this.element)},onElementEvent:function(){var a=this.getValue();if(this.lastValue!=a){this.callback(this.element,a);this.lastValue=a}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},registerCallback:function(a){if(a.type){switch(a.type.toLowerCase()){case'checkbox':case'radio':Event.observe(a,'click',this.onElementEvent.bind(this));break;default:Event.observe(a,'change',this.onElementEvent.bind(this));break}}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});if(!window.Event)var Event={};Object.extend(Event,{KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,cache:{},relatedTarget:function(a){var b;switch(a.type){case'mouseover':b=a.fromElement;break;case'mouseout':b=a.toElement;break;default:return null}return Element.extend(b)}});Event.Methods=(function(){var e;if(Prototype.Browser.IE){var f={0:1,1:4,2:2};e=function(a,b){return a.button==f[b]}}else if(Prototype.Browser.WebKit){e=function(a,b){switch(b){case 0:return a.which==1&&!a.metaKey;case 1:return a.which==1&&a.metaKey;default:return false}}}else{e=function(a,b){return a.which?(a.which===b+1):(a.button===b)}}return{isLeftClick:function(a){return e(a,0)},isMiddleClick:function(a){return e(a,1)},isRightClick:function(a){return e(a,2)},element:function(a){var b=Event.extend(a).target;return Element.extend(b.nodeType==Node.TEXT_NODE?b.parentNode:b)},findElement:function(a,b){var c=Event.element(a);if(!b)return c;var d=[c].concat(c.ancestors());return Selector.findElement(d,b,0)},pointer:function(a){return{x:a.pageX||(a.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),y:a.pageY||(a.clientY+(document.documentElement.scrollTop||document.body.scrollTop))}},pointerX:function(a){return Event.pointer(a).x},pointerY:function(a){return Event.pointer(a).y},stop:function(a){Event.extend(a);a.preventDefault();a.stopPropagation();a.stopped=true}}})();Event.extend=(function(){var c=Object.keys(Event.Methods).inject({},function(m,a){m[a]=Event.Methods[a].methodize();return m});if(Prototype.Browser.IE){Object.extend(c,{stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}});return function(a){if(!a)return false;if(a._extendedByPrototype)return a;a._extendedByPrototype=Prototype.emptyFunction;var b=Event.pointer(a);Object.extend(a,{target:a.srcElement,relatedTarget:Event.relatedTarget(a),pageX:b.x,pageY:b.y});return Object.extend(a,c)}}else{Event.prototype=Event.prototype||document.createEvent("HTMLEvents").__proto__;Object.extend(Event.prototype,c);return Prototype.K}})();Object.extend(Event,(function(){var h=Event.cache;function getEventID(a){if(a._prototypeEventID)return a._prototypeEventID[0];arguments.callee.id=arguments.callee.id||1;return a._prototypeEventID=[++arguments.callee.id]}function getDOMEventName(a){if(a&&a.include(':'))return"dataavailable";return a}function getCacheForID(a){return h[a]=h[a]||{}}function getWrappersForEventName(a,b){var c=getCacheForID(a);return c[b]=c[b]||[]}function createWrapper(b,d,e){var f=getEventID(b);var c=getWrappersForEventName(f,d);if(c.pluck("handler").include(e))return false;var g=function(a){if(!Event||!Event.extend||(a.eventName&&a.eventName!=d))return false;Event.extend(a);e.call(b,a)};g.handler=e;c.push(g);return g}function findWrapper(b,d,e){var c=getWrappersForEventName(b,d);return c.find(function(a){return a.handler==e})}function destroyWrapper(a,b,d){var c=getCacheForID(a);if(!c[b])return false;c[b]=c[b].without(findWrapper(a,b,d))}function destroyCache(){for(var a in h)for(var b in h[a])h[a][b]=null}if(window.attachEvent){window.attachEvent("onunload",destroyCache)}return{observe:function(a,b,c){a=$(a);var d=getDOMEventName(b);var e=createWrapper(a,b,c);if(!e)return a;if(a.addEventListener){a.addEventListener(d,e,false)}else{a.attachEvent("on"+d,e)}return a},stopObserving:function(b,c,d){b=$(b);var e=getEventID(b),name=getDOMEventName(c);if(!d&&c){getWrappersForEventName(e,c).each(function(a){b.stopObserving(c,a.handler)});return b}else if(!c){Object.keys(getCacheForID(e)).each(function(a){b.stopObserving(a)});return b}var f=findWrapper(e,c,d);if(!f)return b;if(b.removeEventListener){b.removeEventListener(name,f,false)}else{b.detachEvent("on"+name,f)}destroyWrapper(e,c,d);return b},fire:function(a,b,c){a=$(a);if(a==document&&document.createEvent&&!a.dispatchEvent)a=document.documentElement;var d;if(document.createEvent){d=document.createEvent("HTMLEvents");d.initEvent("dataavailable",true,true)}else{d=document.createEventObject();d.eventType="ondataavailable"}d.eventName=b;d.memo=c||{};if(document.createEvent){a.dispatchEvent(d)}else{a.fireEvent(d.eventType,d)}return Event.extend(d)}}})());Object.extend(Event,Event.Methods);Element.addMethods({fire:Event.fire,observe:Event.observe,stopObserving:Event.stopObserving});Object.extend(document,{fire:Element.Methods.fire.methodize(),observe:Element.Methods.observe.methodize(),stopObserving:Element.Methods.stopObserving.methodize(),loaded:false});(function(){var a;function fireContentLoadedEvent(){if(document.loaded)return;if(a)window.clearInterval(a);document.fire("dom:loaded");document.loaded=true}if(document.addEventListener){if(Prototype.Browser.WebKit){a=window.setInterval(function(){if(/loaded|complete/.test(document.readyState))fireContentLoadedEvent()},0);Event.observe(window,"load",fireContentLoadedEvent)}else{document.addEventListener("DOMContentLoaded",fireContentLoadedEvent,false)}}else{document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");$("__onDOMContentLoaded").onreadystatechange=function(){if(this.readyState=="complete"){this.onreadystatechange=null;fireContentLoadedEvent()}}}})();Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;var Insertion={Before:function(a,b){return Element.insert(a,{before:b})},Top:function(a,b){return Element.insert(a,{top:b})},Bottom:function(a,b){return Element.insert(a,{bottom:b})},After:function(a,b){return Element.insert(a,{after:b})}};var $continue=new Error('"throw $continue" is deprecated, use "return" instead');var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},within:function(a,x,y){if(this.includeScrollOffsets)return this.withinIncludingScrolloffsets(a,x,y);this.xcomp=x;this.ycomp=y;this.offset=Element.cumulativeOffset(a);return(y>=this.offset[1]&&y<this.offset[1]+a.offsetHeight&&x>=this.offset[0]&&x<this.offset[0]+a.offsetWidth)},withinIncludingScrolloffsets:function(a,x,y){var b=Element.cumulativeScrollOffset(a);this.xcomp=x+b[0]-this.deltaX;this.ycomp=y+b[1]-this.deltaY;this.offset=Element.cumulativeOffset(a);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+a.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+a.offsetWidth)},overlap:function(a,b){if(!a)return 0;if(a=='vertical')return((this.offset[1]+b.offsetHeight)-this.ycomp)/b.offsetHeight;if(a=='horizontal')return((this.offset[0]+b.offsetWidth)-this.xcomp)/b.offsetWidth},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(a){Position.prepare();return Element.absolutize(a)},relativize:function(a){Position.prepare();return Element.relativize(a)},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(a,b,c){c=c||{};return Element.clonePosition(b,a,c)}};if(!document.getElementsByClassName)document.getElementsByClassName=function(f){function iter(a){return a.blank()?null:"[contains(concat(' ', @class, ' '), ' "+a+" ')]"}f.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(a,b){b=b.toString().strip();var c=/\s/.test(b)?$w(b).map(iter).join(''):iter(b);return c?document._getElementsByXPath('.//*'+c,a):[]}:function(b,c){c=c.toString().strip();var d=[],classNames=(/\s/.test(c)?$w(c):null);if(!classNames&&!c)return d;var e=$(b).getElementsByTagName('*');c=' '+c+' ';for(var i=0,child,cn;child=e[i];i++){if(child.className&&(cn=' '+child.className+' ')&&(cn.include(c)||(classNames&&classNames.all(function(a){return!a.toString().blank()&&cn.include(' '+a+' ')}))))d.push(Element.extend(child))}return d};return function(a,b){return $(b||document.body).getElementsByClassName(a)}}(Element.Methods);Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(a){this.element=$(a)},_each:function(b){this.element.className.split(/\s+/).select(function(a){return a.length>0})._each(b)},set:function(a){this.element.className=a},add:function(a){if(this.include(a))return;this.set($A(this).concat(a).join(' '))},remove:function(a){if(!this.include(a))return;this.set($A(this).without(a).join(' '))},toString:function(){return $A(this).join(' ')}};Object.extend(Element.ClassNames.prototype,Enumerable);Element.addMethods();
//scriptaculous.js
var Scriptaculous={Version:'1.8.1',require:function(a){document.write('<script type="text/javascript" src="'+a+'"><\/script>')},REQUIRED_PROTOTYPE:'1.6.0',load:function(){function convertVersionString(a){var r=a.split('.');return parseInt(r[0])*100000+parseInt(r[1])*1000+parseInt(r[2])}if((typeof Prototype=='undefined')||(typeof Element=='undefined')||(typeof Element.Methods=='undefined')||(convertVersionString(Prototype.Version)<convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))throw("script.aculo.us requires the Prototype JavaScript framework >= "+Scriptaculous.REQUIRED_PROTOTYPE);var d=/(proto|scripta)culous[a-z0-9._-]*\.js(\?.*)?$/;$A(document.getElementsByTagName("script")).findAll(function(s){return(s.src&&s.src.match(d))}).each(function(s){var b=s.src.replace(d,'');var c=(s.src.match(/\?.*load=([a-z,]*)/)||['',''])[1];c.split(',').without('').each(function(a){Scriptaculous.require(b+a+'.js')})})}};
//builder.js
var Builder={NODEMAP:{AREA:'map',CAPTION:'table',COL:'table',COLGROUP:'table',LEGEND:'fieldset',OPTGROUP:'select',OPTION:'select',PARAM:'object',TBODY:'table',TD:'table',TFOOT:'table',TH:'table',THEAD:'table',TR:'table'},node:function(a){a=a.toUpperCase();var b=this.NODEMAP[a]||'div';var c=document.createElement(b);try{c.innerHTML="<"+a+"></"+a+">"}catch(e){}var d=c.firstChild||null;if(d&&(d.tagName.toUpperCase()!=a))d=d.getElementsByTagName(a)[0];if(!d)d=document.createElement(a);if(!d)return;if(arguments[1])if(this._isStringOrNumber(arguments[1])||(arguments[1]instanceof Array)||arguments[1].tagName){this._children(d,arguments[1])}else{var f=this._attributes(arguments[1]);if(f.length){try{c.innerHTML="<"+a+" "+f+"></"+a+">"}catch(e){}d=c.firstChild||null;if(!d){d=document.createElement(a);for(attr in arguments[1])d[attr=='class'?'className':attr]=arguments[1][attr]}if(d.tagName.toUpperCase()!=a)d=c.getElementsByTagName(a)[0]}}if(arguments[2])this._children(d,arguments[2]);return d},_text:function(a){return document.createTextNode(a)},ATTR_MAP:{'className':'class','htmlFor':'for'},_attributes:function(a){var b=[];for(attribute in a)b.push((attribute in this.ATTR_MAP?this.ATTR_MAP[attribute]:attribute)+'="'+a[attribute].toString().escapeHTML().gsub(/"/,'&quot;')+'"');return b.join(" ")},_children:function(a,b){if(b.tagName){a.appendChild(b);return}if(typeof b=='object'){b.flatten().each(function(e){if(typeof e=='object')a.appendChild(e);else if(Builder._isStringOrNumber(e))a.appendChild(Builder._text(e))})}else if(Builder._isStringOrNumber(b))a.appendChild(Builder._text(b))},_isStringOrNumber:function(a){return(typeof a=='string'||typeof a=='number')},build:function(a){var b=this.node('div');$(b).update(a.strip());return b.down()},dump:function(b){if(typeof b!='object'&&typeof b!='function')b=window;var c=("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY "+"BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET "+"FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+"KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+"PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+"TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);c.each(function(a){b[a]=function(){return Builder.node.apply(Builder,[a].concat($A(arguments)))}})}};
//effects.js
String.prototype.parseColor=function(){var a='#';if(this.slice(0,4)=='rgb('){var b=this.slice(4,this.length-1).split(',');var i=0;do{a+=parseInt(b[i]).toColorPart()}while(++i<3)}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)a+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)a=this.toLowerCase()}}return(a.length==7?a:(arguments[0]||this))};Element.collectTextNodes=function(b){return $A($(b).childNodes).collect(function(a){return(a.nodeType==3?a.nodeValue:(a.hasChildNodes()?Element.collectTextNodes(a):''))}).flatten().join('')};Element.collectTextNodesIgnoreClass=function(b,c){return $A($(b).childNodes).collect(function(a){return(a.nodeType==3?a.nodeValue:((a.hasChildNodes()&&!Element.hasClassName(a,c))?Element.collectTextNodesIgnoreClass(a,c):''))}).flatten().join('')};Element.setContentZoom=function(a,b){a=$(a);a.setStyle({fontSize:(b/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return a};Element.getInlineOpacity=function(a){return $(a).style.opacity||''};Element.forceRerendering=function(a){try{a=$(a);var n=document.createTextNode(' ');a.appendChild(n);a.removeChild(n)}catch(e){}};var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},Transitions:{linear:Prototype.K,sinoidal:function(a){return(-Math.cos(a*Math.PI)/2)+0.5},reverse:function(a){return 1-a},flicker:function(a){var a=((-Math.cos(a*Math.PI)/4)+0.75)+Math.random()/4;return a>1?1:a},wobble:function(a){return(-Math.cos(a*Math.PI*(9*a))/2)+0.5},pulse:function(a,b){b=b||5;return(((a%(1/b))*b).round()==0?((a*b*2)-(a*b*2).floor()):1-((a*b*2)-(a*b*2).floor()))},spring:function(a){return 1-(Math.cos(a*4.5*Math.PI)*Math.exp(-a*6))},none:function(a){return 0},full:function(a){return 1}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(c){var d='position:relative';if(Prototype.Browser.IE)d+=';zoom:1';c=$(c);$A(c.childNodes).each(function(b){if(b.nodeType==3){b.nodeValue.toArray().each(function(a){c.insertBefore(new Element('span',{style:d}).update(a==' '?String.fromCharCode(160):a),b)});Element.remove(b)}})},multiple:function(c,d){var e;if(((typeof c=='object')||Object.isFunction(c))&&(c.length))e=c;else e=$(c).childNodes;var f=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var g=f.delay;$A(e).each(function(a,b){new d(a,Object.extend(f,{delay:b*f.speed+g}))})},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(a,b){a=$(a);b=(b||'appear').toLowerCase();var c=Object.extend({queue:{position:'end',scope:(a.id||'global'),limit:1}},arguments[2]||{});Effect[a.visible()?Effect.PAIRS[b][1]:Effect.PAIRS[b][0]](a,c)}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null},_each:function(a){this.effects._each(a)},add:function(a){var b=new Date().getTime();var c=Object.isString(a.options.queue)?a.options.queue:a.options.queue.position;switch(c){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=a.finishOn;e.finishOn+=a.finishOn});break;case'with-last':b=this.effects.pluck('startOn').max()||b;break;case'end':b=this.effects.pluck('finishOn').max()||b;break}a.startOn+=b;a.finishOn+=b;if(!a.options.queue.limit||(this.effects.length<a.options.queue.limit))this.effects.push(a);if(!this.interval)this.interval=setInterval(this.loop.bind(this),15)},remove:function(a){this.effects=this.effects.reject(function(e){return e==a});if(this.effects.length==0){clearInterval(this.interval);this.interval=null}},loop:function(){var a=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)this.effects[i]&&this.effects[i].loop(a)}});Effect.Queues={instances:$H(),get:function(a){if(!Object.isString(a))return a;return this.instances.get(a)||this.instances.set(a,new Effect.ScopedQueue())}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(c){function codeForEvent(a,b){return((a[b+'Internal']?'this.options.'+b+'Internal(this);':'')+(a[b]?'this.options.'+b+'(this);':''))}if(c&&c.transition===false)c.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),c||{});this.currentFrame=0;this.state='idle';this.startOn=this.options.delay*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;eval('this.render = function(pos){ '+'if (this.state=="idle"){this.state="running";'+codeForEvent(this.options,'beforeSetup')+(this.setup?'this.setup();':'')+codeForEvent(this.options,'afterSetup')+'};if (this.state=="running"){'+'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+'this.position=pos;'+codeForEvent(this.options,'beforeUpdate')+(this.update?'this.update(pos);':'')+codeForEvent(this.options,'afterUpdate')+'}}');this.event('beforeStart');if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).add(this)},loop:function(a){if(a>=this.startOn){if(a>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return}var b=(a-this.startOn)/this.totalTime,frame=(b*this.totalFrames).round();if(frame>this.currentFrame){this.render(b);this.currentFrame=frame}}},cancel:function(){if(!this.options.sync)Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).remove(this);this.state='finished'},event:function(a){if(this.options[a+'Internal'])this.options[a+'Internal'](this);if(this.options[a])this.options[a](this)},inspect:function(){var a=$H();for(property in this)if(!Object.isFunction(this[property]))a.set(property,this[property]);return'#<Effect:'+a.inspect()+',options:'+$H(this.options).inspect()+'>'}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(a){this.effects=a||[];this.start(arguments[1])},update:function(a){this.effects.invoke('render',a)},finish:function(b){this.effects.each(function(a){a.render(1.0);a.cancel();a.event('beforeFinish');if(a.finish)a.finish(b);a.event('afterFinish')})}});Effect.Tween=Class.create(Effect.Base,{initialize:function(b,c,d){b=Object.isString(b)?$(b):b;var e=$A(arguments),method=e.last(),options=e.length==5?e[3]:null;this.method=Object.isFunction(method)?method.bind(b):Object.isFunction(b[method])?b[method].bind(b):function(a){b[method]=a};this.start(Object.extend({from:c,to:d},options||{}))},update:function(a){this.method(a)}});Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}))},update:Prototype.emptyFunction});Effect.Opacity=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))this.element.setStyle({zoom:1});var b=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(b)},update:function(a){this.element.setOpacity(a)}});Effect.Move=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var b=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(b)},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle('left')||'0');this.originalTop=parseFloat(this.element.getStyle('top')||'0');if(this.options.mode=='absolute'){this.options.x=this.options.x-this.originalLeft;this.options.y=this.options.y-this.originalTop}},update:function(a){this.element.setStyle({left:(this.options.x*a+this.originalLeft).round()+'px',top:(this.options.y*a+this.originalTop).round()+'px'})}});Effect.MoveBy=function(a,b,c){return new Effect.Move(a,Object.extend({x:c,y:b},arguments[3]||{}))};Effect.Scale=Class.create(Effect.Base,{initialize:function(a,b){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var c=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:b},arguments[2]||{});this.start(c)},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle('position');this.originalStyle={};['top','left','width','height','fontSize'].each(function(k){this.originalStyle[k]=this.element.style[k]}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var b=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(a){if(b.indexOf(a)>0){this.fontSize=parseFloat(b);this.fontSizeType=a}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode=='box')this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth]},update:function(a){var b=(this.options.scaleFrom/100.0)+(this.factor*a);if(this.options.scaleContent&&this.fontSize)this.element.setStyle({fontSize:this.fontSize*b+this.fontSizeType});this.setDimensions(this.dims[0]*b,this.dims[1]*b)},finish:function(a){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle)},setDimensions:function(a,b){var d={};if(this.options.scaleX)d.width=b.round()+'px';if(this.options.scaleY)d.height=a.round()+'px';if(this.options.scaleFromCenter){var c=(a-this.dims[0])/2;var e=(b-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-c+'px';if(this.options.scaleX)d.left=this.originalLeft-e+'px'}else{if(this.options.scaleY)d.top=-c+'px';if(this.options.scaleX)d.left=-e+'px'}}this.element.setStyle(d)}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(a){this.element=$(a);if(!this.element)throw(Effect._elementDoesNotExistError);var b=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(b)},setup:function(){if(this.element.getStyle('display')=='none'){this.cancel();return}this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle('background-image');this.element.setStyle({backgroundImage:'none'})}if(!this.options.endcolor)this.options.endcolor=this.element.getStyle('background-color').parseColor('#ffffff');if(!this.options.restorecolor)this.options.restorecolor=this.element.getStyle('background-color');this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this))},update:function(a){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*a)).round().toColorPart())}.bind(this))})},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}))}});Effect.ScrollTo=function(a){var b=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(a).cumulativeOffset(),max=document.viewport.getScrollOffsets[0]-document.viewport.getHeight();if(b.offset)elementOffsets[1]+=b.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1]>max?max:elementOffsets[1],b,function(p){scrollTo(scrollOffsets.left,p.round())})};Effect.Fade=function(b){b=$(b);var c=b.getInlineOpacity();var d=Object.extend({from:b.getOpacity()||1.0,to:0.0,afterFinishInternal:function(a){if(a.options.to!=0)return;a.element.hide().setStyle({opacity:c})}},arguments[1]||{});return new Effect.Opacity(b,d)};Effect.Appear=function(b){b=$(b);var c=Object.extend({from:(b.getStyle('display')=='none'?0.0:b.getOpacity()||0.0),to:1.0,afterFinishInternal:function(a){a.element.forceRerendering()},beforeSetup:function(a){a.element.setOpacity(a.options.from).show()}},arguments[1]||{});return new Effect.Opacity(b,c)};Effect.Puff=function(b){b=$(b);var c={opacity:b.getInlineOpacity(),position:b.getStyle('position'),top:b.style.top,left:b.style.left,width:b.style.width,height:b.style.height};return new Effect.Parallel([new Effect.Scale(b,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(b,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(a){Position.absolutize(a.effects[0].element)},afterFinishInternal:function(a){a.effects[0].element.hide().setStyle(c)}},arguments[1]||{}))};Effect.BlindUp=function(b){b=$(b);b.makeClipping();return new Effect.Scale(b,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(a){a.element.hide().undoClipping()}},arguments[1]||{}))};Effect.BlindDown=function(b){b=$(b);var c=b.getDimensions();return new Effect.Scale(b,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:c.height,originalWidth:c.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makeClipping().setStyle({height:'0px'}).show()},afterFinishInternal:function(a){a.element.undoClipping()}},arguments[1]||{}))};Effect.SwitchOff=function(c){c=$(c);var d=c.getInlineOpacity();return new Effect.Appear(c,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(b){new Effect.Scale(b.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(a){a.element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned().setStyle({opacity:d})}})}},arguments[1]||{}))};Effect.DropOut=function(b){b=$(b);var c={top:b.getStyle('top'),left:b.getStyle('left'),opacity:b.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(b,{x:0,y:100,sync:true}),new Effect.Opacity(b,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(a){a.effects[0].element.makePositioned()},afterFinishInternal:function(a){a.effects[0].element.hide().undoPositioned().setStyle(c)}},arguments[1]||{}))};Effect.Shake=function(g){g=$(g);var h=Object.extend({distance:20,duration:0.5},arguments[1]||{});var i=parseFloat(h.distance);var j=parseFloat(h.duration)/10.0;var k={top:g.getStyle('top'),left:g.getStyle('left')};return new Effect.Move(g,{x:i,y:0,duration:j,afterFinishInternal:function(f){new Effect.Move(f.element,{x:-i*2,y:0,duration:j*2,afterFinishInternal:function(e){new Effect.Move(e.element,{x:i*2,y:0,duration:j*2,afterFinishInternal:function(d){new Effect.Move(d.element,{x:-i*2,y:0,duration:j*2,afterFinishInternal:function(c){new Effect.Move(c.element,{x:i*2,y:0,duration:j*2,afterFinishInternal:function(b){new Effect.Move(b.element,{x:-i,y:0,duration:j,afterFinishInternal:function(a){a.element.undoPositioned().setStyle(k)}})}})}})}})}})}})};Effect.SlideDown=function(b){b=$(b).cleanWhitespace();var c=b.down().getStyle('bottom');var d=b.getDimensions();return new Effect.Scale(b,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();if(window.opera)a.element.setStyle({top:''});a.element.makeClipping().setStyle({height:'0px'}).show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:(a.dims[0]-a.element.clientHeight)+'px'})},afterFinishInternal:function(a){a.element.undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},arguments[1]||{}))};Effect.SlideUp=function(b){b=$(b).cleanWhitespace();var c=b.down().getStyle('bottom');var d=b.getDimensions();return new Effect.Scale(b,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:d.height,originalWidth:d.width},restoreAfterFinish:true,afterSetup:function(a){a.element.makePositioned();a.element.down().makePositioned();if(window.opera)a.element.setStyle({top:''});a.element.makeClipping().show()},afterUpdateInternal:function(a){a.element.down().setStyle({bottom:(a.dims[0]-a.element.clientHeight)+'px'})},afterFinishInternal:function(a){a.element.hide().undoClipping().undoPositioned();a.element.down().undoPositioned().setStyle({bottom:c})}},arguments[1]||{}))};Effect.Squish=function(b){return new Effect.Scale(b,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(a){a.element.makeClipping()},afterFinishInternal:function(a){a.element.hide().undoClipping()}})};Effect.Grow=function(c){c=$(c);var d=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var e={top:c.style.top,left:c.style.left,height:c.style.height,width:c.style.width,opacity:c.getInlineOpacity()};var f=c.getDimensions();var g,initialMoveY;var h,moveY;switch(d.direction){case'top-left':g=initialMoveY=h=moveY=0;break;case'top-right':g=f.width;initialMoveY=moveY=0;h=-f.width;break;case'bottom-left':g=h=0;initialMoveY=f.height;moveY=-f.height;break;case'bottom-right':g=f.width;initialMoveY=f.height;h=-f.width;moveY=-f.height;break;case'center':g=f.width/2;initialMoveY=f.height/2;h=-f.width/2;moveY=-f.height/2;break}return new Effect.Move(c,{x:g,y:initialMoveY,duration:0.01,beforeSetup:function(a){a.element.hide().makeClipping().makePositioned()},afterFinishInternal:function(b){new Effect.Parallel([new Effect.Opacity(b.element,{sync:true,to:1.0,from:0.0,transition:d.opacityTransition}),new Effect.Move(b.element,{x:h,y:moveY,sync:true,transition:d.moveTransition}),new Effect.Scale(b.element,100,{scaleMode:{originalHeight:f.height,originalWidth:f.width},sync:true,scaleFrom:window.opera?1:0,transition:d.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(a){a.effects[0].element.setStyle({height:'0px'}).show()},afterFinishInternal:function(a){a.effects[0].element.undoClipping().undoPositioned().setStyle(e)}},d))}})};Effect.Shrink=function(b){b=$(b);var c=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var d={top:b.style.top,left:b.style.left,height:b.style.height,width:b.style.width,opacity:b.getInlineOpacity()};var e=b.getDimensions();var f,moveY;switch(c.direction){case'top-left':f=moveY=0;break;case'top-right':f=e.width;moveY=0;break;case'bottom-left':f=0;moveY=e.height;break;case'bottom-right':f=e.width;moveY=e.height;break;case'center':f=e.width/2;moveY=e.height/2;break}return new Effect.Parallel([new Effect.Opacity(b,{sync:true,to:0.0,from:1.0,transition:c.opacityTransition}),new Effect.Scale(b,window.opera?1:0,{sync:true,transition:c.scaleTransition,restoreAfterFinish:true}),new Effect.Move(b,{x:f,y:moveY,sync:true,transition:c.moveTransition})],Object.extend({beforeStartInternal:function(a){a.effects[0].element.makePositioned().makeClipping()},afterFinishInternal:function(a){a.effects[0].element.hide().undoClipping().undoPositioned().setStyle(d)}},c))};Effect.Pulsate=function(b){b=$(b);var c=arguments[1]||{};var d=b.getInlineOpacity();var e=c.transition||Effect.Transitions.sinoidal;var f=function(a){return e(1-Effect.Transitions.pulse(a,c.pulses))};f.bind(e);return new Effect.Opacity(b,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(a){a.element.setStyle({opacity:d})}},c),{transition:f}))};Effect.Fold=function(c){c=$(c);var d={top:c.style.top,left:c.style.left,width:c.style.width,height:c.style.height};c.makeClipping();return new Effect.Scale(c,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(b){new Effect.Scale(c,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(a){a.element.hide().undoClipping().setStyle(d)}})}},arguments[1]||{}))};Effect.Morph=Class.create(Effect.Base,{initialize:function(c){this.element=$(c);if(!this.element)throw(Effect._elementDoesNotExistError);var d=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(d.style))this.style=$H(d.style);else{if(d.style.include(':'))this.style=d.style.parseStyle();else{this.element.addClassName(d.style);this.style=$H(this.element.getStyles());this.element.removeClassName(d.style);var e=this.element.getStyles();this.style=this.style.reject(function(a){return a.value==e[a.key]});d.afterFinishInternal=function(b){b.element.addClassName(b.options.style);b.transforms.each(function(a){b.element.style[a.style]=''})}}}this.start(d)},setup:function(){function parseColor(a){if(!a||['rgba(0, 0, 0, 0)','transparent'].include(a))a='#ffffff';a=a.parseColor();return $R(0,2).map(function(i){return parseInt(a.slice(i*2+1,i*2+3),16)})}this.transforms=this.style.map(function(a){var b=a[0],value=a[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color'}else if(b=='opacity'){value=parseFloat(value);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))this.element.setStyle({zoom:1})}else if(Element.CSS_LENGTH.test(value)){var c=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(c[1]);unit=(c.length==3)?c[2]:null}var d=this.element.getStyle(b);return{style:b.camelize(),originalValue:unit=='color'?parseColor(d):parseFloat(d||0),targetValue:unit=='color'?parseColor(value):value,unit:unit}}.bind(this)).reject(function(a){return((a.originalValue==a.targetValue)||(a.unit!='color'&&(isNaN(a.originalValue)||isNaN(a.targetValue))))})},update:function(a){var b={},transform,i=this.transforms.length;while(i--)b[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+(Math.round(transform.originalValue[0]+(transform.targetValue[0]-transform.originalValue[0])*a)).toColorPart()+(Math.round(transform.originalValue[1]+(transform.targetValue[1]-transform.originalValue[1])*a)).toColorPart()+(Math.round(transform.originalValue[2]+(transform.targetValue[2]-transform.originalValue[2])*a)).toColorPart():(transform.originalValue+(transform.targetValue-transform.originalValue)*a).toFixed(3)+(transform.unit===null?'':transform.unit);this.element.setStyle(b,true)}});Effect.Transform=Class.create({initialize:function(a){this.tracks=[];this.options=arguments[1]||{};this.addTracks(a)},addTracks:function(c){c.each(function(a){a=$H(a);var b=a.values().first();this.tracks.push($H({ids:a.keys().first(),effect:Effect.Morph,options:{style:b}}))}.bind(this));return this},play:function(){return new Effect.Parallel(this.tracks.map(function(a){var b=a.get('ids'),effect=a.get('effect'),options=a.get('options');var c=[$(b)||$$(b)].flatten();return c.map(function(e){return new effect(e,Object.extend({sync:true},options))})}).flatten(),this.options)}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+'borderRightColor borderRightStyle borderRightWidth borderSpacing '+'borderTopColor borderTopStyle borderTopWidth bottom clip color '+'fontSize fontWeight height left letterSpacing lineHeight '+'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement('div');String.prototype.parseStyle=function(){var b,styleRules=$H();if(Prototype.Browser.WebKit)b=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';b=String.__parseStyleElement.childNodes[0].style}Element.CSS_PROPERTIES.each(function(a){if(b[a])styleRules.set(a,b[a])});if(Prototype.Browser.IE&&this.include('opacity'))styleRules.set('opacity',this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules};if(document.defaultView&&document.defaultView.getComputedStyle){Element.getStyles=function(c){var d=document.defaultView.getComputedStyle($(c),null);return Element.CSS_PROPERTIES.inject({},function(a,b){a[b]=d[b];return a})}}else{Element.getStyles=function(c){c=$(c);var d=c.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(a,b){a[b]=d[b];return a});if(!styles.opacity)styles.opacity=c.getOpacity();return styles}}Effect.Methods={morph:function(a,b){a=$(a);new Effect.Morph(a,Object.extend({style:b},arguments[2]||{}));return a},visualEffect:function(a,b,c){a=$(a);var s=b.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](a,c);return a},highlight:function(a,b){a=$(a);new Effect.Highlight(a,b);return a}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+'pulsate shake puff squish switchOff dropOut').each(function(c){Effect.Methods[c]=function(a,b){a=$(a);Effect[c.charAt(0).toUpperCase()+c.substring(1)](a,b);return a}});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f]});Element.addMethods(Effect.Methods);
//dragdrop.js
if(Object.isUndefined(Effect))throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(a){this.drops=this.drops.reject(function(d){return d.element==$(a)})},add:function(a){a=$(a);var b=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(b.containment){b._containers=[];var d=b.containment;if(Object.isArray(d)){d.each(function(c){b._containers.push($(c))})}else{b._containers.push($(d))}}if(b.accept)b.accept=[b.accept].flatten();Element.makePositioned(a);b.element=a;this.drops.push(b)},findDeepestChild:function(a){deepest=a[0];for(i=1;i<a.length;++i)if(Element.isParent(a[i].element,deepest.element))deepest=a[i];return deepest},isContained:function(a,b){var d;if(b.tree){d=a.treeNode}else{d=a.parentNode}return b._containers.detect(function(c){return d==c})},isAffected:function(a,b,c){return((c.element!=b)&&((!c._containers)||this.isContained(b,c))&&((!c.accept)||(Element.classNames(b).detect(function(v){return c.accept.include(v)})))&&Position.within(c.element,a[0],a[1]))},deactivate:function(a){if(a.hoverclass)Element.removeClassName(a.element,a.hoverclass);this.last_active=null},activate:function(a){if(a.hoverclass)Element.addClassName(a.element,a.hoverclass);this.last_active=a},show:function(b,c){if(!this.drops.length)return;var d,affected=[];this.drops.each(function(a){if(Droppables.isAffected(b,c,a))affected.push(a)});if(affected.length>0)d=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=d)this.deactivate(this.last_active);if(d){Position.within(d.element,b[0],b[1]);if(d.onHover)d.onHover(c,d.element,Position.overlap(d.overlap,d.element));if(d!=this.last_active)Droppables.activate(d)}},fire:function(a,b){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(a),Event.pointerY(a)],b,this.last_active))if(this.last_active.onDrop){this.last_active.onDrop(b,this.last_active.element,a);return true}},reset:function(){if(this.last_active)this.deactivate(this.last_active)}};var Draggables={drags:[],observers:[],register:function(a){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress)}this.drags.push(a)},unregister:function(a){this.drags=this.drags.reject(function(d){return d==a});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress)}},activate:function(a){if(a.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=a}.bind(this),a.options.delay)}else{window.focus();this.activeDraggable=a}},deactivate:function(){this.activeDraggable=null},updateDrag:function(a){if(!this.activeDraggable)return;var b=[Event.pointerX(a),Event.pointerY(a)];if(this._lastPointer&&(this._lastPointer.inspect()==b.inspect()))return;this._lastPointer=b;this.activeDraggable.updateDrag(a,b)},endDrag:function(a){if(this._timeout){clearTimeout(this._timeout);this._timeout=null}if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(a);this.activeDraggable=null},keyPress:function(a){if(this.activeDraggable)this.activeDraggable.keyPress(a)},addObserver:function(a){this.observers.push(a);this._cacheObserverCallbacks()},removeObserver:function(a){this.observers=this.observers.reject(function(o){return o.element==a});this._cacheObserverCallbacks()},notify:function(a,b,c){if(this[a+'Count']>0)this.observers.each(function(o){if(o[a])o[a](a,b,c)});if(b.options[a])b.options[a](b,c)},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(a){Draggables[a+'Count']=Draggables.observers.select(function(o){return o[a]}).length})}};var Draggable=Class.create({initialize:function(e){var f={handle:false,reverteffect:function(a,b,c){var d=Math.sqrt(Math.abs(b^2)+Math.abs(c^2))*0.02;new Effect.Move(a,{x:-c,y:-b,duration:d,queue:{scope:'_draggable',position:'end'}})},endeffect:function(a){var b=Object.isNumber(a._opacity)?a._opacity:1.0;new Effect.Opacity(a,{duration:0.2,from:0.7,to:b,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[a]=false}})},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))Object.extend(f,{starteffect:function(a){a._opacity=Element.getOpacity(a);Draggable._dragging[a]=true;new Effect.Opacity(a,{duration:0.2,from:a._opacity,to:0.7})}});var g=Object.extend(f,arguments[1]||{});this.element=$(e);if(g.handle&&Object.isString(g.handle))this.handle=this.element.down('.'+g.handle,0);if(!this.handle)this.handle=$(g.handle);if(!this.handle)this.handle=this.element;if(g.scroll&&!g.scroll.scrollTo&&!g.scroll.outerHTML){g.scroll=$(g.scroll);this._isScrollChild=Element.childOf(this.element,g.scroll)}Element.makePositioned(this.element);this.options=g;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this)},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this)},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'left')||'0'),parseInt(Element.getStyle(this.element,'top')||'0')])},initDrag:function(a){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(a)){var b=Event.element(a);if((tag_name=b.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var c=[Event.pointerX(a),Event.pointerY(a)];var d=Position.cumulativeOffset(this.element);this.offset=[0,1].map(function(i){return(c[i]-d[i])});Draggables.activate(this);Event.stop(a)}},startDrag:function(a){this.dragging=true;if(!this.delta)this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex}if(this.options.ghosting){this._clone=this.element.cloneNode(true);this._originallyAbsolute=(this.element.getStyle('position')=='absolute');if(!this._originallyAbsolute)Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element)}if(this.options.scroll){if(this.options.scroll==window){var b=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=b.left;this.originalScrollTop=b.top}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop}}Draggables.notify('onStart',this,a);if(this.options.starteffect)this.options.starteffect(this.element)},updateDrag:function(a,b){if(!this.dragging)this.startDrag(a);if(!this.options.quiet){Position.prepare();Droppables.show(b,this.element)}Draggables.notify('onDrag',this,a);this.draw(b);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height]}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight)}var c=[0,0];if(b[0]<(p[0]+this.options.scrollSensitivity))c[0]=b[0]-(p[0]+this.options.scrollSensitivity);if(b[1]<(p[1]+this.options.scrollSensitivity))c[1]=b[1]-(p[1]+this.options.scrollSensitivity);if(b[0]>(p[2]-this.options.scrollSensitivity))c[0]=b[0]-(p[2]-this.options.scrollSensitivity);if(b[1]>(p[3]-this.options.scrollSensitivity))c[1]=b[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(c)}if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(a)},finishDrag:function(a,b){this.dragging=false;if(this.options.quiet){Position.prepare();var c=[Event.pointerX(a),Event.pointerY(a)];Droppables.show(c,this.element)}if(this.options.ghosting){if(!this._originallyAbsolute)Position.relativize(this.element);delete this._originallyAbsolute;Element.remove(this._clone);this._clone=null}var e=false;if(b){e=Droppables.fire(a,this.element);if(!e)e=false}if(e&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify('onEnd',this,a);var f=this.options.revert;if(f&&Object.isFunction(f))f=f(this.element);var d=this.currentDelta();if(f&&this.options.reverteffect){if(e==0||f!='failure')this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0])}else{this.delta=d}if(this.options.zindex)this.element.style.zIndex=this.originalZ;if(this.options.endeffect)this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset()},keyPress:function(a){if(a.keyCode!=Event.KEY_ESC)return;this.finishDrag(a,false);Event.stop(a)},endDrag:function(a){if(!this.dragging)return;this.stopScrolling();this.finishDrag(a,true);Event.stop(a)},draw:function(a){var b=Position.cumulativeOffset(this.element);if(this.options.ghosting){var r=Position.realOffset(this.element);b[0]+=r[0]-Position.deltaX;b[1]+=r[1]-Position.deltaY}var d=this.currentDelta();b[0]-=d[0];b[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){b[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;b[1]-=this.options.scroll.scrollTop-this.originalScrollTop}var p=[0,1].map(function(i){return(a[i]-b[i]-this.offset[i])}.bind(this));if(this.options.snap){if(Object.isFunction(this.options.snap)){p=this.options.snap(p[0],p[1],this)}else{if(Object.isArray(this.options.snap)){p=p.map(function(v,i){return(v/this.options.snap[i]).round()*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return(v/this.options.snap).round()*this.options.snap}.bind(this))}}}var c=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))c.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))c.top=p[1]+"px";if(c.visibility=="hidden")c.visibility=""},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null}},startScrolling:function(a){if(!(a[0]||a[1]))return;this.scrollSpeed=[a[0]*this.options.scrollSpeed,a[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10)},scroll:function(){var a=new Date();var b=a-this.lastScrolled;this.lastScrolled=a;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=b/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1])}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*b/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*b/1000}Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify('onDrag',this);if(this._isScrollChild){Draggables._lastScrollPointer=Draggables._lastScrollPointer||$A(Draggables._lastPointer);Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*b/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*b/1000;if(Draggables._lastScrollPointer[0]<0)Draggables._lastScrollPointer[0]=0;if(Draggables._lastScrollPointer[1]<0)Draggables._lastScrollPointer[1]=0;this.draw(Draggables._lastScrollPointer)}if(this.options.change)this.options.change(this)},_getWindowScroll:function(w){var T,L,W,H;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft}if(w.innerWidth){W=w.innerWidth;H=w.innerHeight}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight}else{W=body.offsetWidth;H=body.offsetHeight}}return{top:T,left:L,width:W,height:H}}});Draggable._dragging={};var SortableObserver=Class.create({initialize:function(a,b){this.element=$(a);this.observer=b;this.lastValue=Sortable.serialize(this.element)},onStart:function(){this.lastValue=Sortable.serialize(this.element)},onEnd:function(){Sortable.unmark();if(this.lastValue!=Sortable.serialize(this.element))this.observer(this.element)}});var Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(a){while(a.tagName.toUpperCase()!="BODY"){if(a.id&&Sortable.sortables[a.id])return a;a=a.parentNode}},options:function(a){a=Sortable._findRootElement($(a));if(!a)return;return Sortable.sortables[a.id]},destroy:function(a){var s=Sortable.options(a);if(s){Draggables.removeObserver(s.element);s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke('destroy');delete Sortable.sortables[s.element.id]}},create:function(b){b=$(b);var c=Object.extend({element:b,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:b,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(b);var d={revert:true,quiet:c.quiet,scroll:c.scroll,scrollSpeed:c.scrollSpeed,scrollSensitivity:c.scrollSensitivity,delay:c.delay,ghosting:c.ghosting,constraint:c.constraint,handle:c.handle};if(c.starteffect)d.starteffect=c.starteffect;if(c.reverteffect)d.reverteffect=c.reverteffect;else if(c.ghosting)d.reverteffect=function(a){a.style.top=0;a.style.left=0};if(c.endeffect)d.endeffect=c.endeffect;if(c.zindex)d.zindex=c.zindex;var f={overlap:c.overlap,containment:c.containment,tree:c.tree,hoverclass:c.hoverclass,onHover:Sortable.onHover};var g={onHover:Sortable.onEmptyHover,overlap:c.overlap,containment:c.containment,hoverclass:c.hoverclass};Element.cleanWhitespace(b);c.draggables=[];c.droppables=[];if(c.dropOnEmpty||c.tree){Droppables.add(b,g);c.droppables.push(b)}(c.elements||this.findElements(b,c)||[]).each(function(e,i){var a=c.handles?$(c.handles[i]):(c.handle?$(e).select('.'+c.handle)[0]:e);c.draggables.push(new Draggable(e,Object.extend(d,{handle:a})));Droppables.add(e,f);if(c.tree)e.treeNode=b;c.droppables.push(e)});if(c.tree){(Sortable.findTreeElements(b,c)||[]).each(function(e){Droppables.add(e,g);e.treeNode=b;c.droppables.push(e)})}this.sortables[b.id]=c;Draggables.addObserver(new SortableObserver(b,c.onUpdate))},findElements:function(a,b){return Element.findChildren(a,b.only,b.tree?true:false,b.tag)},findTreeElements:function(a,b){return Element.findChildren(a,b.only,b.tree?true:false,b.treeTag)},onHover:function(a,b,c){if(Element.isParent(b,a))return;if(c>.33&&c<.66&&Sortable.options(b).tree){return}else if(c>0.5){Sortable.mark(b,'before');if(b.previousSibling!=a){var d=a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,b);if(b.parentNode!=d)Sortable.options(d).onChange(a);Sortable.options(b.parentNode).onChange(a)}}else{Sortable.mark(b,'after');var e=b.nextSibling||null;if(e!=a){var d=a.parentNode;a.style.visibility="hidden";b.parentNode.insertBefore(a,e);if(b.parentNode!=d)Sortable.options(d).onChange(a);Sortable.options(b.parentNode).onChange(a)}}},onEmptyHover:function(a,b,c){var d=a.parentNode;var e=Sortable.options(b);if(!Element.isParent(b,a)){var f;var g=Sortable.findElements(b,{tag:e.tag,only:e.only});var h=null;if(g){var i=Element.offsetSize(b,e.overlap)*(1.0-c);for(f=0;f<g.length;f+=1){if(i-Element.offsetSize(g[f],e.overlap)>=0){i-=Element.offsetSize(g[f],e.overlap)}else if(i-(Element.offsetSize(g[f],e.overlap)/2)>=0){h=f+1<g.length?g[f+1]:null;break}else{h=g[f];break}}}b.insertBefore(a,h);Sortable.options(d).onChange(a);e.onChange(a)}},unmark:function(){if(Sortable._marker)Sortable._marker.hide()},mark:function(a,b){var c=Sortable.options(a.parentNode);if(c&&!c.ghosting)return;if(!Sortable._marker){Sortable._marker=($('dropmarker')||Element.extend(document.createElement('DIV'))).hide().addClassName('dropmarker').setStyle({position:'absolute'});document.getElementsByTagName("body").item(0).appendChild(Sortable._marker)}var d=Position.cumulativeOffset(a);Sortable._marker.setStyle({left:d[0]+'px',top:d[1]+'px'});if(b=='after')if(c.overlap=='horizontal')Sortable._marker.setStyle({left:(d[0]+a.clientWidth)+'px'});else Sortable._marker.setStyle({top:(d[1]+a.clientHeight)+'px'});Sortable._marker.show()},_tree:function(a,b,c){var d=Sortable.findElements(a,b)||[];for(var i=0;i<d.length;++i){var e=d[i].id.match(b.format);if(!e)continue;var f={id:encodeURIComponent(e?e[1]:null),element:a,parent:c,children:[],position:c.children.length,container:$(d[i]).down(b.treeTag)};if(f.container)this._tree(f.container,b,f);c.children.push(f)}return c},tree:function(a){a=$(a);var b=this.options(a);var c=Object.extend({tag:b.tag,treeTag:b.treeTag,only:b.only,name:a.id,format:b.format},arguments[1]||{});var d={id:null,parent:null,children:[],container:a,position:0};return Sortable._tree(a,c,d)},_constructIndex:function(a){var b='';do{if(a.id)b='['+a.position+']'+b}while((a=a.parent)!=null);return b},sequence:function(b){b=$(b);var c=Object.extend(this.options(b),arguments[1]||{});return $(this.findElements(b,c)||[]).map(function(a){return a.id.match(c.format)?a.id.match(c.format)[1]:''})},setSequence:function(b,c){b=$(b);var d=Object.extend(this.options(b),arguments[2]||{});var e={};this.findElements(b,d).each(function(n){if(n.id.match(d.format))e[n.id.match(d.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n)});c.each(function(a){var n=e[a];if(n){n[1].appendChild(n[0]);delete e[a]}})},serialize:function(b){b=$(b);var c=Object.extend(Sortable.options(b),arguments[1]||{});var d=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:b.id);if(c.tree){return Sortable.tree(b,arguments[1]).children.map(function(a){return[d+Sortable._constructIndex(a)+"[id]="+encodeURIComponent(a.id)].concat(a.children.map(arguments.callee))}).flatten().join('&')}else{return Sortable.sequence(b,arguments[1]).map(function(a){return d+"[]="+encodeURIComponent(a)}).join('&')}}};Element.isParent=function(a,b){if(!a.parentNode||a==b)return false;if(a.parentNode==b)return true;return Element.isParent(a.parentNode,b)};Element.findChildren=function(b,c,d,f){if(!b.hasChildNodes())return null;f=f.toUpperCase();if(c)c=[c].flatten();var g=[];$A(b.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==f&&(!c||(Element.classNames(e).detect(function(v){return c.include(v)}))))g.push(e);if(d){var a=Element.findChildren(e,c,d,f);if(a)g.push(a)}});return(g.length>0?g.flatten():[])};Element.offsetSize=function(a,b){return a['offset'+((b=='vertical'||b=='height')?'Height':'Width')]};
//controls.js
if(typeof Effect=='undefined')throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={};Autocompleter.Base=Class.create({baseInitialize:function(c,d,e){c=$(c);this.element=c;this.update=$(d);this.hasFocus=false;this.changed=false;this.active=false;this.index=0;this.entryCount=0;this.oldElementValue=this.element.value;if(this.setOptions)this.setOptions(e);else this.options=e||{};this.options.paramName=this.options.paramName||this.element.name;this.options.tokens=this.options.tokens||[];this.options.frequency=this.options.frequency||0.4;this.options.minChars=this.options.minChars||1;this.options.onShow=this.options.onShow||function(a,b){if(!b.style.position||b.style.position=='absolute'){b.style.position='absolute';Position.clone(a,b,{setHeight:false,offsetTop:a.offsetHeight})}Effect.Appear(b,{duration:0.15})};this.options.onHide=this.options.onHide||function(a,b){new Effect.Fade(b,{duration:0.15})};if(typeof(this.options.tokens)=='string')this.options.tokens=new Array(this.options.tokens);if(!this.options.tokens.include('\n'))this.options.tokens.push('\n');this.observer=null;this.element.setAttribute('autocomplete','off');Element.hide(this.update);Event.observe(this.element,'blur',this.onBlur.bindAsEventListener(this));Event.observe(this.element,'keydown',this.onKeyPress.bindAsEventListener(this))},show:function(){if(Element.getStyle(this.update,'display')=='none')this.options.onShow(this.element,this.update);if(!this.iefix&&(Prototype.Browser.IE)&&(Element.getStyle(this.update,'position')=='absolute')){new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+'_iefix')}if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50)},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:(!this.update.style.height)});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix)},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,'display')!='none')this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix)},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator)},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator)},onKeyPress:function(a){if(this.active)switch(a.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(a);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(a);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();Event.stop(a);return;case Event.KEY_DOWN:this.markNext();this.render();Event.stop(a);return}else if(a.keyCode==Event.KEY_TAB||a.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&a.keyCode==0))return;this.changed=true;this.hasFocus=true;if(this.observer)clearTimeout(this.observer);this.observer=setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1000)},activate:function(){this.changed=false;this.hasFocus=true;this.getUpdatedChoices()},onHover:function(a){var b=Event.findElement(a,'LI');if(this.index!=b.autocompleteIndex){this.index=b.autocompleteIndex;this.render()}Event.stop(a)},onClick:function(a){var b=Event.findElement(a,'LI');this.index=b.autocompleteIndex;this.selectEntry();this.hide()},onBlur:function(a){setTimeout(this.hide.bind(this),250);this.hasFocus=false;this.active=false},render:function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)this.index==i?Element.addClassName(this.getEntry(i),"selected"):Element.removeClassName(this.getEntry(i),"selected");if(this.hasFocus){this.show();this.active=true}}else{this.active=false;this.hide()}},markPrevious:function(){if(this.index>0)this.index--;else this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(true)},markNext:function(){if(this.index<this.entryCount-1)this.index++;else this.index=0;this.getEntry(this.index).scrollIntoView(false)},getEntry:function(a){return this.update.firstChild.childNodes[a]},getCurrentEntry:function(){return this.getEntry(this.index)},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry())},updateElement:function(a){if(this.options.updateElement){this.options.updateElement(a);return}var b='';if(this.options.select){var c=$(a).select('.'+this.options.select)||[];if(c.length>0)b=Element.collectTextNodes(c[0],this.options.select)}else b=Element.collectTextNodesIgnoreClass(a,'informal');var d=this.getTokenBounds();if(d[0]!=-1){var e=this.element.value.substr(0,d[0]);var f=this.element.value.substr(d[0]).match(/^\s+/);if(f)e+=f[0];this.element.value=e+b+this.element.value.substr(d[1])}else{this.element.value=b}this.oldElementValue=this.element.value;this.element.focus();if(this.options.afterUpdateElement)this.options.afterUpdateElement(this.element,a)},updateChoices:function(a){if(!this.changed&&this.hasFocus){this.update.innerHTML=a;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes){this.entryCount=this.update.down().childNodes.length;for(var i=0;i<this.entryCount;i++){var b=this.getEntry(i);b.autocompleteIndex=i;this.addObservers(b)}}else{this.entryCount=0}this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide()}else{this.render()}}},addObservers:function(a){Event.observe(a,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(a,"click",this.onClick.bindAsEventListener(this))},onObserverEvent:function(){this.changed=false;this.tokenBounds=null;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices()}else{this.active=false;this.hide()}this.oldElementValue=this.element.value},getToken:function(){var a=this.getTokenBounds();return this.element.value.substring(a[0],a[1]).strip()},getTokenBounds:function(){if(null!=this.tokenBounds)return this.tokenBounds;var a=this.element.value;if(a.strip().empty())return[-1,0];var b=arguments.callee.getFirstDifferencePos(a,this.oldElementValue);var c=(b==this.oldElementValue.length?1:0);var d=-1,nextTokenPos=a.length;var e;for(var f=0,l=this.options.tokens.length;f<l;++f){e=a.lastIndexOf(this.options.tokens[f],b+c-1);if(e>d)d=e;e=a.indexOf(this.options.tokens[f],b+c);if(-1!=e&&e<nextTokenPos)nextTokenPos=e}return(this.tokenBounds=[d+1,nextTokenPos])}});Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos=function(a,b){var c=Math.min(a.length,b.length);for(var d=0;d<c;++d)if(a[d]!=b[d])return d;return c};Ajax.Autocompleter=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=c},getUpdatedChoices:function(){this.startIndicator();var a=encodeURIComponent(this.options.paramName)+'='+encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,a):a;if(this.options.defaultParams)this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options)},onComplete:function(a){this.updateChoices(a.responseText)}});Autocompleter.Local=Class.create(Autocompleter.Base,{initialize:function(a,b,c,d){this.baseInitialize(a,b,d);this.options.array=c},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this))},setOptions:function(h){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(a){var b=[];var c=[];var d=a.getToken();var e=0;for(var i=0;i<a.options.array.length&&b.length<a.options.choices;i++){var f=a.options.array[i];var g=a.options.ignoreCase?f.toLowerCase().indexOf(d.toLowerCase()):f.indexOf(d);while(g!=-1){if(g==0&&f.length!=d.length){b.push("<li><strong>"+f.substr(0,d.length)+"</strong>"+f.substr(d.length)+"</li>");break}else if(d.length>=a.options.partialChars&&a.options.partialSearch&&g!=-1){if(a.options.fullSearch||/\s/.test(f.substr(g-1,1))){c.push("<li>"+f.substr(0,g)+"<strong>"+f.substr(g,d.length)+"</strong>"+f.substr(g+d.length)+"</li>");break}}g=a.options.ignoreCase?f.toLowerCase().indexOf(d.toLowerCase(),g+1):f.indexOf(d,g+1)}}if(c.length)b=b.concat(c.slice(0,a.options.choices-b.length));return"<ul>"+b.join('')+"</ul>"}},h||{})}});Field.scrollFreeActivate=function(a){setTimeout(function(){Field.activate(a)},1)};Ajax.InPlaceEditor=Class.create({initialize:function(a,b,c){this.url=b;this.element=a=$(a);this.prepareOptions();this._controls={};arguments.callee.dealWithDeprecatedOptions(c);Object.extend(this.options,c||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+'-inplaceeditor';if($(this.options.formId))this.options.formId=''}if(this.options.externalControl)this.options.externalControl=$(this.options.externalControl);if(!this.options.externalControl)this.options.externalControlOnly=false;this._originalBackground=this.element.getStyle('background-color')||'transparent';this.element.title=this.options.clickToEditText;this._boundCancelHandler=this.handleFormCancellation.bind(this);this._boundComplete=(this.options.onComplete||Prototype.emptyFunction).bind(this);this._boundFailureHandler=this.handleAJAXFailure.bind(this);this._boundSubmitHandler=this.handleFormSubmission.bind(this);this._boundWrapperHandler=this.wrapUp.bind(this);this.registerListeners()},checkForEscapeOrReturn:function(e){if(!this._editing||e.ctrlKey||e.altKey||e.shiftKey)return;if(Event.KEY_ESC==e.keyCode)this.handleFormCancellation(e);else if(Event.KEY_RETURN==e.keyCode)this.handleFormSubmission(e)},createControl:function(a,b,c){var d=this.options[a+'Control'];var e=this.options[a+'Text'];if('button'==d){var f=document.createElement('input');f.type='submit';f.value=e;f.className='editor_'+a+'_button';if('cancel'==a)f.onclick=this._boundCancelHandler;this._form.appendChild(f);this._controls[a]=f}else if('link'==d){var g=document.createElement('a');g.href='#';g.appendChild(document.createTextNode(e));g.onclick='cancel'==a?this._boundCancelHandler:this._boundSubmitHandler;g.className='editor_'+a+'_link';if(c)g.className+=' '+c;this._form.appendChild(g);this._controls[a]=g}},createEditField:function(){var a=(this.options.loadTextURL?this.options.loadingText:this.getText());var b;if(1>=this.options.rows&&!/\r|\n/.test(this.getText())){b=document.createElement('input');b.type='text';var c=this.options.size||this.options.cols||0;if(0<c)b.size=c}else{b=document.createElement('textarea');b.rows=(1>=this.options.rows?this.options.autoRows:this.options.rows);b.cols=this.options.cols||40}b.name=this.options.paramName;b.value=a;b.className='editor_field';if(this.options.submitOnBlur)b.onblur=this._boundSubmitHandler;this._controls.editor=b;if(this.options.loadTextURL)this.loadExternalText();this._form.appendChild(this._controls.editor)},createForm:function(){var d=this;function addText(a,b){var c=d.options['text'+a+'Controls'];if(!c||b===false)return;d._form.appendChild(document.createTextNode(c))};this._form=$(document.createElement('form'));this._form.id=this.options.formId;this._form.addClassName(this.options.formClassName);this._form.onsubmit=this._boundSubmitHandler;this.createEditField();if('textarea'==this._controls.editor.tagName.toLowerCase())this._form.appendChild(document.createElement('br'));if(this.options.onFormCustomization)this.options.onFormCustomization(this,this._form);addText('Before',this.options.okControl||this.options.cancelControl);this.createControl('ok',this._boundSubmitHandler);addText('Between',this.options.okControl&&this.options.cancelControl);this.createControl('cancel',this._boundCancelHandler,'editor_cancel');addText('After',this.options.okControl||this.options.cancelControl)},destroy:function(){if(this._oldInnerHTML)this.element.innerHTML=this._oldInnerHTML;this.leaveEditMode();this.unregisterListeners()},enterEditMode:function(e){if(this._saving||this._editing)return;this._editing=true;this.triggerCallback('onEnterEditMode');if(this.options.externalControl)this.options.externalControl.hide();this.element.hide();this.createForm();this.element.parentNode.insertBefore(this._form,this.element);if(!this.options.loadTextURL)this.postProcessEditField();if(e)Event.stop(e)},enterHover:function(e){if(this.options.hoverClassName)this.element.addClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onEnterHover')},getText:function(){return this.element.innerHTML},handleAJAXFailure:function(a){this.triggerCallback('onFailure',a);if(this._oldInnerHTML){this.element.innerHTML=this._oldInnerHTML;this._oldInnerHTML=null}},handleFormCancellation:function(e){this.wrapUp();if(e)Event.stop(e)},handleFormSubmission:function(e){var a=this._form;var b=$F(this._controls.editor);this.prepareSubmission();var c=this.options.callback(a,b)||'';if(Object.isString(c))c=c.toQueryParams();c.editorId=this.element.id;if(this.options.htmlResponse){var d=Object.extend({evalScripts:true},this.options.ajaxOptions);Object.extend(d,{parameters:c,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Updater({success:this.element},this.url,d)}else{var d=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(d,{parameters:c,onComplete:this._boundWrapperHandler,onFailure:this._boundFailureHandler});new Ajax.Request(this.url,d)}if(e)Event.stop(e)},leaveEditMode:function(){this.element.removeClassName(this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this._originalBackground;this.element.show();if(this.options.externalControl)this.options.externalControl.show();this._saving=false;this._editing=false;this._oldInnerHTML=null;this.triggerCallback('onLeaveEditMode')},leaveHover:function(e){if(this.options.hoverClassName)this.element.removeClassName(this.options.hoverClassName);if(this._saving)return;this.triggerCallback('onLeaveHover')},loadExternalText:function(){this._form.addClassName(this.options.loadingClassName);this._controls.editor.disabled=true;var c=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(c,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._form.removeClassName(this.options.loadingClassName);var b=a.responseText;if(this.options.stripLoadedTextTags)b=b.stripTags();this._controls.editor.value=b;this._controls.editor.disabled=false;this.postProcessEditField()}.bind(this),onFailure:this._boundFailureHandler});new Ajax.Request(this.options.loadTextURL,c)},postProcessEditField:function(){var a=this.options.fieldPostCreation;if(a)$(this._controls.editor)['focus'==a?'focus':'activate']()},prepareOptions:function(){this.options=Object.clone(Ajax.InPlaceEditor.DefaultOptions);Object.extend(this.options,Ajax.InPlaceEditor.DefaultCallbacks);[this._extraDefaultOptions].flatten().compact().each(function(a){Object.extend(this.options,a)}.bind(this))},prepareSubmission:function(){this._saving=true;this.removeForm();this.leaveHover();this.showSaving()},registerListeners:function(){this._listeners={};var b;$H(Ajax.InPlaceEditor.Listeners).each(function(a){b=this[a.value].bind(this);this._listeners[a.key]=b;if(!this.options.externalControlOnly)this.element.observe(a.key,b);if(this.options.externalControl)this.options.externalControl.observe(a.key,b)}.bind(this))},removeForm:function(){if(!this._form)return;this._form.remove();this._form=null;this._controls={}},showSaving:function(){this._oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;this.element.addClassName(this.options.savingClassName);this.element.style.backgroundColor=this._originalBackground;this.element.show()},triggerCallback:function(a,b){if('function'==typeof this.options[a]){this.options[a](this,b)}},unregisterListeners:function(){$H(this._listeners).each(function(a){if(!this.options.externalControlOnly)this.element.stopObserving(a.key,a.value);if(this.options.externalControl)this.options.externalControl.stopObserving(a.key,a.value)}.bind(this))},wrapUp:function(a){this.leaveEditMode();this._boundComplete(a,this.element)}});Object.extend(Ajax.InPlaceEditor.prototype,{dispose:Ajax.InPlaceEditor.prototype.destroy});Ajax.InPlaceCollectionEditor=Class.create(Ajax.InPlaceEditor,{initialize:function($super,b,c,d){this._extraDefaultOptions=Ajax.InPlaceCollectionEditor.DefaultOptions;$super(b,c,d)},createEditField:function(){var a=document.createElement('select');a.name=this.options.paramName;a.size=1;this._controls.editor=a;this._collection=this.options.collection||[];if(this.options.loadCollectionURL)this.loadCollection();else this.checkForExternalText();this._form.appendChild(this._controls.editor)},loadCollection:function(){this._form.addClassName(this.options.loadingClassName);this.showLoadingText(this.options.loadingCollectionText);var c=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(c,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){var b=a.responseText.strip();if(!/^\[.*\]$/.test(b))throw('Server returned an invalid collection representation.');this._collection=eval(b);this.checkForExternalText()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadCollectionURL,c)},showLoadingText:function(a){this._controls.editor.disabled=true;var b=this._controls.editor.firstChild;if(!b){b=document.createElement('option');b.value='';this._controls.editor.appendChild(b);b.selected=true}b.update((a||'').stripScripts().stripTags())},checkForExternalText:function(){this._text=this.getText();if(this.options.loadTextURL)this.loadExternalText();else this.buildOptionList()},loadExternalText:function(){this.showLoadingText(this.options.loadingText);var b=Object.extend({method:'get'},this.options.ajaxOptions);Object.extend(b,{parameters:'editorId='+encodeURIComponent(this.element.id),onComplete:Prototype.emptyFunction,onSuccess:function(a){this._text=a.responseText.strip();this.buildOptionList()}.bind(this),onFailure:this.onFailure});new Ajax.Request(this.options.loadTextURL,b)},buildOptionList:function(){this._form.removeClassName(this.options.loadingClassName);this._collection=this._collection.map(function(a){return 2===a.length?a:[a,a].flatten()});var c=('value'in this.options)?this.options.value:this._text;var d=this._collection.any(function(a){return a[0]==c}.bind(this));this._controls.editor.update('');var e;this._collection.each(function(a,b){e=document.createElement('option');e.value=a[0];e.selected=d?a[0]==c:0==b;e.appendChild(document.createTextNode(a[1]));this._controls.editor.appendChild(e)}.bind(this));this._controls.editor.disabled=false;Field.scrollFreeActivate(this._controls.editor)}});Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions=function(c){if(!c)return;function fallback(a,b){if(a in c||b===undefined)return;c[a]=b};fallback('cancelControl',(c.cancelLink?'link':(c.cancelButton?'button':c.cancelLink==c.cancelButton==false?false:undefined)));fallback('okControl',(c.okLink?'link':(c.okButton?'button':c.okLink==c.okButton==false?false:undefined)));fallback('highlightColor',c.highlightcolor);fallback('highlightEndColor',c.highlightendcolor)};Object.extend(Ajax.InPlaceEditor,{DefaultOptions:{ajaxOptions:{},autoRows:3,cancelControl:'link',cancelText:'cancel',clickToEditText:'Click to edit',externalControl:null,externalControlOnly:false,fieldPostCreation:'activate',formClassName:'inplaceeditor-form',formId:null,highlightColor:'#ffff99',highlightEndColor:'#ffffff',hoverClassName:'',htmlResponse:true,loadingClassName:'inplaceeditor-loading',loadingText:'Loading...',okControl:'button',okText:'ok',paramName:'value',rows:1,savingClassName:'inplaceeditor-saving',savingText:'Saving...',size:0,stripLoadedTextTags:false,submitOnBlur:false,textAfterControls:'',textBeforeControls:'',textBetweenControls:''},DefaultCallbacks:{callback:function(a){return Form.serialize(a)},onComplete:function(a,b){new Effect.Highlight(b,{startcolor:this.options.highlightColor,keepBackgroundImage:true})},onEnterEditMode:null,onEnterHover:function(a){a.element.style.backgroundColor=a.options.highlightColor;if(a._effect)a._effect.cancel()},onFailure:function(a,b){alert('Error communication with the server: '+a.responseText.stripTags())},onFormCustomization:null,onLeaveEditMode:null,onLeaveHover:function(a){a._effect=new Effect.Highlight(a.element,{startcolor:a.options.highlightColor,endcolor:a.options.highlightEndColor,restorecolor:a._originalBackground,keepBackgroundImage:true})}},Listeners:{click:'enterEditMode',keydown:'checkForEscapeOrReturn',mouseover:'enterHover',mouseout:'leaveHover'}});Ajax.InPlaceCollectionEditor.DefaultOptions={loadingCollectionText:'Loading options...'};Form.Element.DelayedObserver=Class.create({initialize:function(a,b,c){this.delay=b||0.5;this.element=$(a);this.callback=c;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this))},delayedListener:function(a){if(this.lastValue==$F(this.element))return;if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(this.onTimerEvent.bind(this),this.delay*1000);this.lastValue=$F(this.element)},onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element))}});
//slider.js
if(!Control)var Control={};Control.Slider=Class.create({initialize:function(a,b,c){var d=this;if(Object.isArray(a)){this.handles=a.collect(function(e){return $(e)})}else{this.handles=[$(a)]}this.track=$(b);this.options=c||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max()}this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=d.handles.length-1-i;d.setValue(parseFloat((Object.isArray(d.options.sliderValue)?d.options.sliderValue[i]:d.options.sliderValue)||d.range.start),i);h.makePositioned().observe("mousedown",d.eventMouseDown)});this.track.observe("mousedown",this.eventMouseDown);document.observe("mouseup",this.eventMouseUp);document.observe("mousemove",this.eventMouseMove);this.initialized=true},dispose:function(){var a=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",a.eventMouseDown)})},setDisabled:function(){this.disabled=true},setEnabled:function(){this.disabled=false},getNearestValue:function(b){if(this.allowedValues){if(b>=this.allowedValues.max())return(this.allowedValues.max());if(b<=this.allowedValues.min())return(this.allowedValues.min());var c=Math.abs(this.allowedValues[0]-b);var d=this.allowedValues[0];this.allowedValues.each(function(v){var a=Math.abs(v-b);if(a<=c){d=v;c=a}});return d}if(b>this.range.end)return this.range.end;if(b<this.range.start)return this.range.start;return b},setValue:function(a,b){if(!this.active){this.activeHandleIdx=b||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles()}b=b||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((b>0)&&(a<this.values[b-1]))a=this.values[b-1];if((b<(this.handles.length-1))&&(a>this.values[b+1]))a=this.values[b+1]}a=this.getNearestValue(a);this.values[b]=a;this.value=this.values[0];this.handles[b].style[this.isVertical()?'top':'left']=this.translateToPx(a);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished()},setValueBy:function(a,b){this.setValue(this.values[b||this.activeHandleIdx||0]+a,b||this.activeHandleIdx||0)},translateToPx:function(a){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(a-this.range.start))+"px"},translateToValue:function(a){return((a/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start)},getRange:function(a){var v=this.values.sortBy(Prototype.K);a=a||0;return $R(v[a],v[a+1])},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX)},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignX)},isVertical:function(){return(this.axis=='vertical')},drawSpans:function(){var a=this;if(this.spans)$R(0,this.spans.length-1).each(function(r){a.setSpan(a.spans[r],a.getRange(r))});if(this.options.startSpan)this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum))},setSpan:function(a,b){if(this.isVertical()){a.style.top=this.translateToPx(b.start);a.style.height=this.translateToPx(b.end-b.start+this.range.start)}else{a.style.left=this.translateToPx(b.start);a.style.width=this.translateToPx(b.end-b.start+this.range.start)}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected')},startDrag:function(a){if(Event.isLeftClick(a)){if(!this.disabled){this.active=true;var b=Event.element(a);var c=[Event.pointerX(a),Event.pointerY(a)];var d=b;if(d==this.track){var e=Position.cumulativeOffset(this.track);this.event=a;this.setValue(this.translateToValue((this.isVertical()?c[1]-e[1]:c[0]-e[0])-(this.handleLength/2)));var e=Position.cumulativeOffset(this.activeHandle);this.offsetX=(c[0]-e[0]);this.offsetY=(c[1]-e[1])}else{while((this.handles.indexOf(b)==-1)&&b.parentNode)b=b.parentNode;if(this.handles.indexOf(b)!=-1){this.activeHandle=b;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var e=Position.cumulativeOffset(this.activeHandle);this.offsetX=(c[0]-e[0]);this.offsetY=(c[1]-e[1])}}}Event.stop(a)}},update:function(a){if(this.active){if(!this.dragging)this.dragging=true;this.draw(a);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(a)}},draw:function(a){var b=[Event.pointerX(a),Event.pointerY(a)];var c=Position.cumulativeOffset(this.track);b[0]-=this.offsetX+c[0];b[1]-=this.offsetY+c[1];this.event=a;this.setValue(this.translateToValue(this.isVertical()?b[1]:b[0]));if(this.initialized&&this.options.onSlide)this.options.onSlide(this.values.length>1?this.values:this.value,this)},endDrag:function(a){if(this.active&&this.dragging){this.finishDrag(a,true);Event.stop(a)}this.active=false;this.dragging=false},finishDrag:function(a,b){this.active=false;this.dragging=false;this.updateFinished()},updateFinished:function(){if(this.initialized&&this.options.onChange)this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null}});
//sound.js
Sound={tracks:{},_enabled:true,template:new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'),enable:function(){Sound._enabled=true},disable:function(){Sound._enabled=false},play:function(c){if(!Sound._enabled)return;var d=Object.extend({track:'global',url:c,replace:false},arguments[1]||{});if(d.replace&&this.tracks[d.track]){$R(0,this.tracks[d.track].id).each(function(a){var b=$('sound_'+d.track+'_'+a);b.Stop&&b.Stop();b.remove()});this.tracks[d.track]=null}if(!this.tracks[d.track])this.tracks[d.track]={id:0};else this.tracks[d.track].id++;d.id=this.tracks[d.track].id;$$('body')[0].insert(Prototype.Browser.IE?new Element('bgsound',{id:'sound_'+d.track+'_'+d.id,src:d.url,loop:1,autostart:true}):Sound.template.evaluate(d))}};if(Prototype.Browser.Gecko&&navigator.userAgent.indexOf("Win")>0){if(navigator.plugins&&$A(navigator.plugins).detect(function(p){return p.name.indexOf('QuickTime')!=-1}))Sound.template=new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>');else Sound.play=function(){}}
//load additional files
Scriptaculous.load();

var PageUtils = {
  getPageSize: function(parent){
    parent = parent || document.body;              
    var windowWidth, windowHeight;
    var pageHeight, pageWidth;
    if (parent != document.body) {
      windowWidth = parent.getWidth();
      windowHeight = parent.getHeight();                                
      pageWidth = parent.scrollWidth;
      pageHeight = parent.scrollHeight;                                
    } 
    else {
      var xScroll, yScroll;

      if (window.innerHeight && window.scrollMaxY) {  
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }


      if (self.innerHeight) {  // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }  

      // for small pages with total height less then height of the viewport
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else { 
        pageHeight = yScroll;
      }

      // for small pages with total width less then width of the viewport
      if(xScroll < windowWidth){  
        pageWidth = windowWidth;
      } else {
        pageWidth = xScroll;
      }
    }             
    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  }
}


// CalendarDateSelect version 1.10.2 - a prototype based date picker
// Questions, comments, bugs? - email the Author - Tim Harper <"timseeharper@gmail.seeom".gsub("see", "c")> 
if (typeof Prototype == 'undefined') alert("CalendarDateSelect Error: Prototype could not be found. Please make sure that your application's layout includes prototype.js (.g. <%= javascript_include_tag :defaults %>) *before* it includes calendar_date_select.js (.g. <%= calendar_date_select_includes %>).");
if (Prototype.Version < "1.6") alert("Prototype 1.6.0 is required.  If using earlier version of prototype, please use calendar_date_select version 1.8.3");

Element.addMethods({
  purgeChildren: function(element) { $A(element.childNodes).each(function(e){$(e).remove();}); },
  build: function(element, type, options, style) {
    var newElement = Element.build(type, options, style);
    element.appendChild(newElement);
    return newElement;
  }
});

Element.build = function(type, options, style)
{
  var e = $(document.createElement(type));
  $H(options).each(function(pair) { eval("e." + pair.key + " = pair.value" ); });
  if (style) 
    $H(style).each(function(pair) { eval("e.style." + pair.key + " = pair.value" ); });
  return e;
};
nil = null;

Date.one_day = 24*60*60*1000;
Date.weekdays = $w("S M T W T F S");
Date.first_day_of_week = 0;
Date.months = $w("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec" );
Date.padded2 = function(hour) { var padded2 = parseInt(hour, 10); if (hour < 10) padded2 = "0" + padded2; return padded2; }
Date.prototype.getPaddedMinutes = function() { return Date.padded2(this.getMinutes()); }
Date.prototype.getAMPMHour = function() { var hour = this.getHours(); return (hour == 0) ? 12 : (hour > 12 ? hour - 12 : hour ) }
Date.prototype.getAMPM = function() { return (this.getHours() < 12) ? "AM" : "PM"; }
Date.prototype.stripTime = function() { return new Date(this.getFullYear(), this.getMonth(), this.getDate());};
Date.prototype.daysDistance = function(compare_date) { return Math.round((compare_date - this) / Date.one_day); };
Date.prototype.toFormattedString = function(include_time){
  var hour, str;
  str = Date.months[this.getMonth()] + " " + this.getDate() + ", " + this.getFullYear();
  
  if (include_time) { hour = this.getHours(); str += " " + this.getAMPMHour() + ":" + this.getPaddedMinutes() + " " + this.getAMPM() }
  return str;
}
Date.parseFormattedString = function(string) { return new Date(string);}
Math.floor_to_interval = function(n, i) { return Math.floor(n/i) * i;}
window.f_height = function() { return( [window.innerHeight ? window.innerHeight : null, document.documentElement ? document.documentElement.clientHeight : null, document.body ? document.body.clientHeight : null].select(function(x){return x>0}).first()||0); }
window.f_scrollTop = function() { return ([window.pageYOffset ? window.pageYOffset : null, document.documentElement ? document.documentElement.scrollTop : null, document.body ? document.body.scrollTop : null].select(function(x){return x>0}).first()||0 ); }

_translations = {
  "OK": "OK",
  "Now": "Now",
  "Today": "Today",
	"Clear": "Clear"
}
SelectBox = Class.create();
SelectBox.prototype = {
  initialize: function(parent_element, values, html_options, style_options) {
    this.element = $(parent_element).build("select", html_options, style_options);
    this.populate(values);
  },
  populate: function(values) {
    this.element.purgeChildren();
    var that = this; $A(values).each(function(pair) { if (typeof(pair)!="object") {pair = [pair, pair]}; that.element.build("option", { value: pair[1], innerHTML: pair[0]}) });
  },
  setValue: function(value) {
    var e = this.element;
    var matched = false;
    $R(0, e.options.length - 1 ).each(function(i) { if(e.options[i].value==value.toString()) {e.selectedIndex = i; matched = true;}; } );
    return matched;
  },
  getValue: function() { return $F(this.element)}
}
CalendarDateSelect = Class.create();
CalendarDateSelect.prototype = {
  initialize: function(target_element, options) {
    this.target_element = $(target_element); // make sure it's an element, not a string
    if (!this.target_element) { alert("Target element " + target_element + " not found!"); return false;}
    if (this.target_element.tagName != "INPUT") this.target_element = this.target_element.down("INPUT")
    
    this.target_element.calendar_date_select = this;
    this.last_click_at = 0;
    // initialize the date control
    this.options = $H({
      embedded: false,
      popup: nil,
      time: false,
      buttons: true,
      year_range: 100,
      close_on_click: nil,
      minute_interval: 5,
      popup_by: this.target_element,
      month_year: "dropdowns",
      onchange: this.target_element.onchange,
      valid_date_check: nil
    }).merge(options || {});
    this.use_time = this.options.get("time");
    this.parseDate();
    this.callback("before_show")
    this.initCalendarDiv();
    if(!this.options.get("embedded")) {
      this.positionCalendarDiv()
      // set the click handler to check if a user has clicked away from the document
      Event.observe(document, "mousedown", this.closeIfClickedOut_handler = this.closeIfClickedOut.bindAsEventListener(this));
      Event.observe(document, "keypress", this.keyPress_handler = this.keyPress.bindAsEventListener(this));
    }
    this.callback("after_show")
  },
  positionCalendarDiv: function() {
    var above = false;
    var c_pos = this.calendar_div.cumulativeOffset(), c_left = c_pos[0], c_top = c_pos[1], c_dim = this.calendar_div.getDimensions(), c_height = c_dim.height, c_width = c_dim.width; 
    var w_top = window.f_scrollTop(), w_height = window.f_height();
    var e_dim = $(this.options.get("popup_by")).cumulativeOffset(), e_top = e_dim[1], e_left = e_dim[0], e_height = $(this.options.get("popup_by")).getDimensions().height, e_bottom = e_top + e_height;
    
    if ( (( e_bottom + c_height ) > (w_top + w_height)) && ( e_bottom - c_height > w_top )) above = true;
    var left_px = e_left.toString() + "px", top_px = (above ? (e_top - c_height ) : ( e_top + e_height )).toString() + "px";
    
    this.calendar_div.style.left = left_px;  this.calendar_div.style.top = top_px;
    
    this.calendar_div.setStyle({visibility:""});
    
    // draw an iframe behind the calendar -- ugly hack to make IE 6 happy
    if(navigator.appName=="Microsoft Internet Explorer") this.iframe = $(document.body).build("iframe", {src: "javascript:false", className: "ie6_blocker"}, { left: left_px, top: top_px, height: c_height.toString()+"px", width: c_width.toString()+"px", border: "0px"})
  },
  initCalendarDiv: function() {
    if (this.options.get("embedded")) {
      var parent = this.target_element.parentNode;
      var style = {}
    } else {
      var parent = document.body
      var style = { position:"absolute", visibility: "hidden", left:0, top:0 }
    }
    this.calendar_div = $(parent).build('div', {className: "calendar_date_select"}, style);
    
    var that = this;
    // create the divs
    $w("top header body buttons footer bottom").each(function(name) {
      eval("var " + name + "_div = that." + name + "_div = that.calendar_div.build('div', { className: 'cds_"+name+"' }, { clear: 'left'} ); ");
    });
    
    this.initHeaderDiv();
    this.initButtonsDiv();
    this.initCalendarGrid();
    this.updateFooter("&#160;");
    
    this.refresh();
    this.setUseTime(this.use_time);
  },
  initHeaderDiv: function() {
    var header_div = this.header_div;
    this.close_button = header_div.build("a", { innerHTML: "x", href:"#", onclick:function () { this.close(); return false; }.bindAsEventListener(this), className: "close" });
    this.next_month_button = header_div.build("a", { innerHTML: "&gt;", href:"#", onclick:function () { this.navMonth(this.date.getMonth() + 1 ); return false; }.bindAsEventListener(this), className: "next" });
    this.prev_month_button = header_div.build("a", { innerHTML: "&lt;", href:"#", onclick:function () { this.navMonth(this.date.getMonth() - 1 ); return false; }.bindAsEventListener(this), className: "prev" });
    
    if (this.options.get("month_year")=="dropdowns") {
      this.month_select = new SelectBox(header_div, $R(0,11).map(function(m){return [Date.months[m], m]}), {className: "month", onchange: function () { this.navMonth(this.month_select.getValue()) }.bindAsEventListener(this)}); 
      this.year_select = new SelectBox(header_div, [], {className: "year", onchange: function () { this.navYear(this.year_select.getValue()) }.bindAsEventListener(this)}); 
      this.populateYearRange();
    } else {
      this.month_year_label = header_div.build("span")
    }
  },
  initCalendarGrid: function() {
    var body_div = this.body_div;
    this.calendar_day_grid = [];
    var days_table = body_div.build("table", { cellPadding: "0px", cellSpacing: "0px", width: "100%" })
    // make the weekdays!
    var weekdays_row = days_table.build("thead").build("tr");
    Date.weekdays.each( function(weekday) { 
      weekdays_row.build("th", {innerHTML: weekday});
    });
    
    var days_tbody = days_table.build("tbody")
    // Make the days!
    var row_number = 0, weekday;
    for(var cell_index = 0; cell_index<42; cell_index++)
    {
      weekday = (cell_index+Date.first_day_of_week ) % 7;
      if ( cell_index % 7==0 ) days_row = days_tbody.build("tr", {className: 'row_'+row_number++});
      (this.calendar_day_grid[cell_index] = days_row.build("td", {
          calendar_date_select: this,
          onmouseover: function () { this.calendar_date_select.dayHover(this); },
          onmouseout: function () { this.calendar_date_select.dayHoverOut(this) },
          onclick: function() { this.calendar_date_select.updateSelectedDate(this, true); },
          className: (weekday==0) || (weekday==6) ? " weekend" : "" //clear the class
        },
        { cursor: "pointer" }
      )).build("div");
      this.calendar_day_grid[cell_index];
    }
  },
  initButtonsDiv: function()
  {
    var buttons_div = this.buttons_div;
    if (this.options.get("time"))
    {
      var blank_time = $A(this.options.get("time")=="mixed" ? [[" - ", ""]] : []);
      buttons_div.build("span", {innerHTML:"@", className: "at_sign"});
      
      var t = new Date();
      this.hour_select = new SelectBox(buttons_div,
        blank_time.concat($R(0,23).map(function(x) {t.setHours(x); return $A([t.getAMPMHour()+ " " + t.getAMPM(),x])} )),
        { 
          calendar_date_select: this, 
          onchange: function() { this.calendar_date_select.updateSelectedDate( { hour: this.value });},
          className: "hour" 
        }
      );
      buttons_div.build("span", {innerHTML:":", className: "seperator"});
      var that = this;
      this.minute_select = new SelectBox(buttons_div,
        blank_time.concat($R(0,59).select(function(x){return (x % that.options.get('minute_interval')==0)}).map(function(x){ return $A([ Date.padded2(x), x]); } ) ),
        { 
          calendar_date_select: this, 
          onchange: function() { this.calendar_date_select.updateSelectedDate( {minute: this.value }) }, 
          className: "minute" 
        }
      );
      
    } else if (! this.options.get("buttons")) buttons_div.remove();
    
    if (this.options.get("buttons")) {
      buttons_div.build("span", {innerHTML: "&#160;"});
      if (this.options.get("time")=="mixed" || !this.options.get("time")) b = buttons_div.build("a", {
          innerHTML: _translations["Today"],
          href: "#",
          onclick: function() {this.today(false); return false;}.bindAsEventListener(this)
        });
      
      if (this.options.get("time")=="mixed") buttons_div.build("span", {innerHTML: " | ", className:"button_seperator"})
      
      if (this.options.get("time")) b = buttons_div.build("a", {
        innerHTML: _translations["Now"],
        href: "#",
        onclick: function() {this.today(true); return false}.bindAsEventListener(this)
      });
      
      if (!this.options.get("embedded"))
      {
        buttons_div.build("span", {innerHTML: "&#160;|&#160;"});
        //buttons_div.build("span", {innerHTML: "&#160;"});
        buttons_div.build("a", { innerHTML: _translations["OK"], href: "#", onclick: function() {this.close(); return false;}.bindAsEventListener(this) });
      }
			buttons_div.build("span", {innerHTML: "&nbsp;|&nbsp;"});
			buttons_div.build("a", { innerHTML: _translations["Clear"], href: "#", onclick: function() {this.target_element.value=''; this.close(); return false;}.bindAsEventListener(this) });
    }
  },
  refresh: function ()
  {
    this.refreshMonthYear();
    this.refreshCalendarGrid();
    
    this.setSelectedClass();
    this.updateFooter();
  },
  refreshCalendarGrid: function () {
    this.beginning_date = new Date(this.date).stripTime();
    this.beginning_date.setDate(1);
    this.beginning_date.setHours(12); // Prevent daylight savings time boundaries from showing a duplicate day
    var pre_days = this.beginning_date.getDay() // draw some days before the fact
    if (pre_days < 3) pre_days += 7;
    this.beginning_date.setDate(1 - pre_days + Date.first_day_of_week);
    
    var iterator = new Date(this.beginning_date);
    
    var today = new Date().stripTime();
    var this_month = this.date.getMonth();
    vdc = this.options.get("valid_date_check");
    for (var cell_index = 0;cell_index<42; cell_index++)
    {
      day = iterator.getDate(); month = iterator.getMonth();
      cell = this.calendar_day_grid[cell_index];
      Element.remove(cell.childNodes[0]); div = cell.build("div", {innerHTML:day});
      if (month!=this_month) div.className = "other";
      cell.day = day; cell.month = month; cell.year = iterator.getFullYear();
      if (vdc) { if (vdc(iterator.stripTime())) cell.removeClassName("disabled"); else cell.addClassName("disabled") };
      iterator.setDate( day + 1);
    }
    
    if (this.today_cell) this.today_cell.removeClassName("today");
    
    if ( $R( 0, 41 ).include(days_until = this.beginning_date.stripTime().daysDistance(today)) ) {
      this.today_cell = this.calendar_day_grid[days_until];
      this.today_cell.addClassName("today");
    }
  },
  refreshMonthYear: function() {
    var m = this.date.getMonth();
    var y = this.date.getFullYear();
    // set the month
    if (this.options.get("month_year") == "dropdowns") 
    {
      this.month_select.setValue(m, false);
      
      var e = this.year_select.element; 
      if (this.flexibleYearRange() && (!(this.year_select.setValue(y, false)) || e.selectedIndex <= 1 || e.selectedIndex >= e.options.length - 2 )) this.populateYearRange();
      
      this.year_select.setValue(y);
      
    } else {
      this.month_year_label.update( Date.months[m] + " " + y.toString()  );
    }
  },
  populateYearRange: function() {
    this.year_select.populate(this.yearRange().toArray());
  },
  yearRange: function() {
    if (!this.flexibleYearRange())
      return $R(this.options.get("year_range")[0], this.options.get("year_range")[1]);
      
    var y = this.date.getFullYear();
    return $R(y - this.options.get("year_range"), y + this.options.get("year_range"));
  },
  flexibleYearRange: function() { return (typeof(this.options.get("year_range")) == "number"); },
  validYear: function(year) { if (this.flexibleYearRange()) { return true;} else { return this.yearRange().include(year);}  },
  dayHover: function(element) {
    var hover_date = new Date(this.selected_date);
    hover_date.setYear(element.year); hover_date.setMonth(element.month); hover_date.setDate(element.day);
    this.updateFooter(hover_date.toFormattedString(this.use_time));
  },
  dayHoverOut: function(element) { this.updateFooter(); },
  clearSelectedClass: function() {if (this.selected_cell) this.selected_cell.removeClassName("selected");},
  setSelectedClass: function() {
    if (!this.selection_made) return;
    this.clearSelectedClass()
    if ($R(0,42).include( days_until = this.beginning_date.stripTime().daysDistance(this.selected_date.stripTime()) )) {
      this.selected_cell = this.calendar_day_grid[days_until];
      this.selected_cell.addClassName("selected");
    }
  },
  reparse: function() { this.parseDate(); this.refresh(); },
  dateString: function() {
    return (this.selection_made) ? this.selected_date.toFormattedString(this.use_time) : "&#160;";
  },
  parseDate: function()
  {
    var value = $F(this.target_element).strip()
    this.selection_made = (value != "");
    this.date = value=="" ? NaN : Date.parseFormattedString(this.options.get("date") || value);
    if (isNaN(this.date)) this.date = new Date();
    if (!this.validYear(this.date.getFullYear())) this.date.setYear( (this.date.getFullYear() < this.yearRange().start) ? this.yearRange().start : this.yearRange().end);
    this.selected_date = new Date(this.date);
    this.use_time = /[0-9]:[0-9]{2}/.exec(value) ? true : false;
    this.date.setDate(1);
  },
  updateFooter:function(text) { if (!text) text = this.dateString(); this.footer_div.purgeChildren(); this.footer_div.build("span", {innerHTML: text }); },
  updateSelectedDate:function(partsOrElement, via_click) {
    var parts = $H(partsOrElement);
    if ((this.target_element.disabled) && this.options.get("popup") != "force")
		{
			return false;
		}
    if (parts.get("day")) {
      var t_selected_date = this.selected_date, vdc = this.options.get("valid_date_check");
      for (var x = 0; x<=3; x++) t_selected_date.setDate(parts.get("day"));
      t_selected_date.setYear(parts.get("year"));
      t_selected_date.setMonth(parts.get("month"));
      
      if (vdc && ! vdc(t_selected_date.stripTime())) { return false; }
      this.selected_date = t_selected_date;
      this.selection_made = true;
    }
    
    if (!isNaN(parts.get("hour"))) this.selected_date.setHours(parts.get("hour"));
    if (!isNaN(parts.get("minute"))) this.selected_date.setMinutes( Math.floor_to_interval(parts.get("minute"), this.options.get("minute_interval")) );
    if (parts.get("hour") === "" || parts.get("minute") === "") 
      this.setUseTime(false);
    else if (!isNaN(parts.get("hour")) || !isNaN(parts.get("minute")))
      this.setUseTime(true);
    
    this.updateFooter();
    this.setSelectedClass();
    
    if (this.selection_made) this.updateValue();
    if (this.closeOnClick()) { this.close(); }
    if (via_click && !this.options.get("embedded")) {
      if ((new Date() - this.last_click_at) < 333) this.close();
      this.last_click_at = new Date();
    }
  },
  closeOnClick: function() {
    if (this.options.get("embedded")) return false;
    if (this.options.get("close_on_click")===nil )
      return (this.options.get("time")) ? false : true
    else
      return (this.options.get("close_on_click"))
  },
  navMonth: function(month) { (target_date = new Date(this.date)).setMonth(month); return (this.navTo(target_date)); },
  navYear: function(year) { (target_date = new Date(this.date)).setYear(year); return (this.navTo(target_date)); },
  navTo: function(date) {
    if (!this.validYear(date.getFullYear())) return false;
    this.date = date;
    this.date.setDate(1);
    this.refresh();
    this.callback("after_navigate", this.date);
    return true;
  },
  setUseTime: function(turn_on) {
    this.use_time = this.options.get("time") && (this.options.get("time")=="mixed" ? turn_on : true) // force use_time to true if time==true && time!="mixed"
    if (this.use_time && this.selected_date) { // only set hour/minute if a date is already selected
      var minute = Math.floor_to_interval(this.selected_date.getMinutes(), this.options.get("minute_interval"));
      var hour = this.selected_date.getHours();
      
      this.hour_select.setValue(hour);
      this.minute_select.setValue(minute)
    } else if (this.options.get("time")=="mixed") {
      this.hour_select.setValue(""); this.minute_select.setValue("");
    }
  },
  updateValue: function() {
    var last_value = this.target_element.value;
    this.target_element.value = this.dateString();
    if (last_value!=this.target_element.value) this.callback("onchange");
  },
  today: function(now) {
    var d = new Date(); this.date = new Date();
    var o = $H({ day: d.getDate(), month: d.getMonth(), year: d.getFullYear(), hour: d.getHours(), minute: d.getMinutes()});
    if ( ! now ) o = o.merge({hour: "", minute:""}); 
    this.updateSelectedDate(o, true);
    this.refresh();
  },
  close: function() {
    if (this.closed) return false;
    this.callback("before_close");
    this.target_element.calendar_date_select = nil;
    Event.stopObserving(document, "mousedown", this.closeIfClickedOut_handler);
    Event.stopObserving(document, "keypress", this.keyPress_handler);
    this.calendar_div.remove(); this.closed = true;
    if (this.iframe) this.iframe.remove();
    if (this.target_element.type!="hidden") this.target_element.focus();
    this.callback("after_close");
  },
  closeIfClickedOut: function(e) {
    if (! $(Event.element(e)).descendantOf(this.calendar_div) ) this.close();
  },
  keyPress: function(e) {
    if (e.keyCode==Event.KEY_ESC) this.close();
  },
  callback: function(name, param) { if (this.options.get(name)) { this.options.get(name).bind(this.target_element)(param); } }
}

Date.prototype.toFormattedString = function(include_time){
  str = this.getFullYear() + "-" + Date.padded2(this.getMonth() + 1) + "-" +Date.padded2(this.getDate()); 

if (include_time) { hour=this.getHours(); str += " " + this.getAMPMHour() + ":" + this.getPaddedMinutes() + " " + this.getAMPM() }
return str;
}
Date.prototype.toPondFormattedString = function(include_time){
  var hour, str;
  str = this.getDate() + " " + Date.months[this.getMonth()] + " " + this.getFullYear();
  
  if (include_time) { str += "; " + this.getHours() + ":" + this.getPaddedMinutes() }
  return str;
}

Date.parseFormattedString = function (string) {
  var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
      "( ([0-9]{1,2}):([0-9]{2})? *(pm|am)" +
      "?)?)?)?";
  var d = string.match(new RegExp(regexp, "i"));
  if (d==null) return Date.parse(string); // at least give javascript a crack at it.
  var offset = 0;
  var date = new Date(d[1], 0, 1);
  if (d[3]) { date.setMonth(d[3] - 1); }
  if (d[5]) { date.setDate(d[5]); }
  if (d[7]) {
    hours = parseInt(d[7], 10);
    offset=0;
		if ( "undefined" != typeof(d[9]) )
		{
			is_pm = (d[9].toLowerCase()=="pm")
			if (is_pm && hours <= 11) hours+=12;
			if (!is_pm && hours == 12) hours=0;
		}
    date.setHours(hours); 
  }
  if (d[8]) { date.setMinutes(d[8]); }
  if (d[10]) { date.setSeconds(d[10]); }
  if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
  if (d[14]) {
      offset = (Number(d[16]) * 60) + Number(d[17]);
      offset *= ((d[15] == '-') ? 1 : -1);
  }
  return date;
}


/**
 * @author Ryan Johnson <ryan@livepipe.net>
 * @copyright 2007 LivePipe LLC
 * @package Control.Modal
 * @license MIT
 * @url http://livepipe.net/projects/control_modal/
 * @version 2.2.3
 */

if(typeof(Control) == "undefined")
	Control = {};
Control.Modal = Class.create();
Object.extend(Control.Modal,{
	loaded: false,
	loading: false,
	loadingTimeout: false,
	overlay: false,
	container: false,
	current: false,
	ie: false,
	effects: {
		containerFade: false,
		containerAppear: false,
		overlayFade: false,
		overlayAppear: false
	},
	targetRegexp: /#(.+)$/,
	imgRegexp: /\.(jpe?g|gif|png|tiff?)$/i,
	overlayStyles: {
		position: 'fixed',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
		zIndex: 9998
	},
	overlayIEStyles: {
		position: 'absolute',
		top: 0,
		left: 0,
		zIndex: 9998
	},
	disableHoverClose: false,
	load: function(){
		if(!Control.Modal.loaded){
			Control.Modal.loaded = true;
			Control.Modal.ie = !(typeof document.body.style.maxHeight != 'undefined');
			Control.Modal.overlay = $(document.createElement('div'));
			Control.Modal.overlay.id = 'modal_overlay';
			Object.extend(Control.Modal.overlay.style,Control.Modal['overlay' + (Control.Modal.ie ? 'IE' : '') + 'Styles']);
			Control.Modal.overlay.hide();
			Control.Modal.container = $(document.createElement('div'));
			Control.Modal.container.id = 'modal_container';
			Control.Modal.container.hide();
			Control.Modal.loading = $(document.createElement('div'));
			Control.Modal.loading.id = 'modal_loading';
			Control.Modal.loading.hide();
			var body_tag = document.getElementsByTagName('body')[0];
			body_tag.appendChild(Control.Modal.overlay);
			body_tag.appendChild(Control.Modal.container);
			body_tag.appendChild(Control.Modal.loading);
			Control.Modal.container.observe('mouseout',function(event){
				if(!Control.Modal.disableHoverClose && Control.Modal.current && Control.Modal.current.options.hover && !Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
					Control.Modal.close();
			});
		}
	},
	open: function(contents,options){
		options = options || {};
		if(!options.contents)
			options.contents = contents;
		var modal_instance = new Control.Modal(false,options);
		modal_instance.open();
		return modal_instance;
	},
	close: function(force){
		if(typeof(force) != 'boolean')
			force = false;
		if(Control.Modal.current)
			Control.Modal.current.close(force);
	},
	attachEvents: function(){
		Event.observe(window,'load',Control.Modal.load);
		//Event.observe(window,'unload',Event.unloadCache,false);
	},
	center: function(element){
		if(!element._absolutized){
			element.setStyle({
				position: 'absolute'
			}); 
			element._absolutized = true;
		}
		var dimensions = element.getDimensions();
		Position.prepare();
		var offset_left = (Position.deltaX + Math.floor((Control.Modal.getWindowWidth() - dimensions.width) / 2));
		var offset_top = (Position.deltaY + ((Control.Modal.getWindowHeight() > dimensions.height) ? Math.floor((Control.Modal.getWindowHeight() - dimensions.height) / 2) : 0));
		element.setStyle({
			top: ((dimensions.height <= Control.Modal.getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0),
			left: ((dimensions.width <= Control.Modal.getDocumentWidth()) ? ((offset_left != null && offset_left > 0) ? offset_left : '0') + 'px' : 0)
		});
	},
	getWindowWidth: function(){
		return (self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0);
	},
	getWindowHeight: function(){
		return (self.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0);
	},
	getDocumentWidth: function(){
		return Math.min(document.body.scrollWidth,Control.Modal.getWindowWidth());
	},
	getDocumentHeight: function(){
		return Math.max(document.body.scrollHeight,Control.Modal.getWindowHeight());
	},
	onKeyDown: function(event){
		if(event.keyCode == Event.KEY_ESC)
			Control.Modal.close();
	}
});
Object.extend(Control.Modal.prototype,{
	mode: '',
	html: false,
	href: '',
	element: false,
	src: false,
	imageLoaded: false,
	ajaxRequest: false,
	initialize: function(element,options){
		this.element = $(element);
		this.options = {
			beforeOpen: Prototype.emptyFunction,
			afterOpen: Prototype.emptyFunction,
			beforeClose: Prototype.emptyFunction,
			afterClose: Prototype.emptyFunction,
			onSuccess: Prototype.emptyFunction,
			onFailure: Prototype.emptyFunction,
			onException: Prototype.emptyFunction,
			beforeImageLoad: Prototype.emptyFunction,
			afterImageLoad: Prototype.emptyFunction,
			autoOpenIfLinked: true,
			contents: false,
			loading: false, //display loading indicator
			fade: false,
			fadeDuration: 0.75,
			image: false,
			imageCloseOnClick: true,
			hover: false,
			iframe: false,
			iframeTemplate: new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0" id="#{id}"></iframe>'),
			evalScripts: true, //for Ajax, define here instead of in requestOptions
			requestOptions: {}, //for Ajax.Request
			overlayDisplay: true,
			overlayClassName: '',
			overlayCloseOnClick: true,
			containerClassName: '',
			opacity: 0.3,
			zIndex: 9998,
			width: null,
			height: null,
			offsetLeft: 0, //for use with 'relative'
			offsetTop: 0, //for use with 'relative'
			position: 'absolute' //'absolute' or 'relative'
		};
		Object.extend(this.options,options || {});
		var target_match = false;
		var image_match = false;
		if(this.element){
			target_match = Control.Modal.targetRegexp.exec(this.element.href);
			image_match = Control.Modal.imgRegexp.exec(this.element.href);
		}
		if(this.options.position == 'mouse')
			this.options.hover = true;
		if(this.options.contents){
			this.mode = 'contents';
		}else if(this.options.image || image_match){
			this.mode = 'image';
			this.src = this.element.href;
		}else if(target_match){
			this.mode = 'named';
			var x = $(target_match[1]);
			this.html = x.innerHTML;
			x.remove();
			this.href = target_match[1];
		}else{
			this.mode = (this.options.iframe) ? 'iframe' : 'ajax';
			this.href = this.element.href;
		}
		if(this.element){
			if(this.options.hover){
				this.element.observe('mouseover',this.open.bind(this));
				this.element.observe('mouseout',function(event){
					if(!Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
						this.close();
				}.bindAsEventListener(this));
			}else{
				this.element.onclick = function(event){
					this.open();
					Event.stop(event);
					return false;
				}.bindAsEventListener(this);
			}
		}
		var targets = Control.Modal.targetRegexp.exec(window.location);
		this.position = function(event){
			if(this.options.position == 'absolute')
				Control.Modal.center(Control.Modal.container);
			else{
				var xy = (event && this.options.position == 'mouse' ? [Event.pointerX(event),Event.pointerY(event)] : Position.cumulativeOffset(this.element));
				Control.Modal.container.setStyle({
					position: 'absolute',
					top: xy[1] + (typeof(this.options.offsetTop) == 'function' ? this.options.offsetTop() : this.options.offsetTop) + 'px',
					left: xy[0] + (typeof(this.options.offsetLeft) == 'function' ? this.options.offsetLeft() : this.options.offsetLeft) + 'px'
				});
			}
			if(Control.Modal.ie){
				Control.Modal.overlay.setStyle({
					height: Control.Modal.getDocumentHeight() + 'px',
					width: Control.Modal.getDocumentWidth() + 'px'
				});
			}
		}.bind(this);
		if(this.mode == 'named' && this.options.autoOpenIfLinked && targets && targets[1] && targets[1] == this.href)
			this.open();
	},
	showLoadingIndicator: function(){
		if(this.options.loading){
			Control.Modal.loadingTimeout = window.setTimeout(function(){
				var modal_image = $('modal_image');
				if(modal_image)
					modal_image.hide();
				Control.Modal.loading.style.zIndex = this.options.zIndex + 1;
				Control.Modal.loading.update('<img id="modal_loading" src="' + this.options.loading + '"/>');
				Control.Modal.loading.show();
				Control.Modal.center(Control.Modal.loading);
			}.bind(this),250);
		}
	},
	hideLoadingIndicator: function(){
		if(this.options.loading){
			if(Control.Modal.loadingTimeout)
				window.clearTimeout(Control.Modal.loadingTimeout);
			var modal_image = $('modal_image');
			if(modal_image)
				modal_image.show();
			Control.Modal.loading.hide();
		}
	},
	open: function(force){
		if(!force && this.notify('beforeOpen') === false)
			return;
		if(!Control.Modal.loaded)
			Control.Modal.load();
		Control.Modal.close();
		if(!this.options.hover)
			Event.observe($(document.getElementsByTagName('body')[0]),'keydown',Control.Modal.onKeyDown);
		Control.Modal.current = this;
		if(!this.options.hover)
			Control.Modal.overlay.setStyle({
				zIndex: this.options.zIndex,
				opacity: this.options.opacity
			});

		var new_width = (this.options.width ? (typeof(this.options.width) == 'function' ? this.options.width() : this.options.width) + '' : null);
		var new_height = (this.options.height ? (typeof(this.options.height) == 'function' ? this.options.height() : this.options.height) + '' : null);

		if ( new_width != null )
		new_width += new_width.endsWith('px') ? "": "px";

		if ( new_height != null )
		new_height += new_height.endsWith('px') ? "": "px";

		Control.Modal.container.setStyle({
			zIndex: this.options.zIndex + 1,
			width: new_width,
			height: new_height
		});
		if(Control.Modal.ie && !this.options.hover){
			$A(document.getElementsByTagName('select')).each(function(select){
				select.style.visibility = 'hidden';
			});
		}
		Control.Modal.overlay.addClassName(this.options.overlayClassName);
		Control.Modal.container.addClassName(this.options.containerClassName);
		switch(this.mode){
			case 'image':
				this.imageLoaded = false;
				this.notify('beforeImageLoad');
				this.showLoadingIndicator();
				var img = document.createElement('img');
				img.onload = function(img){
					this.hideLoadingIndicator();
					this.update([img]);
					if(this.options.imageCloseOnClick)
						$(img).observe('click',Control.Modal.close);
					this.position();
					this.notify('afterImageLoad');
					img.onload = null;
				}.bind(this,img);
				img.src = this.src;
				img.id = 'modal_image';
				break;
			case 'ajax':
				this.notify('beforeLoad');
				var options = {
					method: 'post',
					onSuccess: function(request){
						this.hideLoadingIndicator();
						this.update(request.responseText);
						this.notify('onSuccess',request);
						this.ajaxRequest = false;
					}.bind(this),
					onFailure: function(){
						this.notify('onFailure');
					}.bind(this),
					onException: function(){
						this.notify('onException');
					}.bind(this)
				};
				Object.extend(options,this.options.requestOptions);
				this.showLoadingIndicator();
				this.ajaxRequest = new Ajax.Request(this.href,options);
				break;
			case 'iframe':
				this.update(this.options.iframeTemplate.evaluate({href: this.href, id: 'modal_iframe'}));
				break;
			case 'contents':
				this.update((typeof(this.options.contents) == 'function' ? this.options.contents() : this.options.contents));
				break;
			case 'named':
				this.update(this.html);
				break;
		}
		if(!this.options.hover){
			if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
				Control.Modal.overlay.observe('click',Control.Modal.close);
			if(this.options.overlayDisplay){
				if(this.options.fade){
					if(Control.Modal.effects.overlayFade)
						Control.Modal.effects.overlayFade.cancel();
					Control.Modal.effects.overlayAppear = new Effect.Appear(Control.Modal.overlay,{
						queue: {
							position: 'front',
							scope: 'Control.Modal'
						},
						to: this.options.opacity,
						duration: this.options.fadeDuration / 2
					});
				}else
					Control.Modal.overlay.show();
			}
		}
		if(this.options.position == 'mouse'){
			this.mouseHoverListener = this.position.bindAsEventListener(this);
			this.element.observe('mousemove',this.mouseHoverListener);
		}
		this.notify('afterOpen');
	},
	update: function(html){
		if(typeof(html) == 'string')
			Control.Modal.container.update(html);
		else{
			Control.Modal.container.update('');
			(html.each) ? html.each(function(node){
				Control.Modal.container.appendChild(node);
			}) : Control.Modal.container.appendChild(node);
		}
		if(this.options.fade){
			if(Control.Modal.effects.containerFade)
				Control.Modal.effects.containerFade.cancel();
			Control.Modal.effects.containerAppear = new Effect.Appear(Control.Modal.container,{
				queue: {
					position: 'end',
					scope: 'Control.Modal'
				},
				to: 1,
				duration: this.options.fadeDuration / 2
			});
		}else
			Control.Modal.container.show();
		this.position();
		Event.observe(window,'resize',this.position,false);
		Event.observe(window,'scroll',this.position,false);
	},
	close: function(force){
		if(!force && this.notify('beforeClose') === false)
			return;
		if(this.ajaxRequest)
			this.ajaxRequest.transport.abort();
		this.hideLoadingIndicator();	
		if(this.mode == 'image'){
			var modal_image = $('modal_image');
			if(this.options.imageCloseOnClick && modal_image)
				modal_image.stopObserving('click',Control.Modal.close);
		}
		if(Control.Modal.ie && !this.options.hover){
			$A(document.getElementsByTagName('select')).each(function(select){
				select.style.visibility = 'visible';
			});			
		}
		if(!this.options.hover)
			Event.stopObserving(window,'keyup',Control.Modal.onKeyDown);
		Control.Modal.current = false;
		Event.stopObserving(window,'resize',this.position,false);
		Event.stopObserving(window,'scroll',this.position,false);
		if(!this.options.hover){
			if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
				Control.Modal.overlay.stopObserving('click',Control.Modal.close);
			if(this.options.overlayDisplay){
				if(this.options.fade){
					if(Control.Modal.effects.overlayAppear)
						Control.Modal.effects.overlayAppear.cancel();
					Control.Modal.effects.overlayFade = new Effect.Fade(Control.Modal.overlay,{
						queue: {
							position: 'end',
							scope: 'Control.Modal'
						},
						from: this.options.opacity,
						to: 0,
						duration: this.options.fadeDuration / 2
					});
				}else
					Control.Modal.overlay.hide();
			}
		}
		if(this.options.fade){
			if(Control.Modal.effects.containerAppear)
				Control.Modal.effects.containerAppear.cancel();
			Control.Modal.effects.containerFade = new Effect.Fade(Control.Modal.container,{
				queue: {
					position: 'front',
					scope: 'Control.Modal'
				},
				from: 1,
				to: 0,
				duration: this.options.fadeDuration / 2,
				afterFinish: function(){
					Control.Modal.container.update('');
					this.resetClassNameAndStyles();
				}.bind(this)
			});
		}else{
			Control.Modal.container.hide();
			Control.Modal.container.update('');
			this.resetClassNameAndStyles();
		}
		if(this.options.position == 'mouse')
			this.element.stopObserving('mousemove',this.mouseHoverListener);
		this.notify('afterClose');
	},
	resetClassNameAndStyles: function(){
		Control.Modal.overlay.removeClassName(this.options.overlayClassName);
		Control.Modal.container.removeClassName(this.options.containerClassName);
		Control.Modal.container.setStyle({
			height: null,
			width: null,
			top: null,
			left: null
		});
	},
	notify: function(event_name){
		try{
			if(this.options[event_name])
				return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
		}catch(e){
			if(e != $break)
				throw e;
			else
				return false;
		}
	}
});
if(typeof(Object.Event) != 'undefined')
	Object.Event.extend(Control.Modal);
Control.Modal.attachEvents();


if(typeof (Control)=="undefined"){Control={};}Control.Rating=Class.create();Object.extend(Control.Rating,{instances:[],findByElementId:function(id){return Control.Rating.instances.find(function(_2){return (_2.container.id&&_2.container.id==id);});}});Object.extend(Control.Rating.prototype,{container:false,value:false,options:{},initialize:function(_3,_4){Control.Rating.instances.push(this);this.value=false;this.links=[];this.container=$(_3);this.container.update("");this.options={min:1,max:5,rated:false,input:false,reverse:false,capture:true,multiple:false,classNames:{off:"rating_off",half:"rating_half",on:"rating_on",selected:"rating_selected"},updateUrl:false,updateParameterName:"value",afterChange:Prototype.emptyFunction};Object.extend(this.options,_4||{});if(this.options.value){this.value=this.options.value;delete this.options.value;}if(this.options.input){this.options.input=$(this.options.input);this.options.input.observe("change",function(_5){this.setValueFromInput(_5);}.bind(this,this.options.input));this.setValueFromInput(this.options.input,true);}var _6=$R(this.options.min,this.options.max);(this.options.reverse?$A(_6).reverse():_6).each(function(i){var _8=this.buildLink(i);this.container.appendChild(_8);this.links.push(_8);}.bind(this));this.setValue(this.value||this.options.min-1,false,true);},buildLink:function(_9){var _a=$(document.createElement("a"));_a.value=_9;if(this.options.multiple||(!this.options.rated&&!this.options.multiple)){_a.href="";_a.onmouseover=this.mouseOver.bind(this,_a);_a.onmouseout=this.mouseOut.bind(this,_a);_a.onclick=this.click.bindAsEventListener(this,_a);}else{_a.style.cursor="default";_a.observe("click",function(_b){Event.stop(_b);return false;}.bindAsEventListener(this));}_a.addClassName(this.options.classNames.off);return _a;},disable:function(){this.links.each(function(_c){_c.onmouseover=Prototype.emptyFunction;_c.onmouseout=Prototype.emptyFunction;_c.onclick=Prototype.emptyFunction;_c.observe("click",function(_d){Event.stop(_d);return false;}.bindAsEventListener(this));_c.style.cursor="default";}.bind(this));},setValueFromInput:function(_e,_f){this.setValue((_e.options?_e.options[_e.options.selectedIndex].value:_e.value),true,_f);},setValue:function(_10,_11,_12){this.value=_10;if(this.options.input){if(this.options.input.options){$A(this.options.input.options).each(function(_13,i){if(_13.value==this.value){this.options.input.options.selectedIndex=i;throw $break;}}.bind(this));}else{this.options.input.value=this.value;}}this.render(this.value,_11);if(!_12){if(this.options.updateUrl){var _15={};_15[this.options.updateParamterName]=this.value;new Ajax.Request(this.options.updateUrl,{parameters:_15});}this.notify("afterChange",this.value);}},render:function(_16,_17){(this.options.reverse?this.links.reverse():this.links).each(function(_18,i){if(_18.value<=Math.ceil(_16)){_18.className=this.options.classNames[_18.value<=_16?"on":"half"];if(this.options.rated||_17){_18.addClassName(this.options.classNames.selected);}}else{_18.className=this.options.classNames.off;}}.bind(this));},mouseOver:function(_1a){this.render(_1a.value,true);},mouseOut:function(_1b){this.render(this.value);},click:function(_1c,_1d){this.options.rated=true;this.setValue((_1d.value?_1d.value:_1d),true);if(!this.options.multiple){this.disable();}if(this.options.capture){Event.stop(_1c);return false;}},notify:function(_1e){try{if(this.options[_1e]){return [this.options[_1e].apply(this.options[_1e],$A(arguments).slice(1))];}}catch(e){if(e!=$break){throw e;}else{return false;}}}});if(typeof (Object.Event)!="undefined"){Object.Event.extend(Control.Rating);}

/*----------------------------------------------------------------------------\
|                                XMenu 1.12                                   |
|-----------------------------------------------------------------------------|
|                          Created by Erik Arvidsson                          |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| An object based tree widget,  emulating the one found in microsoft windows, |
| with persistence using cookies. Works in IE 5+, Mozilla and konqueror 3.    |
|-----------------------------------------------------------------------------|
|                   Copyright (c) 1999 - 2002 Emil A Eklund                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2001-01-12 | Original Version Posted.                                       |
| 2001-11-20 | Added hover mode support and removed Opera focus hacks         |
| 2001-12-20 | (1.1) Added auto positioning and some properties to support    |
|            | this.                                                          |
| 2002-08-13 | (1.11) toString used ' for attributes. Changed to " to allow   |
|            | in properties/arguments.                                       |
| 2003-04-27 | (1.12) Added support for target property on menu item/button   |
|-----------------------------------------------------------------------------|
| Created 2001-01-12 | All changes are in the log above. | Updated 2003-04-27 |
\----------------------------------------------------------------------------*/



// check browsers
var ua = navigator.userAgent;
var opera = /opera [56789]|opera\/[56789]/i.test(ua);
var ie = !opera && /MSIE/.test(ua);
var ie50 = ie && /MSIE 5\.[01234]/.test(ua);
var ie6 = ie && /MSIE [6789]/.test(ua);
var ieBox = ie && (document.compatMode == null || document.compatMode != "CSS1Compat");
var moz = !opera && /gecko/i.test(ua);
var nn6 = !opera && /netscape.*6\./i.test(ua);
// define the default values
webfxMenuDefaultWidth			= 100;

webfxMenuDefaultBorderLeft		= 1;
webfxMenuDefaultBorderRight		= 1;
webfxMenuDefaultBorderTop		= 1;
webfxMenuDefaultBorderBottom	= 1;
webfxMenuDefaultPaddingLeft		= 1;
webfxMenuDefaultPaddingRight	= 1;
webfxMenuDefaultPaddingTop		= 1;
webfxMenuDefaultPaddingBottom	= 1;

webfxMenuDefaultShadowLeft		= 0;
webfxMenuDefaultShadowRight		= ie && !ie50 && /win32/i.test(navigator.platform) ? 4 :0;
webfxMenuDefaultShadowTop		= 0;
webfxMenuDefaultShadowBottom	= ie && !ie50 && /win32/i.test(navigator.platform) ? 4 : 0;

webfxMenuItemDefaultHeight		= 18;
webfxMenuItemDefaultText		= "Untitled";
webfxMenuItemDefaultHref		= "javascript:void(0)";

webfxMenuSeparatorDefaultHeight	= 6;

webfxMenuDefaultEmptyText		= "Empty";

webfxMenuDefaultUseAutoPosition	= nn6 ? false : true;

// other global constants
webfxMenuImagePath				= "";

webfxMenuUseHover				= opera ? true : false;
webfxMenuHideTime				= 500;
webfxMenuShowTime				= 200;

var webFXMenuHandler = {
	idCounter		:	0,
	idPrefix		:	"webfx-menu-object-",
	all				:	{},
	getId			:	function () { return this.idPrefix + this.idCounter++; },
	overMenuItem	:	function (oItem) {
		if (this.showTimeout != null)
			window.clearTimeout(this.showTimeout);
		if (this.hideTimeout != null)
			window.clearTimeout(this.hideTimeout);
		var jsItem = this.all[oItem.id];
		if (webfxMenuShowTime <= 0)
			this._over(jsItem);
		else
			//this.showTimeout = window.setTimeout(function () { webFXMenuHandler._over(jsItem) ; }, webfxMenuShowTime);
			// I hate IE5.0 because the piece of shit crashes when using setTimeout with a function object
			this.showTimeout = window.setTimeout("webFXMenuHandler._over(webFXMenuHandler.all['" + jsItem.id + "'])", webfxMenuShowTime);
	},
	outMenuItem	:	function (oItem) {
		if (this.showTimeout != null)
			window.clearTimeout(this.showTimeout);
		if (this.hideTimeout != null)
			window.clearTimeout(this.hideTimeout);
		var jsItem = this.all[oItem.id];
		if (webfxMenuHideTime <= 0)
			this._out(jsItem);
		else
			//this.hideTimeout = window.setTimeout(function () { webFXMenuHandler._out(jsItem) ; }, webfxMenuHideTime);
			this.hideTimeout = window.setTimeout("webFXMenuHandler._out(webFXMenuHandler.all['" + jsItem.id + "'])", webfxMenuHideTime);
	},
	blurMenu		:	function (oMenuItem) {
		window.setTimeout("webFXMenuHandler.all[\"" + oMenuItem.id + "\"].subMenu.hide();", webfxMenuHideTime);
	},
	_over	:	function (jsItem) {
		if (jsItem.subMenu) {
			jsItem.parentMenu.hideAllSubs();
			jsItem.subMenu.show();
		}
		else
			jsItem.parentMenu.hideAllSubs();
	},
	_out	:	function (jsItem) {
		// find top most menu
		var root = jsItem;
		var m;
		if (root instanceof WebFXMenuButton)
			m = root.subMenu;
		else {
			m = jsItem.parentMenu;
			while (m.parentMenu != null && !(m.parentMenu instanceof WebFXMenuBar))
				m = m.parentMenu;
		}
		if (m != null)
			m.hide();
	},
	hideMenu	:	function (menu) {
		if (this.showTimeout != null)
			window.clearTimeout(this.showTimeout);
		if (this.hideTimeout != null)
			window.clearTimeout(this.hideTimeout);

		this.hideTimeout = window.setTimeout("webFXMenuHandler.all['" + menu.id + "'].hide()", webfxMenuHideTime);
	},
	showMenu	:	function (menu, src, dir) {
	
		// a. patel: hack to hide all other menus before showing a menu (this gets rid of the double menu showing
		// at once bug.
		ck4HideAllMenus();

		if (this.showTimeout != null)
			window.clearTimeout(this.showTimeout);
		if (this.hideTimeout != null)
			window.clearTimeout(this.hideTimeout);
		if (arguments.length < 3)
			dir = "vertical";

		menu.show(src, dir);
	}
};

function WebFXMenu() {
	this._menuItems	= [];
	this._subMenus	= [];
	this.id			= webFXMenuHandler.getId();
	this.top		= 0;
	this.left		= 0;
	this.shown		= false;
	this.parentMenu	= null;
	webFXMenuHandler.all[this.id] = this;
}

WebFXMenu.prototype.width			= webfxMenuDefaultWidth;
WebFXMenu.prototype.emptyText		= webfxMenuDefaultEmptyText;
WebFXMenu.prototype.useAutoPosition	= webfxMenuDefaultUseAutoPosition;

WebFXMenu.prototype.borderLeft		= webfxMenuDefaultBorderLeft;
WebFXMenu.prototype.borderRight		= webfxMenuDefaultBorderRight;
WebFXMenu.prototype.borderTop		= webfxMenuDefaultBorderTop;
WebFXMenu.prototype.borderBottom	= webfxMenuDefaultBorderBottom;

WebFXMenu.prototype.paddingLeft		= webfxMenuDefaultPaddingLeft;
WebFXMenu.prototype.paddingRight	= webfxMenuDefaultPaddingRight;
WebFXMenu.prototype.paddingTop		= webfxMenuDefaultPaddingTop;
WebFXMenu.prototype.paddingBottom	= webfxMenuDefaultPaddingBottom;

WebFXMenu.prototype.shadowLeft		= webfxMenuDefaultShadowLeft;
WebFXMenu.prototype.shadowRight		= webfxMenuDefaultShadowRight;
WebFXMenu.prototype.shadowTop		= webfxMenuDefaultShadowTop;
WebFXMenu.prototype.shadowBottom	= webfxMenuDefaultShadowBottom;

WebFXMenu.prototype.add = function (menuItem) {
	this._menuItems[this._menuItems.length] = menuItem;
	if (menuItem.subMenu) {
		this._subMenus[this._subMenus.length] = menuItem.subMenu;
		menuItem.subMenu.parentMenu = this;
	}

	menuItem.parentMenu = this;
};

WebFXMenu.prototype.show = function (relObj, sDir) {
	if (this.useAutoPosition)
		this.position(relObj, sDir);

	var divElement = document.getElementById(this.id);
	divElement.style.left = opera ? this.left : this.left + "px";
	divElement.style.top = opera ? this.top : this.top + "px";
	divElement.style.visibility = "visible";
	this.shown = true;
	if (this.parentMenu)
		this.parentMenu.show();
};

WebFXMenu.prototype.hide = function () {
	this.hideAllSubs();
	var divElement = document.getElementById(this.id);
	divElement.style.visibility = "hidden";
	this.shown = false;
};

WebFXMenu.prototype.hideAllSubs = function () {
	for (var i = 0; i < this._subMenus.length; i++) {
		if (this._subMenus[i].shown)
			this._subMenus[i].hide();
	}
};
WebFXMenu.prototype.toString = function () {
	var top = this.top + this.borderTop + this.paddingTop;
	var str = "<div id='" + this.id + "' class='webfx-menu' style='" +
	"width:" + (!ieBox  ?
		this.width - this.borderLeft - this.paddingLeft - this.borderRight - this.paddingRight  :
		this.width) + "px;" +
	(this.useAutoPosition ?
		"left:" + this.left + "px;" + "top:" + this.top + "px;" :
		"") +
	(ie50 ? "filter: none;" : "") +
	"'>";

	if (this._menuItems.length == 0) {
		str +=	"<span class='webfx-menu-empty'>" + this.emptyText + "</span>";
	}
	else {
		// loop through all menuItems
		for (var i = 0; i < this._menuItems.length; i++) {
			var mi = this._menuItems[i];
			str += mi;
			if (!this.useAutoPosition) {
				if (mi.subMenu && !mi.subMenu.useAutoPosition)
					mi.subMenu.top = top - mi.subMenu.borderTop - mi.subMenu.paddingTop;
				top += mi.height;
			}
		}

	}

	str += "</div>";

	for (var i = 0; i < this._subMenus.length; i++) {
		this._subMenus[i].left = this.left + this.width - this._subMenus[i].borderLeft;
		str += this._subMenus[i];
	}

	return str;
};
// WebFXMenu.prototype.position defined later
function WebFXMenuItem(sText, sHref, sToolTip, oSubMenu) {
	this.text = sText || webfxMenuItemDefaultText;
	this.href = (sHref == null || sHref == "") ? webfxMenuItemDefaultHref : sHref;
	this.subMenu = oSubMenu;
	if (oSubMenu)
		oSubMenu.parentMenuItem = this;
	this.toolTip = sToolTip;
	this.id = webFXMenuHandler.getId();
	webFXMenuHandler.all[this.id] = this;
};
WebFXMenuItem.prototype.height = webfxMenuItemDefaultHeight;
WebFXMenuItem.prototype.toString = function () {
	return	"<a" +
			" id='" + this.id + "'" +
			" href=\"" + this.href + "\"" +
			(this.target ? " target=\"" + this.target + "\"" : "") +
			(this.toolTip ? " title=\"" + this.toolTip + "\"" : "") +
			" onmouseover='webFXMenuHandler.overMenuItem(this)'" +
			(webfxMenuUseHover ? " onmouseout='webFXMenuHandler.outMenuItem(this)'" : "") +
			(this.subMenu ? " unselectable='on' tabindex='-1'" : "") +
			">" +
			(this.subMenu ? "<img class='arrow' src=\"" + webfxMenuImagePath + "arrow.right.png\">" : "") +
			this.text +
			"</a>";
};


function WebFXMenuSeparator() {
	this.id = webFXMenuHandler.getId();
	webFXMenuHandler.all[this.id] = this;
};
WebFXMenuSeparator.prototype.height = webfxMenuSeparatorDefaultHeight;
WebFXMenuSeparator.prototype.toString = function () {
	return	"<div" +
			" id='" + this.id + "'" +
			(webfxMenuUseHover ?
			" onmouseover='webFXMenuHandler.overMenuItem(this)'" +
			" onmouseout='webFXMenuHandler.outMenuItem(this)'"
			:
			"") +
			"></div>"
};

function WebFXMenuBar() {
	this._parentConstructor = WebFXMenu;
	this._parentConstructor();
}
WebFXMenuBar.prototype = new WebFXMenu;
WebFXMenuBar.prototype.toString = function () {
	var str = "<div id='" + this.id + "' class='webfx-menu-bar'>";

	// loop through all menuButtons
	for (var i = 0; i < this._menuItems.length; i++)
		str += this._menuItems[i];

	str += "</div>";

	for (var i = 0; i < this._subMenus.length; i++)
		str += this._subMenus[i];

	return str;
};

function WebFXMenuButton(sText, sHref, sToolTip, oSubMenu) {
	this._parentConstructor = WebFXMenuItem;
	this._parentConstructor(sText, sHref, sToolTip, oSubMenu);
}
WebFXMenuButton.prototype = new WebFXMenuItem;
WebFXMenuButton.prototype.toString = function () {
	return	"<a" +
			" id='" + this.id + "'" +
			" href=\"" + this.href + "\"" +
			(this.target ? " target=\"" + this.target + "\"" : "") +
			(this.toolTip ? " title=\"" + this.toolTip + "\"" : "") +
			(webfxMenuUseHover ?
				(" onmouseover='webFXMenuHandler.overMenuItem(this)'" +
				" onmouseout='webFXMenuHandler.outMenuItem(this)'") :
				(
					" onfocus='webFXMenuHandler.overMenuItem(this)'" +
					(this.subMenu ?
						" onblur='webFXMenuHandler.blurMenu(this)'" :
						""
					)
				)) +
			">" +
			this.text +
			(this.subMenu ? " <img class='arrow' src=\"" + webfxMenuImagePath + "arrow.down.png\" align='absmiddle'>" : "") +
			"</a>";
};


/* Position functions */

function getInnerLeft(el) {
	if (el == null) return 0;
	if (ieBox && el == document.body || !ieBox && el == document.documentElement) return 0;
	return getLeft(el) + getBorderLeft(el);
}

function getLeft(el) {
	if (el == null) return 0;
	return el.offsetLeft + getInnerLeft(el.offsetParent);
}

function getInnerTop(el) {
	if (el == null) return 0;
	if (ieBox && el == document.body || !ieBox && el == document.documentElement) return 0;
	return getTop(el) + getBorderTop(el);
}

function getTop(el) {
	if (el == null) return 0;
	return el.offsetTop + getInnerTop(el.offsetParent);
}

function getBorderLeft(el) {
	return ie ?
		el.clientLeft :
		parseInt(window.getComputedStyle(el, null).getPropertyValue("border-left-width"));
}

function getBorderTop(el) {
	return ie ?
		el.clientTop :
		parseInt(window.getComputedStyle(el, null).getPropertyValue("border-top-width"));
}

function opera_getLeft(el) {
	if (el == null) return 0;
	return el.offsetLeft + opera_getLeft(el.offsetParent);
}

function opera_getTop(el) {
	if (el == null) return 0;
	return el.offsetTop + opera_getTop(el.offsetParent);
}

function getOuterRect(el) {
	return {
		left:	(opera ? opera_getLeft(el) : getLeft(el)),
		top:	(opera ? opera_getTop(el) : getTop(el)),
		width:	el.offsetWidth,
		height:	el.offsetHeight
	};
}

// mozilla bug! scrollbars not included in innerWidth/height
function getDocumentRect(el) {
	return {
		left:	0,
		top:	0,
		width:	(ie ?
					(ieBox ? document.body.clientWidth : document.documentElement.clientWidth) :
					window.innerWidth
				),
		height:	(ie ?
					(ieBox ? document.body.clientHeight : document.documentElement.clientHeight) :
					window.innerHeight
				)
	};
}

function getScrollPos(el) {
	return {
		left:	(ie ?
					(ieBox ? document.body.scrollLeft : document.documentElement.scrollLeft) :
					window.pageXOffset
				),
		top:	(ie ?
					(ieBox ? document.body.scrollTop : document.documentElement.scrollTop) :
					window.pageYOffset
				)
	};
}

/* end position functions */

WebFXMenu.prototype.position = function (relEl, sDir) {
	var dir = sDir;
	// find parent item rectangle, piRect
	var piRect;
	if (!relEl) {
		var pi = this.parentMenuItem;
		if (!this.parentMenuItem)
			return;

		relEl = document.getElementById(pi.id);
		if (dir == null)
			dir = pi instanceof WebFXMenuButton ? "vertical" : "horizontal";

		piRect = getOuterRect(relEl);
	}
	else if (relEl.left != null && relEl.top != null && relEl.width != null && relEl.height != null) {	// got a rect
		piRect = relEl;
	}
	else
		piRect = getOuterRect(relEl);

	var menuEl = document.getElementById(this.id);
	var menuRect = getOuterRect(menuEl);
	var docRect = getDocumentRect();
	var scrollPos = getScrollPos();
	var pMenu = this.parentMenu;

	if (dir == "vertical") {
		if (piRect.left + menuRect.width - scrollPos.left <= docRect.width)
			this.left = piRect.left;
		else if (docRect.width >= menuRect.width)
			this.left = docRect.width + scrollPos.left - menuRect.width;
		else
			this.left = scrollPos.left;

		if (piRect.top + piRect.height + menuRect.height <= docRect.height + scrollPos.top)
			this.top = piRect.top + piRect.height;
		else if (piRect.top - menuRect.height >= scrollPos.top)
			this.top = piRect.top - menuRect.height;
		else if (docRect.height >= menuRect.height)
			this.top = docRect.height + scrollPos.top - menuRect.height;
		else
			this.top = scrollPos.top;
	}
	else {
		if (piRect.top + menuRect.height - this.borderTop - this.paddingTop <= docRect.height + scrollPos.top)
			this.top = piRect.top - this.borderTop - this.paddingTop;
		else if (piRect.top + piRect.height - menuRect.height + this.borderTop + this.paddingTop >= 0)
			this.top = piRect.top + piRect.height - menuRect.height + this.borderBottom + this.paddingBottom + this.shadowBottom;
		else if (docRect.height >= menuRect.height)
			this.top = docRect.height + scrollPos.top - menuRect.height;
		else
			this.top = scrollPos.top;

		var pMenuPaddingLeft = pMenu ? pMenu.paddingLeft : 0;
		var pMenuBorderLeft = pMenu ? pMenu.borderLeft : 0;
		var pMenuPaddingRight = pMenu ? pMenu.paddingRight : 0;
		var pMenuBorderRight = pMenu ? pMenu.borderRight : 0;

		if (piRect.left + piRect.width + menuRect.width + pMenuPaddingRight +
			pMenuBorderRight - this.borderLeft + this.shadowRight <= docRect.width + scrollPos.left)
			this.left = piRect.left + piRect.width + pMenuPaddingRight + pMenuBorderRight - this.borderLeft;
		else if (piRect.left - menuRect.width - pMenuPaddingLeft - pMenuBorderLeft + this.borderRight + this.shadowRight >= 0)
			this.left = piRect.left - menuRect.width - pMenuPaddingLeft - pMenuBorderLeft + this.borderRight + this.shadowRight;
		else if (docRect.width >= menuRect.width)
			this.left = docRect.width  + scrollPos.left - menuRect.width;
		else
			this.left = scrollPos.left;
	}
};


function constExpression(x) {
	return x;
}

function simplifyCSSExpression() {
	try {
		var ss,sl, rs, rl;
		ss = document.styleSheets;
		sl = ss.length
	
		for (var i = 0; i < sl; i++) {
			simplifyCSSBlock(ss[i]);
		}
	}
	catch (exc) {
		alert("Got an error while processing css. The page should still work but might be a bit slower");
		throw exc;
	}
}

function simplifyCSSBlock(ss) {
	var rs, rl;
	
	for (var i = 0; i < ss.imports.length; i++)
		simplifyCSSBlock(ss.imports[i]);
	
	if (ss.cssText.indexOf("expression(constExpression(") == -1)
		return;

	rs = ss.rules;
	rl = rs.length;
	for (var j = 0; j < rl; j++)
		simplifyCSSRule(rs[j]);
	
}

function simplifyCSSRule(r) {
	var str = r.style.cssText;
	var str2 = str;
	var lastStr;
	do {
		lastStr = str2;
		str2 = simplifyCSSRuleHelper(lastStr);
	} while (str2 != lastStr)

	if (str2 != str)
		r.style.cssText = str2;
}

function simplifyCSSRuleHelper(str) {
	var i, i2;
	i = str.indexOf("expression(constExpression(");
	if (i == -1) return str;
	i2 = str.indexOf("))", i);
	var hd = str.substring(0, i);
	var tl = str.substring(i2 + 2);
	var exp = str.substring(i + 27, i2);
	var val = eval(exp)
	return hd + val + tl;
}

if (/msie/i.test(navigator.userAgent) && window.attachEvent != null) {
	window.attachEvent("onload", function () {
		simplifyCSSExpression();
	});
}

// vim: set foldmethod=marker:
//------------------------------------------------------------------------------
// util_func.js
//
//	This file consists of some general purpose JS code used througout the
//	site.
//
//	@author		Aman. Patel <aman.patel@stjude.org>
//	@co-author		Martin Norland <martin.norland@stjude.org>
//	
//------------------------------------------------------------------------------

// JS GLOBALs

// this is an array that contains all onLoad
var onload_functions = new Array();

// Standard Detection Variables (GLOBALS):
DOM = (document.getElementById) ? true : false;
NS4 = (document.layers) ? true : false;
IE = (document.all) ? true : false;
IE4 = IE && !DOM;
isIE = ((document.all) || (IE4 && navigator.appVersion.indexOf("5.")!=-1));

// State of form values stored in this global
var frm_state = new Array;


// {{{ registerOnLoadFunction
//
// Register an onload function to be called upon BODY.onLoad()
//
// Returns void.
// Accepts a Function Object (  i.e. func_obj = new Function("alert('this is the body of this function');");   )
//
// takes an optional parameter to determine 'when' it is onloaded, 0 going first and higher being later
// defaults to (0) if not specified
// TODO - prefer to have it default to 10 (so things that are specified have a chance to go before it)
// TODO - so use our condense_array function across the array in the onload

function registerOnLoadFunction( func_obj , onload_position) {
	// append the func_obj to onloads global array.
	if ( onload_position == null) { onload_position = 0; }
	if (onload_functions[onload_position] == null) { onload_functions[onload_position] = new Array(); }
	if ( func_obj != null ) {
		onload_functions[onload_position][onload_functions[onload_position].length] = func_obj;
	}
}
// }}}

// {{{ Navigate
//
// Navigate to a url
//
// This function is used mostly in <input type="button">'s onClick events to
// transfer the user to a particular URL.
//
//	p_URL	The url where to transfer to.
//

function navigate( p_URL ) {
	window.parent.location.href=p_URL;
}
// }}}

// {{{ parse_pond_id
function parse_pond_id(str)
{
	var id = new String(str);
	var i = id.indexOf("[");
	var rec = id.substr(0,i);
  id = id.substr(i + 1);
  id = id.substring(0, id.length-1);
  id = id.split("][");

	return new Array(rec,id[0],id[1],id[2]);
}
// }}}


// {{{ calcBSA
// Calculate Body Surface Area according to formula:
// also calculates the BMI (body mass index)
//
// bsa = sqrt( (height*weight/3600) );
function calcBSA(focus_field)
{
	// determine the table/view
	arr = parse_pond_id(focus_field.id);
	var rec = arr[0];
	var table = arr[1];
	var view = arr[2];
	var field = arr[3];

	height = $(rec+"["+table+"]["+view+"][height]");
	mass = $(rec+"["+table+"]["+view+"][weight]");
	bsa_field = $(rec+"["+table+"]["+view+"][calc_bsa]");
	bmi_field = $(rec+"["+table+"]["+view+"][calc_bmi]");

	if ( height.value < 0 || mass.value < 0 )
	{
		bsa_field.value = "0";
		bmi_field.value = "0";
		return;
	}

	// see formula above...
	var bsa = Math.pow(
			((height.value * mass.value)/3600),
			1/2
		);

	// Round to the nearest 0.01
	bsa = Math.round(bsa * 100) / 100;

	var bmi = ( mass.value / Math.pow((height.value/100),2) );
	bmi = Math.round(bmi * 100) / 100;

	if (isNaN(bsa))
	{
		// alert("<?php tpl_lang("error_enter_only_num"); ?>");
		focus_field.value = "";
		focus_field.focus();
		return;
	}

	if (isNaN(bmi))
	{
		//alert("<?php tpl_lang("error_enter_only_num"); ?>");
		focus_field.value = "";
		focus_field.focus();
		return;
	}

	if (bsa_field)
	{
		bsa_field.value = bsa.toString();
	}
	if (bmi_field)
	{
		bmi_field.value = bmi.toString();
	}
}
// }}}

// {{{ popup_window
//
// Opens a popup window
//
// All parameters are optional.
//
//	p_Width		width of the popped window (default 560)
//	p_Height	height of the window (default 400)
//	p_Name		name of the window (can be used to later refer back to
//			the particular window.
//	p_MenuBar	yes/no, on whether to include the menu bar
//	p_ToolBar	yes/no, on whether to include the tool bar
//
function popup_window(p_Where, p_Width, p_Height, p_Name, p_MenuBar, p_ToolBar)
{
	if (p_Width == '') {p_Width = 560}
	if (p_Height == '') {p_Height = 400}
	if (p_Name == '') {p_Name = 'fetch_pop'}
	if (p_MenuBar == '') {p_MenuBar = 'yes'}
	if (p_ToolBar == '') {p_ToolBar = 'no'}
	var win=open(p_Where, p_Name,
		'menubar='+p_MenuBar
		+',toolbar='+p_ToolBar
		+',width=' + p_Width
		+',height=' + p_Height
		+',resizable=1,'
		+'scrollbars=1');
	win.moveTo(0,0);
	win.focus();
	return win;
}
// }}}

// {{{ email_validation
//
// Checks email address to see if it complies with the normal
// 	user@site.name
// format.
//
// returns true/false depending upon the validation result.
//
function email_validation(e)
{
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
	for(i=0; i < e.length ;i++)
		if(ok.indexOf(e.charAt(i))<0)	return (false);

	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two))	return (-1);		
	}
}
// }}}

// {{{ getElement
/**
 * This function taken from functions.js of phpMyAdmin codebase. (thank you!)
 *
 * Provided with a element id (the value of id="") it returns the corresponding
 * object.
 *
 * getElement
 *
 */
function getElement(e,f)
{
    if(document.layers){
        f=(f)?f:self;
        if(f.document.layers[e]) {
            return f.document.layers[e];
        }
        for(W=0;i<f.document.layers.length;W++) {
            return(getElement(e,fdocument.layers[W]));
        }
    }
    if(document.all) {
        return document.all[e];
    }
    return document.getElementById(e);
}
// }}}

// {{{ setChanged
/**
* 
* This function looks for the element named userChanged[] and sets it to
* 'y'.
* 
// added by a.patel:
//	This function will now check for original value of this element at the
//	load time, if the values are same, it set the change mark to 'n', see
//	the white paper.
	//if ( changed_name == '' ) {		// be backwards compatible, not
	//					// all setcChanged will pass
	//					// this param 
	//	changed_object = MM_findObj ( changed_name )
	//	// did this object was changed back to the original value?
	//	if ( changed_object.value == frm_state[changed_name] ) { 
	//		// it did, so mark as not changed.
	//		obj.value = 'n';	
	//	}
	//}
*/
function setChanged(n)
{
	objname = 'userChanged[' + n + ']';
	obj = MM_findObj(objname);
	obj.value = 'y';
	return true;
}
// }}}

// {{{ storeState
/**
 * Store the state of all form values and names.
 *
 */

function storeState(frm)
{
	frm = MM_findObj( frm );
	for( i=0; i< frm.elements.length; i++ )
	{
		n = frm.elements[i].name;
		frm_state[n] = frm.elements[i].value;
	}
}
// }}}

// {{{ check_for_onload_function
/**
 * Calls all registered on load functions for this page.
 *
 * This function is not a user function. It is called by every
 * page's onLoad event.
 *
 * Returns nothing.
 * Accepts nothing.
 *
 */

function check_for_onload_function()
{
	if (window.onloadfunc != undefined)
	{
		onloadfunc();
	}

	if (onload_functions != undefined)
	{
		for (var i =0; i < onload_functions.length; i++ )
		{
			if (onload_functions[i] != undefined)
			{
				for (var j = 0; j < onload_functions[i].length; j++ )
				{
					onload_functions[i][j]();
				}
			}
		}
	}
}
// }}}

// {{{ g_set_form_elements
function g_set_form_elements(form_obj, begins_with, value)
{
	for ( var i=0; i <= form_obj.elements.length; i++ )
	{

		if ( form_obj.elements[i] )
		{
			name_str = new String(form_obj.elements[i].name); // because x.name is not a String() object
			if ( name_str.substr(0,begins_with.length) == begins_with )
			{
				//form_obj.elements[i].disabled=false; // at some point we may want stuff disabled until enabled

				if (form_obj.elements[i].options)
				{
					g_set_dropdown(form_obj.elements[i],'');
				}
				else if( form_obj.elements[i].type == "radio" )
				{
					if ( form_obj.elements[i].value == value )
					{
						form_obj.elements[i].checked = true;
					}
				}
				else
				{
					form_obj.elements[i].value = '';
				}
			}
		}
	}
}
// }}}

// {{{ g_select_radiogroup
function g_select_radiogroup(obj, value)
{
	// obj is the radio group array
	for( var i=0; i < obj.length; i++ )
	{
		if (obj[i].type == "radio")
		{
			if (obj[i].value == value)
			{
				// select this:
				obj[i].checked = true;
			}
		}
	}
}
// }}}

// {{{ g_set_dropdown
/**
 * Set a dropdown to a specific value
 * [works with multi's but won't unset w/o extra params/code.]
 *
 */

function g_set_dropdown(dropdownid, newvalue, clear)
{
	if (clear == null)
	{
		clear = true;
	}
	if (clear == true)
	{
		dropdownid.selectedIndex = -1; // safe default
	}
	//pieces.options[i].selected
	if (g_isArray(newvalue))
	{
		// array of items, call recursively.
		for (var i=0; i<newvalue.length;i++)
		{
			g_set_dropdown(dropdownid, newvalue[i], false);
		}
	}
	else
	{
		// single item
		for (var i=0; i<dropdownid.options.length; i++)
		{
			if (dropdownid.options[i].value == newvalue)
			{
				dropdownid.options[i].selected = true;
			}
		}
	}
}
// }}}

// {{{ g_translate_dropdown
/**
 * Translate a value from a dropdown. (eg. you pass male_female_dropdown, 'm'
 * and 'Male' is returned)
 *
 */

function g_translate_dropdown(dropdownid, key)
{
	// searches through a dropdown for key == dropdownid.value, and returns the displayed key
	for (var i=0; i<dropdownid.options.length; i++)
	{
		if (dropdownid.options[i].value == key)
		{
			return dropdownid.options[i].innerHTML;
		}
	}
	return key;
}
// }}}

// {{{ g_set_value
/**
 * Set an items value to the passed value [convenience function, allows us to apply other functions to the data
 * if we wish
 *
 */

function g_set_value (inputid, newvalue)
{
	inputid.value = newvalue;
}
// }}}

// {{{ g_condense_array
/**
 * Takes a sparse array (eg. Arr[0]="foo", Arr[50]="bar") and condenses it into Arr[0]/Arr[1] - this is needed
 * because javascript implicitly defines the values inbetween, and it doesn't condense when you try to delete them.
 *
 * returns the array condensed - so you must use this function as:
 *   myarray = condense_array( myarray) ;
 * (does not just blindly set the array assuming it's global)
 */

function g_condense_array( myarray )
{
	var dense_array = new Array();
	var skipped = 0;
	for (var i=0; i<myarray.length; i++)
	{
		// TODO: check against '== undefined' here
		if (myarray[i] == "")
		{
			skipped++;
		}
		else
		{
			dense_array[i-skipped] = myarray[i];
		}
	}
	return dense_array;
}
// }}}

// {{{ g_htmlent_string
/**
 * takes a value and a description of which quotes to htmlent and does just that, replaces them.
 * used when writing to innerHTML, input values - so all data will be stored.
 *   eg. 'this " would break' => <input type="hidden" value="this " would break">
 *
 * when pulling back out of database, values must be stripslashes'd (through tpl())
 */

function g_htmlent_string( value, which )
{
	// double, single, both [none - nah!]
	switch(which)
	{
		case 'double':
			value = g_htmlent_double(value);
			break;
		case 'single':
			value = g_htmlent_single(value);
			break;
		default: // all
			// handle & and/or ; *FIRST* if you ever do them
			value = g_htmlent_double(value);
			value = g_htmlent_single(value);
			break;
	}
	return value;
}
// }}}

// {{{ g_htmlent_string
/**
 * child function of g_htmlent_string - handles single quotes
 */
function g_htmlent_single(str)
{
	str_obj = new String(str);
	var re = new RegExp ("'", 'gi') ;
	return (str_obj.replace(re,"&#39;")); // (&apos;) &#39;    [&apos works but isn't standard]
}
// }}}

// {{{ g_htmlent_double
/**
 * child function of g_htmlent_string - handles double quotes
 */
function g_htmlent_double(str)
{
	str_obj = new String(str);
	var re = new RegExp ('"', 'gi') ;
	return (str_obj.replace(re,'&quot;')); // &quot; &#34;
}
// }}}

// {{{ g_class_add
function g_class_add(which, what)
{
	which.className = what + " " + which.className;
}
// }}}

// {{{ g_class_strip
function g_class_strip(which, what)
{
	regex = new RegExp("(.*)"+what+"(.*)","");
	which.className = which.className.replace(regex, "$1$2");
}
// }}}

// {{{ g_set_options
//
// replace all <options> of a select box (target)
//
function g_set_options(target, values, names, blank)
{
	var blank_opt_str = '';
	if (blank == null) {
		blank = 1; // default true, have blanks
	} else if (blank != false) {
		if (blank != true && blank != 1) { blank_opt_str = blank; } // if they pass a string, use that as display
		blank = 1;
	} else {
		blank = 0; // blank should be 0 for false
	}
	//if (values.length == 1 && values[0] == "") { return;show_noclassification(); }

	var newnum = values.length + blank; // include blank option in length
	var oldnum = target.options.length; // already includes blank option in length
	if (blank == 1) { target.options[0] = new Option(blank_opt_str,"") }
	for (var i=blank; i < newnum; i++) {
		var newoption = new Option(names[i-blank], values[i-blank]); // correct indexing for blank option
		target.options[i] = newoption; // add 1 [if blank] to 'hop' the blank option at the front
	}
	// clear out extraneous options (if exist)
	if (newnum < oldnum) {
		for (var i=newnum; i < oldnum; i++) {
			target.options[newnum] = null; // nulling deletes it entirely, thus moving the index down
		}
	}
	target.selectedIndex = 0;
}
// }}}

// {{{ g_set_options_categorized
//
// replace all <options> of a select box (target)
//
function g_set_options_categorized(target, contents, blank)
{
// contents is an array of categories, containing vals/names paired arrays
// e.g. contents[category]['vals'] = 'value_stored';
//      contents[category]['names'] = 'the Value printed';
	var blank_opt_str = '';
	if (blank == null) {
		blank = 1; // default true, have blanks
	} else if (blank != false) {
		if (blank != true && blank != 1) { blank_opt_str = blank; } // if they pass a string, use that as display
		blank = 1;
	} else {
		blank = 0; // blank should be 0 for false
	}
	//if (values.length == 1 && values[0] == "") { return;show_noclassification(); }

	var oldnum = target.options.length; // already includes blank option in length
	if (blank == 1) { target.options[0] = new Option(blank_opt_str,"") }
	var current_spot = blank;
	var cat_string = " - - - - - ";
	for (var c in contents) {
		var newoption = new Option( cat_string + contents[c]['cat'] + cat_string, '');
		newoption.disabled = true; // disable our 'categories'
		newoption.style.color = "#00c"; // make them blue :)
		newoption.style.background_color = "#333";
		target.options[current_spot] = newoption;
		current_spot = current_spot + 1;
		for (var i=0; i < contents[c]['vals'].length; i++) {
			var newoption = new Option(contents[c]['names'][i], contents[c]['vals'][i]);
			target.options[current_spot] = newoption;
			current_spot = current_spot + 1;
		}
	}
	// clear out extraneous options (if exist)
	if (current_spot < oldnum) {
		for (var i=current_spot; i < oldnum; i++) {
			target.options[current_spot] = null; // nulling deletes it entirely, thus moving the index down
		}
	}
	target.selectedIndex = 0;
}
// }}}

// {{{ g_print_dialog
function g_print_dialog()
{
	if (typeof(window.print) != 'undefined')
	{
		window.print();
	}
}
// }}}

// {{{ g_set_display
// which = which item.
// status: display (values: block | none | inline | list-item)
//  block      - show (xxx deprecated - use '')
//  none       - hide but do not occupy space
//  inline     - show (xxx deprecated - use '')
//  list-item  - show as list item (n/a?)
//  ''         - show
function g_set_display( which, status )
{
	which.style.display = status
}
// }}}

// {{{ g_set_visibility
// which = which item.
// status: visibility (values: inherit | visible | hidden)
//  inherit - inherit vis from parent
//  hidden  - hide (still occupys space)
//  visible - show
function g_set_visibility( which, status )
{
	which.style.visibility = status
}
// }}}

// {{{ g_toggle_disp_hide
function g_toggle_disp_hide ( which ) {
	if (which.style.display != 'hidden') {
		which.style.display = 'hidden';
	}
	else {
		which.style.display = '';
	}
}
// }}}

// {{{ g_toggle_disp_none
//--------------------------------------------------
// used to toggle the display of a MM_findObj object (html id)
function g_toggle_disp_none ( which ) {
	if (which.style.display != 'none') {
		which.style.display = 'none';
	}
	else {
		which.style.display = '';
	}
}
// }}}

// {{{ g_display_value
//--------------------------------------------------
// used to display the value of a form field, type is one of string or select.
	function g_display_value(value, type, object) {
		// type is one of 'string' or 'select':  object is optional - used for dropdowns
		// todo select type is UNTESTED as of right now
		if (type == 'select') { return g_translate_dropdown(object, value); }
		// from here out - we're just echoing it, so we set blanks to nbsp'd
		if (value == '') { value = "&nbsp;"; }
		if (type == 'string') { return value; }
		if (type == 'comment') { return value; }
	}
// }}}

// {{{ is_empty
//--------------------------------------------------
// test if arr is empty...
function is_empty( arr )
{
	if ( arr.length <= 1 && arr[0] == undefined )
	{
		return true;
	}
	else
	{
		return false;
	}
}
// }}}

// {{{ g_isArray
// Return a boolean value telling whether the first argument is an Array object.
function g_isArray()
{
	if (typeof arguments[0] == 'object')
	{
		var criterion = arguments[0].constructor.toString().match(/array/i);
		return (criterion != null);
	}
	return false;
}
// }}}

// {{{ g_isString
// Return a boolean value telling whether the first argument is a string.
function g_isString() {
	if (typeof arguments[0] == 'string')
	{
		return true;
	}

	if (typeof arguments[0] == 'object')
	{
		var criterion = arguments[0].constructor.toString().match(/string/i);
		return (criterion != null);
	}
	return false;
}
// }}}

// {{{ g_in_array
function g_in_array(needle,haystack)
{
	for(i=0; i<haystack.length;i++)
	{
		if ( haystack[i] == needle )
		{
			return true;
		}
	}
	return false;
}
// }}}

// {{{ vital_recalc_multi
function vital_recalc_multi(which, view)
{
	if (view == null)
	{
		return false;
	}
	var total = 0;
	var divide = 0;
	var measurement_1 = MM_findObj('record[patient_vital]['+view+']['+which+'_1]');
	var measurement_2 = MM_findObj('record[patient_vital]['+view+']['+which+'_2]');
	var measurement_3 = MM_findObj('record[patient_vital]['+view+']['+which+'_3]');
	var measurement = MM_findObj('record[patient_vital]['+view+']['+which+']');
	if ( parseFloat(measurement_1.value) >= 0 )
	{
		total += parseFloat(measurement_1.value); divide++;
	}
	else
	{
		measurement_1.value = '';
	}
	if (parseFloat(measurement_2.value) >= 0)
	{
		total += parseFloat(measurement_2.value); divide++;
	}
	else
	{
		measurement_2.value = '';
	}

	if (parseFloat(measurement_3.value) >= 0)
	{
		total += parseFloat(measurement_3.value); divide++;
	}
	else
	{
		measurement_3.value = '';
	}
	
	if ( total > 0 )
	{
		measurement.value = Math.round((total * 100)/ divide)/100;
	}
	else
	{
		//var original_measurement = MM_findObj('NONDATA[patient_vital]['+view+']['+which+']');
		//measurement.value = original_measurement.value;
	}
	return;
}
// }}}

// {{{ vital_calc_muamc
function vital_calc_muamc(which,view)
{
	var calc_field = MM_findObj('record[patient_vital]['+view+'][calc_muamc_'+which+']');
	if (calc_field != null)
	{
		var tricep = MM_findObj('record[patient_vital]['+view+'][sft_tricep_'+which+']');
		var muac = MM_findObj('record[patient_vital]['+view+'][midupper_arm_circ_'+which+']');
		var calculated = ( Math.round((parseFloat(muac.value)*10 - (parseFloat(tricep.value) * Math.PI))))/10;
		if (isNaN(calculated))
		{
			calculated = "";
		}
		calc_field.value = calculated;
	}
}
// }}}

// {{{ g_jsobj_properties
// returns a string with a single level of properties of the DOM element itemized
function g_jsobj_properties(which, max)
{
	var count = 0;
	var results = "";
	if (max == null)
	{
		max = 3;
	}
	for (var i in which)
	{
		results += i + ": " + which[i] + "\t";
		count++;
		if (count%max == 0)
		{
			count = 0;
			results += "\n";
		}
	}
	return results;
}
// }}}

// {{{ next_click_innerHTML
function next_click_innerHTML(that)
{
	if (that.innerHTML == lang_translations.click_to_expand)
	{
		that.innerHTML = lang_translations.click_to_collapse;
	}
	else
	{
		that.innerHTML = lang_translations.click_to_expand;
	}
}
// }}}

// {{{ g_jsobj_children
function g_jsobj_children(which)
{
	var count = 0;
	for (var i in which)
	{
		count++;
	}
	return count;
}
// }}}

// {{{ toggle_lab_fields
function toggle_lab_fields(table, view)
{
	var extras = new Array ('spec_rcvd_datetime', 'spec_rcvd_comments', 'spec_proc_datetime', 'spec_proc_comments');
	for (var i=0; i<extras.length; i++)
	{
		var target = MM_findObj(table+'_'+view+'_extra_labdata_'+extras[i]);
		if (target != null)
		{
			g_toggle_disp_none(target);
		}
	}
}
// }}}

// {{{ change_pond_language
function change_pond_language(l)
{
	document.change_language_form.list_lang.value = l;
	document.change_language_form.submit();
}
// }}}

// {{{ g_set_visibility
function MM_findObj(n, d)
{
	var p, i, x;
	
	if (!d) {
		d = document;
	}
	
	if ((p = n.indexOf('?')) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p+1)].document;
		n = n.substring(0,p);
	}
	
	if (!(x = d[n]) && d.all) {
		x = d.all[n];
	}
	
	for (i = 0; !x && i < d.forms.length; i++) {
		x = d.forms[i][n];
	}
	
	for (i = 0; !x && d.layers && i < d.layers.length; i++) {
		x = MM_findObj(n, d.layers[i].document);
	}
	
	if(!x && d.getElementById) {
		x=d.getElementById(n);
	}
	
	return x;
}
// }}}

// {{{ pond_status_change
function pond_status_change(obj)
{
	// first turn off all status blocks
	$$('div#divs_patient_status > div').each(function(d){
		d.hide();
	});

	// if blank selected
	// only process if it was not blank
	$("div_patient_status_"+obj.value).show();
	return;
}
// }}}

var help_contents_var;
var help_modal_control;
// {{{ help
function help(id)
{
	var url = docu_root+"home/help/article.php?id="+id;
	help_modal_control = new Control.Modal(false, {
		height: 580,
		width: 750,
		fade: true,
		position: 'absolute',
		contents: function() {
			new Ajax.Request(url,{
				asynchronous: false,
				onComplete: function(r){
					help_contents_var = r.responseText;
				}
			});
			return help_contents_var;
		}
	});  
	help_modal_control.open();
	return false;
}
// }}}

function show_help_dialog(txt, icon)
{
	if (undefined == icon)
	{
		icon = 'help-browser';
	}
	
	html = "";
	html += '<div align="left">';
	html += '  <img hspace="4" src="'+docu_root+'custom/images/tango/32/'+icon+'.gif" align="left" />';
	html += txt;
	html += '</div>';

	help_modal_control = new Control.Modal(false, {contents: html});
	help_modal_control.open();

	return;
}

function show_video_player(url)
{
	new Ajax.Request(url,{
		asynchronous: false,
		onComplete: function(r)
		{
			help_modal_control.update(r.responseText);
		}
	});
}


function close_help_dialog()
{
	help_modal_control.close();
}


var comments_contents_var;
var comments_modal_control;
// {{{ comments
function comments(id)
{
  var url = docu_root+"home/pond_message_comments.php?id="+id;
  comments_modal_control = new Control.Modal(false, {
    height: 580,
    width: 750,
    fade: true,
    position: 'absolute',
    contents: function() {
      new Ajax.Request(url,{
        asynchronous: false,
        onComplete: function(r){
          comments_contents_var = r.responseText;
        }
      });
      return comments_contents_var;
    }
  });
  comments_modal_control.open();
  return false;
}
// }}}

// {{{ modifyThisReport
// function to go back to the report page from a button
function modifyThisReport(href)
{
	if ( href != '' && href != null )
	{
		window.location.href = href;
	}			
}
// }}}

function insert_iframe_status_alive(patient_id)
{
	//#piecediv_1403
	var obj = $('piecediv_1403');
	if (obj == null || obj == 'piecediv_1403')
	{
		// didn't exists
		$('div_patient_status_alive').innerHTML = "<iframe src='"+http_root+"patient/ajax/dstatus.php?patient_id="+patient_id+"' width='900' height='420'></iframe>";
	}
	else
	{
		// ok go ahead with the iframe
		//
		$('div_patient_status_alive').innerHTML = "<a href='#groupfieldset_9_patient_diagnosis_disease'>Click here to edit disease status</a>";
	}
}

// replace the in-existent function (because of control.modal 2.2.3 insists on using it)
if (typeof Prototype != 'undefined') 
	Event.unloadCache = Prototype.emptyFunction  


	// global array holding form control objects created in record_header
	var form_controls = new Array();

	function form_control(table, view, patient_id, record_id, is_qf, patient_qf_id) {
		this.loaded = false;
		this.table = table;
		this.view = view;
		this.patient_id = patient_id;
		this.record_id = record_id;
		this.is_qf = is_qf;
		this.patient_qf_id = patient_qf_id;
		this.action = 'patient/detail/action/index.php';
		this.review = false;

		this.onload = function () {
			this.target_form = MM_findObj('form_control_master');
			this.form_review = MM_findObj('form_control_review['+this.table+']['+this.view+']');
			this.form_delete = MM_findObj('form_control_delete['+this.table+']['+this.view+']');
			this.loaded = true;
		};

		this.register_review = function (obj) {
			this.review = obj;
		}

		this.open_delete = function () {
			if (this.loaded) {
				g_set_display( this.form_review, 'none' );
				g_toggle_disp_none ( this.form_delete );
			}
			return false;
		};

		this.open_review = function () {
			if (this.loaded) {
				g_set_display( this.form_delete, 'none' )
				g_toggle_disp_none ( this.form_review );
			}
			return false;
		};

		this.close = function () {
			if (this.loaded) {
				g_set_display( this.form_delete, 'none' )
				g_set_display( this.form_review, 'none' )
			}
			return false;
		};

		this.process_submit = function (operation) {
			// get+set the form action
			var getstring = MM_findObj( 'query', this.target_form);
			query = getstring.value;
			this.target_form.action = docu_root + this.action + '?' + query; // docu_root is defined in header
			// now set the operation
			var op = MM_findObj( 'op', this.target_form);
			op.value = operation;
			// now set the common fields
			var field = MM_findObj( 'table', this.target_form);
			field.value = this.table;
			var field = MM_findObj( 'view', this.target_form);
			field.value = this.view;
			var field = MM_findObj( 'patient_id', this.target_form);
			field.value = this.patient_id;
			var field = MM_findObj( 'record_id', this.target_form);
			field.value = this.record_id;
			var field = MM_findObj( 'is_qf', this.target_form);
			field.value = this.is_qf;
			var field = MM_findObj( 'patient_qf_id', this.target_form);
			field.value = this.patient_qf_id;
			// finally, submit the form
			this.target_form.submit();
		}

		this.process_delete = function (mode) {
			var confirmation = lang_translations.form_control_really_confirm_delete_form;
			if (this.table == 'patient') { confirmation = lang_translations.form_control_really_confirm_delete_patient; }
			var are_they_sure = confirm(confirmation);
			this.close();
			if (are_they_sure == true) {
				if (mode == 'all') {
					this.process_submit('delete_all');
				}
				else {
					this.process_submit('delete');
				}
			}
			return false;
		};

		this.process_review = function () {
			this.close();
			if (this.review != false) {
				var review = MM_findObj( 'form_control_review', this.target_form);
				review.value = this.review.value
				this.process_submit('review');
			}
			this.review = false; // unset it each iteration, they need to focus to store this.
		};

		return false;

	}

	function onload_all_form_controls() {
		for (var i=0; i < form_controls.length; i++) {
			form_controls[i].onload();
		}
	}

	load_up_form_controls = new Function("onload_all_form_controls();");
	registerOnLoadFunction( load_up_form_controls );

// --- 
// interesting way to delve into objects
// ---
//function onload_all_form_controls() {
//	for (y in form_controls) {
//		y_obj = eval('form_controls.' + y);
//		for (x in y_obj) {
//			x_obj = eval('form_controls.' + y + '.' + x);
//			if (x == 'onload_form_controls') { x_obj(); }
//		}
//	}
//}

	// duplicates all the child form elements of a given element
	function DOM_duplicate_form ( element, dest_form ) {
		new_dom = DOM_duplicate_fields ( element );
		results = DOM_addelements ( new_dom, dest_form );
		return results;
	}

	function DOM_addelements ( element_array, dest_form ) {
		if (element_array != null) {
			if (element_array.length > 0) {
				for (var i=0; i < element_array.length; i++) {
					DOM_addelements ( element_array[i], dest_form );
				}
			} else {
				// this removal should be neccessary - but for some reason nothing seems to be disabled
				//alert(element_array.value);
				element_array.disabled = false;
				dest_form.appendChild(element_array);
			}
		return true;
		}
		return false;
	}
	
	// duplicates the fields and values of a given DOM element
	function DOM_duplicate_fields ( element ) {
		// check if we're a form element
		//alert("element check: " + element.tagName + " " + element + " - " + element.childNodes.length + " ::: " + element.value);
		//elements = Array("input", "textarea");
		alert(element.tagName);
		if ( (element.tagName == 'INPUT') || (element.tagName == 'TEXTAREA') ) {
			new_fields = element;
		// else check if we have children
		} else if (element.childNodes.length > 0) {
			var new_fields = Array();
			for (var i=0; i < element.childNodes.length; i++) {
				new_fields[i] = DOM_duplicate_fields ( element.childNodes[i] )
			}
		}
		return new_fields;
	}



function cia_popuptime(tgt, part, src)
{
	// tgt is the target element name (hh:mm format)
	// part is 'h' or 'm' (for hours or minutes)
	// src is 'this' select element for hours or minutes

	elem = MM_findObj(tgt);

	val = src.options[src.selectedIndex].value;

	current_value = elem.value;
	hours = current_value.substr(0,2);
	minutes = current_value.substr(3,2);

	if (val < 10) val = '0' + val;

	if (part == 'h') {
		elem.value = val + ':' + minutes;
	}

	if (part == 'm') {
		elem.value = hours + ':' + val;
	}

	return true;
}


// vim: set foldmethod=marker:
// 

var Pond_Child = Class.create();
Object.extend(Pond_Child.prototype,{

	// {{{ initialize
	// the data definition of the repeating fields
	initialize: function(data_definition, default_values, div_id, instance_object_name)
	{
		//constructor of the pond child class goes here.
		this.dd = data_definition;
		this.default_values = default_values;
		this.div_element = $(div_id);
		//this.parent_table_name = this.dd.table_name;
		this.table_name = this.dd.child_table_name;
		this.view_name = this.dd.view_name;
		this.parent_key_field = this.dd.key_field;
		this.instance_object_name = instance_object_name; // string containing the instance name of this class (per child)
	},
	// }}}

	// {{{ hook_update
	// this function is called whenever there is an update by the picker tool
	// 
	//		action
	//			if "clear", will clear the default_values array
	hook_update: function(action, data)
	{
		if (action == "clear")
		{
			this.default_values=[];
		}
		else
		{
			//console.log("eval string was: " + "data."+this.table_name);
			this.default_values = eval("data."+this.table_name);
		}
		this.render_area();
	},
	//}}}

	// this is the main render function... (displays the whole thing)
	// {{{ render_area
	render_area: function(nonPond)
	{
		var html = "";
		var val = "";
		if ( undefined != this.default_values && this.default_values.length > 0)
		{
			val = eval("this.default_values[0]."+this.parent_key_field);
		}
		else if ( nonPond != true )
		{
			str = "record["+this.dd.table_name+"]["+this.dd.view_name+"]["+this.dd.key_field+"]";

			if ($(str).value != "")
			{
				val = $(str).value;
			}
		}

		if (val != "")
		{
			html += "<input type='hidden' value='"+val+"' ";
			html += "name='record["+this.table_name+"]["+this.view_name+"]["+this.parent_key_field+"]'";
			html += " />";
		}

		// {{{ Section 1: display current values
		html += "<table class='tabular_data'><thead><tr>";
		// insert columns
		this.dd.fields.each(function(f) {
			html+= "<th>"+f.trans+"</th>";
		});
		html +="<th>&nbsp;</th>";
		html+="</tr></thead>";
		// }}}

		// {{{ BODY: loop through current values
		html+="<tbody id='pondchild_tbody_"+this.table_name+"' >";
		if ( undefined != this.default_values )
		{
			for(var i=0; i < this.default_values.length; i++)
			{
				s = this.default_values[i];
        if ( i > 0 ) {
          var prior_value = this.default_values[i-1];
        }
				html+="<tr>";

				val = eval("s."+this.table_name+"_id");

				var id_prfx = "pc_"+this.table_name+"_"+this.view_name;
				var id_field_html = "<input type='hidden' value='"+val+"' "
					+ "name='record["+this.table_name+"]["+this.view_name+"]["+i+"]["+this.table_name+"_id]'"
					+ " />";

				this.dd.fields.each(function(f) {
					html+= "<td>";
					html+= id_field_html;
					the_field_value = eval("s."+f.field_name);
          if ( i > 0 ) {
            if ( f.increment_values_field ) {
              prior_field_value = eval("prior_value."+f.increment_values_field);
            } else {
              prior_field_value = eval("prior_value."+f.field_name);
            }
          } else { prior_field_value = null; }

					if (f.dependent_list_yn == 'y')
					{
						// SC: assume relapse bit
						if (s.list_status_followup == 'relapse')
						{
							html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_dep' style='display:none;'>"+ Pond.Func.translate('n_a') +"</div>";
							html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_widget'>";
						}
						else
						{
							html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_dep'>"+ Pond.Func.translate('n_a') +"</div>";
							html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_widget' style='display:none;'>";
						}
					}

					if (f.type=="listpack")
					{
						html += this.get_select_box(f,i,the_field_value);
					}
					else if(f.type=="text")
					{
						html += this.get_text_box(f,i,the_field_value,prior_field_value);
					}
					else if(f.type=="date")
					{
						html += this.get_date_box(f,i,the_field_value);
					}

					if (f.dependent_list_yn == 'y')
					{
						html += "</div>";
					}

					html+= "</td>";

					id_field_html=""; // reset the id field so its not repeated...
            
				}.bind(this));

				html += "<th><a onclick='Element.remove(Element.up(this,1));return false;' href='#'><img border='0' src='"+http_root+"custom/images/icons/delete.gif' /></a></th>";

				html+="</tr>";
			}
		}
		html+="</tbody>";
		// }}}

		// {{{ footer show add form
		html+="<tfoot>";
		html+="<tr><td colspan='9'>";
		html += "<div class='boxed_link'><a onclick='return "+this.instance_object_name+".add_new_row();' href='#'><img border='0' src='"+http_root+"custom/images/icons/add.gif' /> "+Pond.Func.translate('picker_add_new')+"</a></div>";
		html += "</td>"; 
		html+="</tfoot>";
		html+="<table>";
		// }}}

		// Section : Display/Update everything
		//Insertion.Bottom(this.div_element, html);

		this.div_element.innerHTML = html;
 
	},
	// }}}
	
	// {{{ add_new_row
	add_new_row: function()
	{
		var html= "<tr>";

		if (undefined == this.default_values)
		{
			this.default_values = [];
		}

		var id_prfx = "pc_"+this.table_name+"_"+this.view_name;


		var i = this.default_values.length;
		this.dd.fields.each(function(f) {
			html+= "<td>";

			if (f.dependent_list_yn == 'y')
			{
				// SC: assume relapse bit
				html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_dep'>"+ Pond.Func.translate('n_a') +"</div>";
				html += "<div id='"+id_prfx+"_"+f.field_name+"_"+i+"_widget' style='display:none;'>";
			}

			if (f.type=="listpack")
			{
				html += this.get_select_box(f,i,null);
			}
			else if(f.type=="text")
			{
				html += this.get_text_box(f,i,null);
			}
			else if(f.type=="date")
			{
				html += this.get_date_box(f,i,null);
			}

			if (f.dependent_list_yn == 'y')
			{
				html += "</div>";
			}

			html+= "</td>"
		}.bind(this));

		this.default_values[i] = {};

		html += "<th><a onclick='Element.remove(Element.up(this,1));return false;' href='#'><img border='0' src='"+http_root+"custom/images/icons/delete.gif' /></a></th>";
		html += "</tr>";

		new Insertion.Bottom($('pondchild_tbody_'+this.table_name), html);
		return false;
	},
	// }}}

	// {{{ get_date_box
	get_date_box: function(f,num,default_value)
	{
		var html="";
		// text field
		html += "<input readonly='readonly' class='readonly' size='10' type='text'";
		html += "id='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"]'";
		html += "name='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"]'";
			
		if (default_value != null)
		{
			html+= ' value="'+default_value+'"';
		}
		else
		{
			html+=" value=''";
		}
		html += " />";

		html += "<img alt='Calendar' style='border: 0px none ; cursor: pointer;'";
		html += 'onclick="new CalendarDateSelect($(';
		html += "'record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"]'";
		html += '), {year_range:10});" src="'+http_root+'custom/images/icons/calendar.gif" />';

		return html;
	},
	// }}}

	// {{{ get_text_box
	get_text_box: function(f,num,default_value,prior_value)
	{

		var html="";
		// text field
		html += "<input class='small_text' type='text' maxlength='"+f.maxlen+"' size='"+f.size+"' ";
		html += "name='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"]'";
    html += "id='record-"+this.table_name+"-"+this.view_name+"-"+num+"-"+f.field_name+"'";
    if ( f.value != null )
    {
      var new_value = f.value;
      if ( f.increment_values_field && num > 0 ) {
        if ( prior_value != undefined && prior_value != null ) {
          new_value = prior_value;
        } else if ( document.getElementById("record-"+this.table_name+"-"+this.view_name+"-"+(num - 1)+"-"+f.increment_values_field) ) {
          new_value = document.getElementById("record-"+this.table_name+"-"+this.view_name+"-"+(num - 1)+"-"+f.increment_values_field).value;
        }
      }
      html += ' value="'+new_value+'"';
    }
    else if (default_value != null)
		{
			html+= ' value="'+default_value+'"';
		}
		else
		{
			html+=" value=''";
		}
  
    if ( f.disabled == true )
    {
      html+=' disabled="disabled"';
    }

    if (f.increment_values_lock && num > 0)
    {
      html += ' onchange="var previous_value = document.getElementById(\''+'record-'+this.table_name+'-'+this.view_name+'-'+(num - 1)+'-'+f.field_name+'\').value;if(this.value < previous_value){this.value=previous_value+1;}if(this.value== previous_value){this.value=(previous_value*1 + 1);}"'; 
    }

		html += " />";
		return html;
	},
	// }}}

	// {{{ select_onchange
	select_onchange: function(num, value)
	{
		var id_prfx = "pc_"+this.table_name+"_"+this.view_name;
		var dep1 = id_prfx+"_list_child_relapsesite_"+num+"_dep";
		var widget1 = id_prfx+"_list_child_relapsesite_"+num+"_widget";
		var dep2 = id_prfx+"_relapse_site_other_"+num+"_dep";
		var widget2 = id_prfx+"_relapse_site_other_"+num+"_widget";

		if (value == "relapse")
		{
			// show the widget,
			$(dep1).hide(); $(widget1).show();
			$(dep2).hide(); $(widget2).show();
		}
		else
		{
			$(dep1).show(); $(widget1).hide();
			$(dep2).show(); $(widget2).hide();
		}
	},
	// }}}

	// {{{ get_select_box
	get_select_box: function(f,num,default_value)
	{
		var html ="";

		if (f.lpmulti_list_yn == 'y')
		{
			html += '<input type="hidden" value="" ';
			html += "name='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"][]' />";
		}

		// select box
		html += "<select class='small_text'";
		if ( f.field_name == "list_status_followup" )
		{
			html+= ' onchange="patient_diagnosis_patient_diagnosis_status_ddjson_class.select_onchange('+num+',this.value)" ';
		}

		if ( f.lpmulti_list_yn == "y" )
		{
			html+= ' multiple="multiple" size="4" ';
			html += "name='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"][]'>";
		}
		else
		{
			html += "name='record["+this.table_name+"]["+this.view_name+"]["+num+"]["+f.field_name+"]'>";
		}

		// multi select boxes don't get the first blank as an option
		if ( f.lpmulti_list_yn != "y" )
		{
			html += "<option value=''></option>";
		}

		if (this.table_name == "patient_diagnosis_staging" && f.field_name =="list_classcode")
		{
			// {{{ SC/special case: staging area gets special filter
			if (undefined != pond_diag_obj && pond_diag_obj.list_disease_name != "" && undefined != Pond.disease_specific_classcodes[pond_diag_obj.list_disease_name])
			{
				var subarray = Pond.disease_specific_classcodes[pond_diag_obj.list_disease_name];

				Object.keys(f.listpack_values).each(function(v){
					if ( subarray.indexOf(v) != -1 )
					{
						html += "<option value='"+v+"'";
						if ( v == default_value )
						{
							html+= " selected='selected'";
						}
						html+=">"+f.listpack_values[v]+"</option>";
					}
				});
			}
			// }}}
		}
		else if (this.table_name == "patient_diagnosis_status" && f.field_name =="list_status_followup")
		{
			// {{{ SC/special case: diagnosis status gets special filter
			var leukemias_arr = ["all","aml","apl","leuk_other","cml","mds","mps"];
			if (undefined != pond_diag_obj && pond_diag_obj.list_disease_name != "")
			{
				var subarray;
				if (leukemias_arr.indexOf(pond_diag_obj.list_disease_name) == -1)
				{
					// NOT A LUEKEMIA
					subarray = Pond.non_leuk_followupstatus;
				}
				else
				{
					// IS A LEUKEMIA
					subarray = Pond.leuk_followupstatus;
				}

				Object.keys(f.listpack_values).each(function(v){
					if ( subarray.indexOf(v) != -1 )
					{
						html += "<option value='"+v+"'";
						if ( v == default_value )
						{
							html+= " selected='selected'";
						}
						html+=">"+f.listpack_values[v]+"</option>";
					}
				});
			}
			// }}}
		}
		else
		{
			if (f.lpmulti_list_yn == "y")
			{
				var val_ary = [];
				if (undefined != default_value)
				{
					val_ary = default_value.split('||');
				}
			}
			Object.keys(f.listpack_values).each( function(v){
				html += "<option value='"+v+"'";

				if (f.lpmulti_list_yn == "y" && val_ary.length > 0)
				{
					for(var ii=0;ii<val_ary.length;ii++)
					{
						if (val_ary[ii] == v)
						{
							html+= " selected='selected'"; break;
						}
					}
				}
				else
				{
					if ( v == default_value )
					{
						html+= " selected='selected'";
					}
				}

				html+=">"+f.listpack_values[v]+"</option>";
			});
		}

		html += "</select>";

		return html;
	}
	// }}}
});


// vim: set foldmethod=marker:
//
// This is the javascript library that allows the pond quickforms to load ajax
// data from the server and allow users to browse and pick patient records
// from the server.
// 
var Pond_Picker = Class.create();

Object.extend(Pond_Picker.prototype, {
	form_id: 'pond_qf_form', // constant

	// {{{ consturctor:
	initialize: function(table_name,view_name,patient_id,record_id,msg)
	{
		this.box = "pk"+table_name+view_name;
		this.record_id = record_id;

		this.table_name = table_name;
		this.view_name = view_name;
		this.patient_id = patient_id;
		this.edit_record_json = {};
		this.self_instance_name = '';
		this.dialog = false;
		this.confirm_dialog = false;
		this.review_text = msg;

		this.hook_fns = [];

		this.self_instance_name = "picker_obj_"+table_name+view_name;
		return false;
	},
	// }}}

	// {{{ confirm functions
	add_new_confirm: function()
	{
		// 0) Confirm with the user, because this action is destructive.
		this.confirm_clear('add_new()');
	},
	edit_record_confirm: function(id)
	{
		// 0) Confirm with the user, because this action is destructive.
		this.confirm_clear('edit_record('+id+')');
	},
	// }}}

	// {{{ add_hook
	add_hook: function(fn)
	{
		// add this function to the hook
		this.hook_fns[this.hook_fns.length] = fn;
	},
	// }}}

	// {{{ add_new
	add_new: function()
	{
		if (this.confirm_dialog != false)
		{
			this.confirm_dialog.close();
		}

		// 1) Clear all fields in this table/view
		this.clear_this_form();

		// 2) handle hooks
		this.hook_fns.each(function(f) {
			if ( f.indexOf("(") == -1 )
			{
				eval(f+"('clear');");
			}
			else
			{
				eval(f);
			}
		}.bind(this));

		var tobj = $(this.box+"status");
		if (!(tobj == null || tobj == this.box+"status"))
		{
			// this field exists...
			tobj.hide();
		}

		var tobj = $(this.box+"btns");
		if (!(tobj == null || tobj == this.box+"btns"))
		{
			// this field exists...
			tobj.hide();
			tobj.down().next().removeClassName('bttn_flagged');
		}
	},
	// }}}

	// {{{ edit_record()
	edit_record: function(id)
	{
		if (this.confirm_dialog != false)
		{
			this.confirm_dialog.close();
		}

		// 1) Clear all fields in this table/view
		this.clear_this_form();

		// 2) Load the values for "id"
		var url = http_root+"patient/ajax/picker.php?op=get_record&record_id="+id+"&t="+this.table_name+"&v="+this.view_name;

		// 3a) make sure you show the created/modified and buttons boxes
		obj = $(this.box+"status");
		if (!(obj == null || obj == this.box+"status"))
		{
			// this field exists...
			obj.show();
		}

		obj = $(this.box+"btns");
		if (!(obj == null || obj == this.box+"btns"))
		{
			// this field exists...
			obj.show();
		}
		this.record_id = id;

		new Ajax.Request(url,{
			asynchronous: false,
			method: 'get',
			onComplete: function(r) {
				this.edit_record_json = r.responseText.evalJSON(true);
			}.bind(this)
		});

		// now this.edit_record_json has the record value
		
		// 3) Transfer values loaded in to the form

		var flds = Object.keys(this.edit_record_json);

		flds.each(function(fld){
			id_name = "record["+this.table_name+"]["+this.view_name+"]["+fld+"]";
			obj = $(id_name);

			if (obj == null || obj == id_name)
			{
				// this field does not exists in this document
				// most likely the following fields will end up here:
			}
			else
			{
				if (typeof(this.edit_record_json[fld]) == 'string')
				{
					// field exists, transfer value
					//console.log('fld found: ' + fld + ' value was: ' + this.edit_record_json[fld]);
					obj.value = this.edit_record_json[fld];
				}
				else if (typeof(this.edit_record_json[fld]) == 'object')
				{
					if ( obj.type == 'select-multiple' )
					{
						var vals = this.edit_record_json[fld];

						vals.each(function(vals_one){

							// its a multi-select lets assing values
							for(var cnti=0; cnti<obj.options.length; cnti++)
							{
								if ( obj.options[cnti].value == vals_one )
								{
									obj.options[cnti].selected = true;
								}
							}
						}.bind(this));
					}
					//console.log(fld + ': type:' + obj.type + ' obj.options: ' + obj.options );
				}
				else
				{
					//console.log(fld + ': skipped because type is not supported ' + typeof(this.edit_record_json[fld]));
				}
				//console.log("onchange for: " + obj.id + " was: " + obj.onchange);
				if ( obj.onchange != undefined )
				{
					obj.onchange();
				}
			}
		}.bind(this));

		// {{{ update created/modified by boxes
		var dt = Date.parseFormattedString(this.edit_record_json["add_datetime"]);

		$(this.box+"add").innerHTML = "<a href='#' class='infolink' onclick=\"popup_window('"
			+ docu_root
			+ "custom/tpl/info_popups/user.php?user="
			+ this.edit_record_json["add_username"]
			+ "',632,426,'user_info_window'); return false;\">"
			+ this.edit_record_json["add_username"]
			+ "</a> ("
			+ dt.toPondFormattedString(true)
			+ ")";

		dt = Date.parseFormattedString(this.edit_record_json["chg_datetime"]);
		var dt_val = "";
		if (!isNaN(dt))
		{
			dt_val = dt.toPondFormattedString(true)
		}

		$(this.box+"chg").innerHTML = "<a href='#' class='infolink' onclick=\"popup_window('"
			+ docu_root
			+ "custom/tpl/info_popups/user.php?user="
			+ this.edit_record_json["chg_username"]
			+ "',632,426,'user_info_window'); return false;\">"
			+ this.edit_record_json["chg_username"]
			+ "</a> ("
			+ dt_val
			+ ")";
		// }}}

		this.update_review(this.edit_record_json["form_control_review"]);

		this.hook_fns.each(function(f){
			if ( f.indexOf("(") == -1 )
			{
				eval(f+"('update',this.edit_record_json);");
			}
			else
			{
				eval(f);
			}
		}.bind(this));

		// 4) Handle complex pieces.
		return;
	},
	// }}}

	// {{{ clear_this_form
	// actually clears the form
	clear_this_form: function()
	{
		var all_elements = Form.getElements($(this.form_id));
		var compare_with = "record["+this.table_name+"]["+this.view_name+"]";
		this.record_id = 0;

		all_elements.each(function(ele) {
			if (ele.name.startsWith(compare_with))
			{
				if (ele.type == 'select-multiple' )
				{
					ele.clear();

					//it seems that clear() is not very well implemented for select-multiple type
					// so we do our own clearing()
					for (var cnti=0; cnti<ele.options.length;cnti++)
					{
						ele.options[cnti].selected = false;
					}
				}
				else
				{
					ele.clear();
				}
			}
		});

		// todo, special processing to clear out values for child piece / complex pieces
		//this.hook_fns.each(function(f){ f('clear',null); });
	},
	// }}}

	// {{{ confirm_clear
	// presents a dialog with YES/NO, about clearing...
	confirm_clear: function(callback_func_string)
	{
		if (this.dialog != false)
		{
			this.dialog.close();
		}

		this.confirm_dialog = new Control.Modal(false, {
			height: 120,
			width: 290,
			containerClassName: 'pickerContainer',
			position: 'absolute',
			opacity: 0.7,
			contents: "<div class='pickerDialog'>"+
			"This will clear values currently in the form.<br /><br />Continue?<br/><br/>"+
			"<div class='boxed_link' style='float:left;font-weight:bold;margin: 0 10px;'>"+
			"<a href='#' onclick='"+this.self_instance_name+"."+callback_func_string+";return false;'>Yes - Clear Values</a></div>"+
			"<div class='boxed_link'><a href='#' onclick='"+this.self_instance_name+".confirm_dialog.close();return false;'>Cancel</a></div>"+
			"</div>"
		});
		this.confirm_dialog.open();
	},
	// }}}

	// {{{ picker_menu
	picker_menu: function(anchor_obj)
	{
		this.anchor_obj = anchor_obj;
		// Show a menu first...
		var url = http_root+"patient/ajax/picker.php?op=picker&patient_id="+this.patient_id+"&t="+this.table_name+"&v="+this.view_name;

		this.dialog = new Control.Modal(this.anchor_obj, {
			height: 250,
			containerClassName: 'pickerContainer',
			width: 180,
			offsetLeft: 20,
			offsetTop: 20,
			position: 'relative',
			contents: function() {
				new Ajax.Request(url,{
					method: 'get',
					asynchronous: false,
					onComplete: function(r){
						contents_var = r.responseText;
					}
				});
				return contents_var;
			}
		});
		this.dialog.open();
		return false;
	},
	// }}}

	// {{{ update_review
	update_review: function(msg)
	{
		var tobj = $(this.box+"btns");
		if (!(tobj == null || tobj == this.box+"btns"))
		{
			// this field exists...
			var bx = tobj.down().next();

			// mark as reviewed...
			if ( msg == "" )
			{
				bx.removeClassName('bttn_flagged');
			}
			else
			{
				// add only if not already present
				if ( !bx.hasClassName('bttn_flagged') )
				{
					bx.addClassName('bttn_flagged');
				}
			}
		}

		this.review_text = msg;
	},
	// }}}

	// {{{ mark_void
	mark_void: function(anchor_obj)
	{
		if(this.record_id > 0 && confirm(Pond.Func.translate("form_control_confirm_delete_form")))
		{
			var url = http_root+"patient/ajax/picker.php?op=void&record_id="+this.record_id+"&t="+this.table_name;
			// actually delete:
			new Ajax.Request(url,{
				evalJSON: true,
				asynchronous: false,
				onSuccess: function(r){
					//process the response here
				}
			});

			// special handling when voiding a patient:
			if ( this.table_name == "patient" )
			{
				// redirect them back to records page
				window.location.href= docu_root+"patient/";
			}

			this.add_new(); // simulate adding a new record (because we just deleted current record!);
		}
	},
	// }}}

	// {{{ mark_review
	mark_review: function(anchor_obj)
	{
		if(this.record_id)
		{
			var msg = prompt(Pond.Func.translate("form_control_comments"),this.review_text);
			if (msg != null)
			{
				var url = http_root+"patient/ajax/picker.php?op=review&record_id="+this.record_id+"&t="+this.table_name+"&patient_id="+this.patient_id;

				// actually delete:
				new Ajax.Request(url,{
					evalJSON: true,
					parameters: { 'msg': msg },
					asynchronous: false,
					onSuccess: function(r){
						//process the response here
					}
				});

				this.update_review(msg);
			}
		}
	}
	// }}}
	

});


// vim: set foldmethod=marker:
//

if(typeof(Pond) == "undefined") Pond = {};

// {{{ Pond.Func
Pond.Func = Class.create();
Object.extend(Pond.Func,{
	translate: function(key)
	{
		return Pond_Lang[key];
	},
	translate_listkey: function(lpack,key)
	{
		return Pond.Func.translate("list_"+lpack+"."+key);
	},
	sanitize_json_key: function(key)
	{
		return key.gsub(/[-]/, '_');
	},

	parse_field_name: function(fname)
	{
		var parts = [];
		fname.scan(/\w+/, function(s) { if (s!="record") parts.push(s[0])} );
		return parts;
	}
});
// }}}

// {{{ Pond.Tox class
Pond.Tox = Class.create();
Object.extend(Pond.Tox,{
	// {{{ category_changed
	category_changed: function(obj)
	{
		// a category has just been selected, lets lookup any events that need to be filled:
		var events_obj = $("record[patient_toxicity][default][list_ctcae_event]");
		var old_events_value = events_obj.value;
		
		// clear the events options
		var i=0; var sel=false;
		events_obj.options.length = 0;

		var data = [];
		if ( obj.value != "")
		{
			data = Pond.CTCAE_cat_events[obj.value];
			// create event options:
			events_obj.options[i++] = new Option('', '', true);
			if (old_events_value == "x") {sel=true;} else {sel=false;}
			events_obj.options[i++] = new Option('No data', 'x',sel);
			for(var j=0; j<data.length; j++ )
			{
				if (old_events_value == data[j]) {sel=true;} else {sel=false;}
				events_obj.options[i++] = new Option(Pond.Func.translate_listkey('ctcae_event',data[j]), data[j],sel);
			}
		}
		else
		{
			// someone selected blank (tell them to select a category
			events_obj.options[i++] = new Option('Please select category:', '');
		}

		// call the change function for the events pulldown
		Pond.Tox.events_changed(events_obj)
		return;
	},
	// }}}

	// {{{ events_changed
	events_changed: function(obj)
	{
		// a event was selected (or updated)
		var supra_obj = $("record[patient_toxicity][default][list_ctcae_supra]");
		var old_supra_value = supra_obj.value;
		
		// clear the events options
		var i=0;
		supra_obj.options.length = 0;
		supra_obj.innerHTML= ""; // clear out any optgroups defined as well.

		if ( obj.value != "" )
		{
			data = Pond.CTCAE_event_supra[obj.value];
			var optgroups = Object.keys(data);
			if ( optgroups.length > 0 )
			{
				supra_obj.options[i++] = new Option('', '', true);
				// there are supra's so lets create the option groups and option tags:
				for(var j=0; j< optgroups.length; j++)
				{
					// create the optgroup
					var oGroup = document.createElement('optgroup');
					oGroup.label = (optgroups[j] == "") ? "------" : Pond.Func.translate_listkey('ctcae_supra_cat',optgroups[j]);

					// now create the options
					var opts = data[optgroups[j]];
					for(var k=0;k< opts.length;k++)
					{
						var oOption = document.createElement('option');
						oOption.value = opts[k];
						if ( old_supra_value == opts[k])
						{
							oOption.selected = true;
						}
						oOption.innerHTML = Pond.Func.translate_listkey('ctcae_supra',opts[k]);
						oGroup.appendChild(oOption);
					}
					supra_obj.appendChild(oGroup);
				}
			}
			else
			{
				supra_obj.options[i++] = new Option("No adverse event details defined","");
			}
		}
		else
		{
			// what to do when a blank option has been selected
			supra_obj.options[i++] = new Option("Please select adverse event","");
		}

		if (obj.value == 'synd-retinoic_acid')
		{
			// show the fields
			$('div_toxicity_spec_fields').show();
			// hide the no spec fields message
			$('no_toxicity_spec_fields_msg').hide();
		}
		else
		{
			// hide the fields and show a message about no specific fields for this toxicity
			$('div_toxicity_spec_fields').hide();
			$('no_toxicity_spec_fields_msg').show();
		}

		Pond.Tox.supra_changed(supra_obj);
	},
	// }}}

	// {{{ supra_changed
	supra_changed: function(obj)
	{
		// don't do anything right now
		// a event was selected (or updated)
		//var supra_obj = $("record[patient_toxicity][default][list_ctcae_supra]");
	}
	// }}}
});
// }}}


if(typeof(Pond) == "undefined") Pond = {};
Pond.CTCAE_cat_events = {"allergy_immuno":["allergy_immuno-hypersense","allergy_immuno-rhinitis","allergy_immuno-autoimmune","allergy_immuno-serum_sick","allergy_immuno-vasculitis","allergy_immuno-other"],"aud_ear":["aud_ear-hear_monitor","aud_ear-hear_no_monitor","aud_ear-otitis_ext","aud_ear-otitis_mid","aud_ear-tinnitus","aud_ear-other"],"blood_bone":["blood_bone-bone_marrow_cell","blood_bone-cd4","blood_bone-haptoglobin","blood_bone-hemoglobin","blood_bone-hemolysis","blood_bone-iron_overload","blood_bone-leukocytes","blood_bone-lymphopenia","blood_bone-myelodysplasia","blood_bone-neutrophils","blood_bone-platelets","blood_bone-splenic_func","blood_bone-other"],"card_arrhy":["card_arrhy-conduct_abnorm","card_arrhy-palpitations","card_arrhy-prolong_qtc_int","card_arrhy-supravent_arrhythmia","card_arrhy-vasovagal_epi","card_arrhy-ventric_arrhythmia","card_arrhy-other"],"card_gen":["card_gen-ischem_infarc","card_gen-troponin_I","card_gen-troponin_T","card_gen-arrest_unknown","card_gen-hypertension","card_gen-hypotension","card_gen-left_ventri_diastolic","card_gen-left_ventri_systolic","card_gen-myocarditis","card_gen-pericard_effusion","card_gen-pericarditis","card_gen-pulm_hypertension","card_gen-restr_cardiomyopathy","card_gen-right_ventri","card_gen-valvular_heart_dis","card_gen-other"],"coag":["coag-DIC","coag-fibrinogen","coag-INR_prothrombin","coag-PTT","coag-thromb_microangi","coag-other"],"const":["const-fatigue","const-fever","const-hypothermia","const-insomnia","const-obesity","const-odor","const-rigors_or_chills","const-sweating","const-weight_gain","const-weight_loss","const-other"],"death":["death-death"],"derma_skin":["derma_skin-atrophy_skin","derma_skin-atrophy_fat","derma_skin-bruising","derma_skin-burn","derma_skin-cheilitis","derma_skin-dry_skin","derma_skin-flushing","derma_skin-hair_loss","derma_skin-hyperpigmentation","derma_skin-hypopigmentation","derma_skin-induration_fibrosis","derma_skin-inject_site_react","derma_skin-nail_changes","derma_skin-photosensitivity","derma_skin-pruritus","derma_skin-acne","derma_skin-rash_dermatitis","derma_skin-rash_erythema","derma_skin-rash_hand_foot_react","derma_skin-decubitus","derma_skin-striae","derma_skin-telangiectasia","derma_skin-ulceration","derma_skin-urticaria","derma_skin-wound_comp_non_inf","derma_skin-other"],"endo":["endo-adren_insuff","endo-cushingoid_appear","endo-feminine_of_male","endo-hot_flashes","endo-masculine_of_female","endo-neuro_ACTH_defic","endo-neuro_ADH_abnorm","endo-neuro_gonado_abnorm","endo-neuro_growth_horm_abnorm","endo-neuro_prolac_horm_abnorm","endo-diabetes","endo-hypoparathyroid","endo-hyperthyroidism","endo-hypothyroidism","endo-other"],"gastro":["gastro-anorexia","gastro-ascites","gastro-colitis","gastro-constipation","gastro-dehydration","gastro-dentures","gastro-periodontal","gastro-teeth","gastro-diarrhea","gastro-distension","gastro-dry_mouth","gastro-dysphagia","gastro-enteritis","gastro-esophagitis","gastro-fistula","gastro-flatulence","gastro-gastritis","gastro-heartburn","gastro-hemorrhoids","gastro-ileus","gastro-incontinence_anal","gastro-leak","gastro-malabsorption","gastro-mucositis_clinic","gastro-mucositis_func","gastro-nausea","gastro-necrosis","gastro-obstruction","gastro-perforation","gastro-proctitis","gastro-prolapse_stoma","gastro-salivary_gland","gastro-stricture","gastro-taste_alter","gastro-typhlitis","gastro-ulcer","gastro-vomiting","gastro-other"],"growth_devel":["growth_devel-bone_age","growth_devel-bone_femor_head","growth_devel-bone_limb_length","growth_devel-bone_spine_kyph","growth_devel-growth_velo","growth_devel-puberty_delayed","growth_devel-puberty_precocious","growth_devel-short_stature","growth_devel-other"],"hemor_bleed":["hemor_bleed-hematoma","hemor_bleed-hemorr_w_surgery","hemor_bleed-hemorr_CNS","hemor_bleed-hemorr_GI","hemor_bleed-hemorr_GU","hemor_bleed-hemorr_pulm_resp","hemor_bleed-petechiae","hemor_bleed-other"],"hepat_panc":["hepat_panc-cholecystitis","hepat_panc-liver_dysfunc","hepat_panc-panc_exocrine_defic","hepat_panc-pancreatitis","hepat_panc-other"],"infec":["infec-colitis_infect","infec-febrile_neutropenia","infec-infect_clinic","infec-infect_w_norm_ANC","infec-infect_w_unkn_ANC","infec-lymphopenia_infect","infec-viral_hepatitis","infec-other"],"lymph":["lymph-chyle_lymph_leak","lymph-dermal_change","lymph-edema_head_neck","lymph-edema_limb","lymph-edema_trunk_genital","lymph-edema_viscera","lymph-lymphedema_rel_fibrosis","lymph-lymphocele","lymph-phlebolymph_cord","lymph-other"],"metab_lab":["metab_lab-acidosis","metab_lab-hypoalbuminemia","metab_lab-alkaline_phosphatase","metab_lab-alkalosis","metab_lab-ALT_SGPT","metab_lab-amylase","metab_lab-AST_SGOT","metab_lab-bicarbonate","metab_lab-bilirubin","metab_lab-hypocalcemia","metab_lab-hypercalcemia","metab_lab-cholesterol","metab_lab-CPK","metab_lab-creatinine","metab_lab-GCT","metab_lab-GFR","metab_lab-hyperglycemia","metab_lab-hypoglycemia","metab_lab-hemoglobinuria","metab_lab-lipase","metab_lab-hypermagnesemia","metab_lab-hypomagnesemia","metab_lab-hypophosphatemia","metab_lab-hyperkalemia","metab_lab-hypokalemia","metab_lab-proteinuria","metab_lab-hypernatremia","metab_lab-hyponatremia","metab_lab-hypertriglyceridemia","metab_lab-hyperuricemia","metab_lab-other"],"muscul_tissue":["muscul_tissue-arthritis","muscul_tissue-bone_scoliosis","muscul_tissue-cervic_spine_ROM","muscul_tissue-exostosis","muscul_tissue-extrem_gait","muscul_tissue-extrem_up_func","muscul_tissue-fibrosis_cosmesis","muscul_tissue-fibrosis_deep","muscul_tissue-fracture","muscul_tissue-joint_effus","muscul_tissue-joint_func","muscul_tissue-prosthesis","muscul_tissue-lumbar_spine_ROM","muscul_tissue-muscle_weak","muscul_tissue-hypoplasia","muscul_tissue-myositis","muscul_tissue-osteonecrosis","muscul_tissue-osteoporosis","muscul_tissue-seroma","muscul_tissue-soft_necrosis","muscul_tissue-trismus","muscul_tissue-other"],"neuro":["neuro-apnea","neuro-arachnoiditis","neuro-ataxia","neuro-brach_plexopathy","neuro-CNS_ischemia","neuro-CNS_necrosis","neuro-cognitive_dist","neuro-confusion","neuro-dizziness","neuro-encephalopathy","neuro-invol_movement","neuro-hydrocephalus","neuro-irritability","neuro-laryngeal_nerve","neuro-CSF_leak","neuro-leukoencephalopathy","neuro-memory_impair","neuro-mental_status","neuro-mood_alter","neuro-myelitis","neuro-neuro_cranial","neuro-neuro_motor","neuro-neuro_sensory","neuro-personality","neuro-phrenic_nerve","neuro-psychosis","neuro-pyramidal_tract","neuro-seizure","neuro-somnolence","neuro-speech_impair","neuro-syncope_faint","neuro-tremor","neuro-other"],"ocu_vis":["ocu_vis-cataract","ocu_vis-dry_eye","ocu_vis-eyelid_dysfunc","ocu_vis-glaucoma","ocu_vis-keratitis","ocu_vis-nyctalopia","ocu_vis-nystagmus","ocu_vis-ocular_surf_dis","ocu_vis-diplopia","ocu_vis-optic_disc_edema","ocu_vis-proptosis_enophthalmos","ocu_vis-retinal_detach","ocu_vis-retinopathy","ocu_vis-scleral_necrosis","ocu_vis-uveitis","ocu_vis-blurred_vision","ocu_vis-flashing_lights","ocu_vis-photophobia","ocu_vis-vitreous_hemorr","ocu_vis-watery_eye","ocu_vis-other"],"pain":["pain-pain","pain-other"],"pulm_resp":["pulm_resp-ARDS","pulm_resp-aspiration","pulm_resp-atelectasis","pulm_resp-bronchospasm","pulm_resp-carb_monox_diff_cap","pulm_resp-chylothorax","pulm_resp-cough","pulm_resp-dyspnea","pulm_resp-edema_larynx","pulm_resp-fev1","pulm_resp-fistula_pulm","pulm_resp-hiccoughs","pulm_resp-hypoxia","pulm_resp-nasal_paranasal_react","pulm_resp-obstruct_airway","pulm_resp-pleural_effusion","pulm_resp-pneumonitis","pulm_resp-pneumothorax","pulm_resp-chest_tube_drain_leak","pulm_resp-prolong_intubation","pulm_resp-pulm_fibrosis","pulm_resp-vital_capacity","pulm_resp-voice_change","pulm_resp-other"],"renal_genit":["renal_genit-bladder_spasm","renal_genit-cystitis","renal_genit-fistula","renal_genit-incontin_urine","renal_genit-leak","renal_genit-obstruct","renal_genit-perforation","renal_genit-prolapse_stoma","renal_genit-renal_fail","renal_genit-stricture_anastomo","renal_genit-urinary_elect_waste","renal_genit-urinary_freq","renal_genit-urinary_retent","renal_genit-urine_color_chg","renal_genit-other"],"sec_malig":["sec_malig-poss_rel"],"sex_repro":["sex_repro-breast_func","sex_repro-nipple_areolar_deform","sex_repro-breast_vol","sex_repro-erect_dysfunc","sex_repro-ejac_dysfunc","sex_repro-gynecomastia","sex_repro-infert_sterile","sex_repro-irreg_menses","sex_repro-libido","sex_repro-orgas_dysfunc","sex_repro-vaginal_discharge","sex_repro-vaginal_dry","sex_repro-vaginal_mucositis","sex_repro-vaginal_stenosis","sex_repro-vaginitis","sex_repro-other"],"surg_injury":["surg_injury-intraop_inj","surg_injury-other"],"synd":["synd-alcohol_intol","synd-cytokine_release","synd-flu_like","synd-retinoic_acid","synd-tumor_flare","synd-tumor_lysis","synd-other"],"vasc":["vasc-acute_vasc_leak","vasc-periph_arter_ischemia","vasc-phlebitis","vasc-portal_flow","vasc-thrombosis_emb_vascular","vasc-thrombosis_thrombus_emb","vasc-vess_inj_artery","vasc-vess_inj_vein","vasc-visc_artery_ischemia","vasc-other"],"transreact":["transreact-febrile","transreact-allergic","transreact-inflammatory","transreact-mixed_allergic_inflam","transreact-trali","transreact-hypotension","transreact-hemolysis","transreact-sepsis","transreact-circulatory_overload"]};
Pond.CTCAE_event_supra = {"card_arrhy-conduct_abnorm":{"":["asystole","av_block_first","av_block_second_type_I","av_block_second_type_II","av_block_complete","conduct_abnorm_nos","sick_sinus","stokes_adams","wolff_park_white"]},"card_arrhy-supravent_arrhythmia":{"":["atrial_fibril","atrial_flut","atrial_tachyc","nodal_junc","sinus_arrhythm","sinus_brady","sinus_tachyc","supravent_arrhythm_nos","supravent_extrasys","supravent_tachyc"]},"card_arrhy-ventric_arrhythmia":{"":["bigeminy","idioventri_rhythm","pvcs","torsade_pointes","trigeminy","vent_arrhythm_nos","vent_fibiril","vent_flutter","vent_tachyc"]},"death-death":{"":["death_nos","disease_prog_nos","multiorgan_fail","sudden_death"]},"derma_skin-rash_dermatitis":{"":["chemoradiation","radiation"]},"gastro-fistula":{"":["abdomen_nos","anus","bilitree","colon_cecum_appendix","duodenum","esophagus","gallbladder","ileum","jejunum","oral_cavity","pancreas","pharynx","rectum","salivary_gland","small_bowel_nos","stomach"]},"gastro-leak":{"":["bilitree","esophagus","large_bowel","leak_nos","pancreas","pharynx","rectum","small_bowel","stoma","stomach"]},"gastro-mucositis_clinic":{"":["anus","esophagus","large_bowel","larynx","oral_cavity","pharynx","rectum","small_bowel","stomach","trachea"]},"gastro-mucositis_func":{"":["anus","esophagus","large_bowel","larynx","oral_cavity","pharynx","rectum","small_bowel","stomach","trachea"]},"gastro-necrosis":{"":["anus","colon_cecum_appendix","duodenum","esophagus","gallbladder","hepatic","ileum","jejunum","oral","pancreas","peritoneal_cavity","pharynx","rectum","small_bowel_nos","stoma","stomach"]},"gastro-obstruction":{"":["cecum","colon","duodenum","esophagus","gallbladder","ileum","jejunum","rectum","small_bowel_nos","stoma","stomach"]},"gastro-perforation":{"":["appendix","bilitree","cecum","colon","duodenum","esophagus","gallbladder","ileum","jejunum","rectum","small_bowel_nos","stomach"]},"gastro-stricture":{"":["anus","bilitree","cecum","colon","duodenum","esophagus","ileum","jejunum","pancreas_duct","pharynx","rectum","small_bowel_nos","stoma","stomach"]},"gastro-ulcer":{"":["anus","cecum","colon","duodenum","esophagus","ileum","jejunum","rectum","small_bowel_nos","stoma","stomach"]},"hemor_bleed-hemorr_GI":{"":["abdomen_nos","anus","bilitree","cecum_appendix","colon","duodenum","esophagus","ileum","jejunum","liver","lower_GI_nos","oral_cavity","pancreas","peritoneal_cavity","rectum","stoma","stomach","upper_GI_nos","varices_esophag","varices_rectal"]},"hemor_bleed-hemorr_GU":{"":["bladder","fallopian_tube","kidney","ovary","prostate","retroperitoneum","spermatic_cord","stoma","testes","ureter","urethra","urinary_nos","uterus","vagina","vas_deferens"]},"hemor_bleed-hemorr_pulm_resp":{"":["bronchopulmn_nos","bronchus","larynx","lung","mediastinum","nose","pharynx","pleura","respir_tract_nos","stoma","trachea"]},"infec-infect_clinic":{"aud_ear":["external_ear_otitis","middle_ear_otitis"],"card":["artery","heart_endocard","spleen","vein"],"derm_skin":["lip_perioral","peristomal","cellulitis","ungual_nails"],"gastro":["abdomen_nos","anal_perianal","appendix","cecum","colon","dental_tooth","duodenum","esophagus","ileum","jejunum","oral_cav_gingivitis","peritoneal_cavity","rectum","salivary_gland","small_bowel_nos","stomach"],"general":["blood","cathether_rel","foreign_body","wound"],"hepa_panc":["bilitree","gallbladder_cholecyst","liver","pancreas"],"lymph":["lymphatic"],"muscskel":["bone_osteomyel","joint","muscle_myositis","soft_tissue_nos"],"neuro":["brain_encep_infec","brain_spinal_encephal","meninges_meningitis","nerve_cranial","nerve_peripheral","spinal_cord_myelitis"],"ocular":["conjunctiva","cornea","eye_nos","lens"],"pulm_uresp":["bronchus","larynx","lung_pneumonia","mediastinum_nos","mucosa","neck_nos","nose","paranasal","pharynx","pleura_empyema","sinus","trachea","upper_aerodigest_nos","upper_airway_nos"],"renal_geni":["bladder_urine","kidney","prostate","ureter","urethra","urinary_tract_nos"],"sex_repro":["cervix","fallopian_tube","pelvis_nos","penis","scrotum","uterus","vagina","vulva"]},"infec-infect_w_norm_ANC":{"aud_ear":["external_ear_otitis","middle_ear_otitis"],"card":["artery","heart_endocard","spleen","vein"],"derm_skin":["lip_perioral","peristomal","cellulitis","ungual_nails"],"gastro":["abdomen_nos","anal_perianal","appendix","cecum","colon","dental_tooth","duodenum","esophagus","ileum","jejunum","oral_cav_gingivitis","peritoneal_cavity","rectum","salivary_gland","small_bowel_nos","stomach"],"general":["blood","cathether_rel","foreign_body","wound"],"hepa_panc":["bilitree","gallbladder_cholecyst","liver","pancreas"],"lymph":["lymphatic"],"muscskel":["bone_osteomyel","joint","muscle_myositis","soft_tissue_nos"],"neuro":["brain_encep_infec","brain_spinal_encephal","meninges_meningitis","nerve_cranial","nerve_peripheral","spinal_cord_myelitis"],"ocular":["conjunctiva","cornea","eye_nos","lens"],"pulm_uresp":["bronchus","larynx","lung_pneumonia","mediastinum_nos","mucosa","neck_nos","nose","paranasal","pharynx","pleura_empyema","sinus","trachea","upper_aerodigest_nos","upper_airway_nos"],"renal_geni":["bladder_urine","kidney","prostate","ureter","urethra","urinary_tract_nos"],"sex_repro":["cervix","fallopian_tube","pelvis_nos","penis","scrotum","uterus","vagina","vulva"]},"infec-infect_w_unkn_ANC":{"aud_ear":["external_ear_otitis","middle_ear_otitis"],"card":["artery","heart_endocard","spleen","vein"],"derm_skin":["lip_perioral","peristomal","cellulitis","ungual_nails"],"gastro":["abdomen_nos","anal_perianal","appendix","cecum","colon","dental_tooth","duodenum","esophagus","ileum","jejunum","oral_cav_gingivitis","peritoneal_cavity","rectum","salivary_gland","small_bowel_nos","stomach"],"general":["blood","cathether_rel","foreign_body","wound"],"hepa_panc":["bilitree","gallbladder_cholecyst","liver","pancreas"],"lymph":["lymphatic"],"muscskel":["bone_osteomyel","joint","muscle_myositis","soft_tissue_nos"],"neuro":["brain_encep_infec","brain_spinal_encephal","meninges_meningitis","nerve_cranial","nerve_peripheral","spinal_cord_myelitis"],"ocular":["conjunctiva","cornea","eye_nos","lens"],"pulm_uresp":["bronchus","larynx","lung_pneumonia","mediastinum_nos","mucosa","neck_nos","nose","paranasal","pharynx","pleura_empyema","sinus","trachea","upper_aerodigest_nos","upper_airway_nos"],"renal_geni":["bladder_urine","kidney","prostate","ureter","urethra","urinary_tract_nos"],"sex_repro":["cervix","fallopian_tube","pelvis_nos","penis","scrotum","uterus","vagina","vulva"]},"muscul_tissue-muscle_weak":{"":["extraocular","extremity_lower","extremity_upper","facial","left_sided","ocular","pelvis","right_sided","trunk","whole_body_general"]},"muscul_tissue-soft_necrosis":{"":["abdomen","extremity_lower","extremity_upper","head","neck","pelvic","thorax"]},"neuro-mood_alter":{"":["agitation","anxiety","depression","euphoria"]},"neuro-neuro_cranial":{"":["cn_i_smell","cn_ii_vision","cn_iii_pupil","cn_iv_down_eye","cn_v_mot_musc_face","cn_vi_lateral_eye","cn_vii_mot_face_taste","cn_viii_hear_balance","cn_ix_mot_pharynx_ear_tongue","cn_x_mot_palate_pharynx_larynx","cn_xi_mot_sternomast_trapez","cn_xii_tongue"]},"pain-pain":{"aud_ear":["external_ear","middle_ear"],"card":["cardiac_heart","pericardium"],"derm_skin":["face","lip","oral_gums","scalp","skin"],"gastro":["abdomen_nos","anus","dental_teeth_periodon","esophagus","oral_cavity","peritoneum","rectum","stomach"],"general":["pain_nos","tumor_pain"],"hepa_panc":["gallbladder","liver"],"lymph":["lymph_node"],"muscskel":["back","bone","buttock","extremity_limb","intestine","joint","muscle","neck","phantom_limb_pain"],"neuro":["head_headache","neuralgia_periph_nerve"],"ocular":["eye"],"pulm_uresp":["chest_wall","chest_thorax_nos","larynx","pleura","sinus","throat_pharynx_larynx"],"renal_geni":["bladder","kidney"],"sex_repro":["breast","ovulatory","pelvis","penis","perineum","prostate","scrotum","testicle","urethra","uterus","vagina"]},"pulm_resp-fistula_pulm":{"":["bronchus","larynx","lung","oral_cavity","pharynx","pleura","trachea"]},"pulm_resp-obstruct_airway":{"":["bronchus","larynx","pharynx","trachea"]},"renal_genit-fistula":{"":["bladder","genital_tract_female","kidney","ureter","urethra","uterus","vagina"]},"renal_genit-leak":{"":["bladder","fallopian_tube","kidney","spermatic_cord","stoma","ureter","urethra","uterus","vagina","vas_deferens"]},"renal_genit-obstruct":{"":["bladder","fallopian_tube","prostate","spermatic_cord","stoma","testes","ureter","urethra","uterus","vagina","vas_deferens"]},"renal_genit-perforation":{"":["bladder","fallopian_tube","kidney","ovary","prostate","spermatic_cord","stoma","testes","ureter","urethra","uterus","vagina","vas_deferens"]},"renal_genit-stricture_anastomo":{"":["bladder","fallopian_tube","prostate","spermatic_cord","stoma","testes","ureter","urethra","uterus","vagina","vas_deferens"]},"surg_injury-intraop_inj":{"aud_ear":["inner_ear","middle_ear","outer_ear_nos","outer_ear_pinna"],"card":["artery_aorta","artery_carotid","artery_cerebral","artery_extrem_lower","artery_extrem_upper","artery_hepatic","artery_major_visceral","artery_pulmonary","artery_nos","heart","spleen","vein_extrem_lower","vein_extrem_upper","vein_hepatic","vein_inferior","vein_jugular","vein_major_visc","vein_portal","vein_pulmon","vein_super_vena_cava","vein_nos"],"derm_skin":["breast","nails","skin"],"endocrine":["adrenal_gland","parathyroid","pituitary","thyroid"],"head_neck":["gingiva","larynx","lip_perioral","face_nos","nasal_cavity","nasopharynx","neck_nos","nose","oral_cavity_nos","parotid_gland","pharynx","salivary_duct","salivary_gland","sinus","teeth","tongue","upper_aerodigest_nos"],"gastro":["abdomen_nos","anal_sphincter","anus","appendix","cecum","colon","duodenum","esophagus","ileum","jejunum","oral","peritoneal_cavity","rectum","small_bowel_nos","stoma_GI","stomach"],"hepa_panc":["bilitree_common_bile_duct","bilitree_common_hepat_duct","bilitree_left_hepat_duct","bilitree_right_hepat_duct","bilitree_nos","gallbladder","liver","pancreas","pancreatic_duct"],"muscskel":["bone","cartilage","extremity_lower","extremity_upper","joint","ligament","muscle","soft_tissue_nos","tendon"],"neuro":["brain","meninges","spinal_cord","brachial_plexus","nerv-cn_i_olfact","nerv-cn_ii_optic","nerv-cn_iii_oculo","nerv-cn_iv_troch","nerv-cn_v_trige_motor","nerv-cn_v_trige_sensor","nerv-cn_vi_abducen","nerv-cn_vii_facial_motor","nerv-cn_vii_facial_sensor","nerv-cn_viii_vestibulococh","nerv-cn_ix_motor_pharynx","nerv-cn_ix_sensor_ear_tongue","nerv-cn_x_vagus","nerv-cn_xi_spinal","nerv-cn_xii_hypogloss","nerv-cranial_branch_nos","nerv-lingual","nerv-lung_thoracic","nerv-periph_motor_nos","nerv-periph_sensor_nos","recurrent_laryngeal","sacral_plexus","sciatic","thoracodorsal"],"ocular":["conjunctiva","cornea","eye_nos","lens","retina"],"pulm_uresp":["bronchus","lung","mediastinum","pleura","thoracic_duct","trachea","upper_airway_nos"],"renal_geni":["bladder","cervix","fallopian_tube","kidney","ovary","pelvis_nos","penis","prostate","scrotum","testis","ureter","urethra","urinary_conduit","urinary_tract_nos","uterus","vagina","vulva"]},"vasc-vess_inj_artery":{"":["aorta","carotid","extremity_lower","extremity_upper","other_nos","visceral"]},"vasc-vess_inj_vein":{"":["extremity_lower","extremity_upper","ivc","jugular","other_nos","svc","viscera"]}};
Pond.leuk_followupstatus = ["relapse","cr1","cr2","cr3","cr4","resistant_disease","alive_w_disease"];
Pond.non_leuk_followupstatus = ["relapse","cr1","cr2","cr3","cr4","alive_w_disease","partial_response","progressive","progressive_1","progressive_2","progressive_3","progressive_4","progressive_5","progressive_6","progressive_7","progressive_8","stable"];
Pond.disease_specific_classcodes = {"all":["x","unassign"],"aml":["x","unassign"],"anemia":["x","unassign"],"anemia_aplast":["x","unassign"],"anemia_fanconi":["x","unassign"],"anemia_sicklecell":["x","unassign"],"apl":["x","unassign"],"carcino":["tnm","figo","x","unassign"],"carc_parotid":["x","unassign"],"carc_thyroid":["tnm","x","unassign"],"cml":["cml_chronic","cml_accel","cml_blastic","x","unassign"],"cns":["tnm","brain_tumor_m","x","unassign"],"ewing":["tnm","sfop","sjcrh","x","unassign"],"gist":["x","unassign"],"hblast":["tnm","pretext","x","unassign"],"hcellcarcinoma":["tnm","x","unassign"],"hemangioma":["x","unassign"],"hemophilia":["x","unassign"],"histiocytic":["ish","x","unassign"],"hod":["ann_arbor","sjcrh","x","unassign"],"itp":["x","unassign"],"leuk_other":["x","unassign"],"lymphaden_benign":["x","unassign"],"lymphoma_nos":["x","unassign"],"mds":["x","unassign"],"mps":["x","unassign"],"nasocarcinoma":["tnm","x"],"nblast":["inss","tnm","x","unassign"],"neoplas_malig_unspec":["x","unassign"],"non_cns":["tnm","x","unassign"],"non_hod":["sfop","sjcrh","ann_arbor","x","unassign"],"non_rhab":["irs","tnm","x","unassign","irs_post_surgical"],"non_wilms":["nwtsg","tnm","x","unassign"],"no_diagnosis":["x","unassign"],"osteo":["tnm","x","unassign"],"other":["sfop","tnm","inss","irs","figo","sjcrh","ann_arbor","nwtsg","ish","x","unassign"],"other_disease":["x","unassign"],"rblast":["ccsg","r_ellsworth","x","unassign","international_abc","irss","sj_global_rs"],"rhab":["irs","tnm","x","unassign","irs_post_surgical"],"skin_cancer":["x","unassign"],"thalassemia":["x","unassign"],"wilms":["nwtsg","x","unassign"]};
Pond.disease_specific_histologies = {"all":["t_lineage","b_lineage"],"aml":["aml_m0","aml_m1","aml_m2","aml_m4","aml_m5","aml_m6","aml_m7","unknown"],"carcino":["nasophar_carcin","colon_carcin","breast_carcin","ovarian_carcin","carc_adrenocort","carc_other","merkel_cell_carcinoma","unknown"],"carc_thyroid":["carc_thy_follic","carc_thy_pap","carc_thy_med","unknown"],"cns":["astro_juv_pilo_w1","astro_px","astro_ca","astro_sgc","astro_fib_astrocy","astro_fib_astrocy_w2","astro_fib_astrobl_w2","astro_fib_glioblast_w4","oligo_oligo_w2","oligo_anap_oligo_w3","mixed_glial_oligo_w2","epen_anap_epen_w3","choroid_plexus_papi","choroid_plexus_carc","epen_epen_w2","epen_epenblast_tumor","epen_myxo_epen","epen_subepen","neuronal_cerebral_gang","neuronal_central_neuro","neuronal_pine","neuronal_gang_w1","neuronal_gang_w2","neuronal_anap_gang_w3","neuronal_des_inf_gang","neuronal_dys_neuro_tumor","emb_pine","emb_mixed","emb_medepi","emb_medblast","emb_atyp","sellar_cranio","sellar_pituit","astro_fib_anp_w3","chordoma","mening_nos","mening_heman","mening_mening","mening_melanocy","mening_mal_melano","mening_melanomat","gliomas_other","neoplas_other","astro_nos","neural_tumor","cns_gbm","cns_glioma_optic_nerve","cns_glioma_brainstem","cns_spinalcord","cns_teratoma","cns_gct","cns_pineal","cns_nos","unknown","cns_germinoma","cns_embryo","cns_yolk_sac","cns_choriocarcinoma","cns_germ_cell"],"ewing":["ewing_sarc_bone","ewing_sarc_stissue","askin_tumor_st","extra_ewing_st","desmo_sctumor_st","ewing_neuroect","unknown"],"hblast":["fetal","undifferentiated","mixed","unknown"],"hcellcarcinoma":["fibrolamellar","fibrolamellar_non","unknown"],"histiocytic":["langer_cell","malig_hist","hemoph_synd","unknown"],"hod":["lymp_predom","nod_sclerosing","mixed_cell","lymp_deple","hod_nos","unknown"],"leuk_other":["acute_bilineage_leuk","acute_undiff_leuk","acute_leuk_unclass","chronic_lymph_leuk","leuk_juv_mmc","leuk_nos","unknown"],"nasocarcinoma":["lympho_lymp_nk"],"nblast":["neuroblastoma","ganglioneuroblastoma","ganglioneuroma","unknown"],"non_cns":["ben_mat_tera_gona","ben_gona","ind_behav_imm_tera","mal_germ_sem","mal_germ_dys","yolk","emb_carc","chorio","mix_mal_germ","mal_germ_xgonad","carc_gonad","unknown"],"non_hod":["burkit_lymp","b_clc_lymp","lympho_lymp","anap_lymp","non_anap_lymp","lympho_lymp_b","lympho_lymp_t","lympho_lymp_nk","unknown"],"non_rhab":["synovial_sarc","malig_fib","malig_pns_tumor","fibro","leiomyo_sarc","epi_sarc","alvelar_sarc","hemangioperi","sarc_soft_other","sarc_soft_nos","sarc_soft_chondro","sarc_soft_clearcell","sarc_soft_nervesheath","non_rhab_schwanoma","oth","unknown","malignant_rhabdoid_tumour_of_sof","desmoplastic_small_round_cell_tu","congenital_infantile_fibrosarcom","fibroblastic-myofibroblastic_pro","inflammatory_myofibroblastic_tum","desmoid-type_fibromatosis"],"non_wilms":["rhab_tumor","cc_sarcoma","renal_c_carc","meso_neph","renal_nos","unknown"],"osteo":["conventional","telangiectatic","small_cell","multifocal","parsteal","periosteal","unknown","extra_osteo","osteo_nos"],"rhab":["alvelar_rhab","embryonal_rhab","botryoidal","pleomorphic","undifferentiated","unknown"],"skin_cancer":["carc_skin","carc_melanoma","carc_basal","unknown"],"wilms":["wilms_fav","wilms_fav_nuclear","wilms_anap","unknown"]};
Pond.disease_specific_fields = {"all":["251","243","250","287","1123","252","254","259","1397","1403","249","246","247","248","249","287"],"aml":["251","243","250","287","1123","252","254","259","1397","1403","249","246","247","248","249","287"],"apl":["251","243","250","287","1123","252","254","1397","1403","249","246","247","248","249","287"],"cns":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","256","257","274","278","1399","1403","1459","1458","249","246","247","248","249","287"],"ewing":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","258","271","272","273","274","278","279","1399","1403","1459","1458","249","246","247","248","249","287"],"hblast":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","258","271","272","278","1399","1403","1459","1458","249","246","247","248","249","287"],"hcellcarcinoma":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","258","271","272","278","1399","1403","1459","1458","249","246","247","248","249","287"],"hod":["251","243","250","287","1123","248","249","246","245","247","252","253","256","257","260","259","261","262","263","264","265","266","271","272","278",288,289,290,291,292,"1397","1399","1403","1459","1458","249","246","247","248","249","287"],"nblast":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","253","256","257","258","271","272","276","277","278","1399","1403","1459","1458","249","246","247","248","249","287"],"non_cns":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","271","272","278","1399","1403","1459","1458","249","246","247","248","249","287"],"non_hod":["251","243","250","287","1123","248","249","246","245","247","252","256","257","261","262","263","264","265","266","271","272",288,289,290,291,292,"1397","1399","1403","1459","1458","249","246","247","248","249","287"],"non_rhab":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","255","256","257","258","271","272","278","280","1399","1403","1459","1458","249","246","247","248","249","287"],"non_wilms":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","256","257","258","268","269","270","271","272","273","278","1399","1403","1459","1458","249","246","247","248","249","287"],"osteo":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","267","271","272","273","278","279","1399","1403","1459","1458","249","246","247","248","249","287"],"leuk_other":["251","243","250","287","1123","252","253","254","255","256","257","258","260","259","261","262","263","264","265","1397","1403","249","246","247","248","249","287"],"rblast":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","295","293","303","301","299","297","296","294","304","302","300","298","305","307","306","309","308","310","325","323","329","327","321","319","312","311","316","315","326","324","330","328","322","320","314","313","318","317","342","333","339","340","337","341","343","335","344","331","334","338","336","345","332","346","252","254","278","282","283","284","1399","1403","1459","1458","249","1461","246","247","248","249","287"],"rhab":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","255","256","257","258","271","272","278","1399","1403","1459","1458","249","246","247","248","249","287"],"wilms":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","256","257","258","268","269","270","271","272","273","278","1399","1403","1459","1458","249","246","247","248","249","287"],"histiocytic":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","253","254","255","256","257","258","260","259","261","262","263","264","265","278","1399","1403","1459","1458","249","246","247","248","249","287"],"carcino":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","253","254","255","256","257","258","260","259","261","262","263","264","265","266","267","268","269","270","271","272","273","274","275","276","277","278","279","1399","1403","1459","1458","249","246","247","248","249","287"],"other":["251","243","250","287","1123","252","271","272","278","1403","249","246","247","248","249","287"],"cml":["251","243","250","287","1123","252","254","259","1397","1403","249","246","247","248","249","287"],"skin_cancer":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","1399","1403","1459","1458","249","246","247","248","249","287"],"carc_thyroid":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","258","278","1399","1403","1459","1458","249","246","247","248","249","287"],"neoplas_malig_unspec":["251","243","250","287","1123","252","254","256","257","258","271","272","278","1403","249","246","247","248","249","287"],"carc_parotid":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","258","278","1399","1403","1459","1458","249","246","247","248","249","287"],"mds":["251","243","250","287","1123","252","254","1397","1403","249","246","247","248","249","287"],"mps":["251","243","250","287","1123","252","254","1397","1403","249","246","247","248","249","287"],"lymphoma_nos":["251","243","250","287","1123","248","249","246","245","247","252","254","260","259","261","262","263","264","265","271","272","1397","1403","1459","1458","249","246","247","248","249","287"],"gist":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","252","254","256","257","258","278","1399","1403","1459","1458","249","246","247","248","249","287"],"anemia_aplast":["251","243","250","287","1123","286","1403","249","246","247","248","249","287"],"thalassemia":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"anemia_sicklecell":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"anemia_fanconi":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"other_disease":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"no_diagnosis":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"itp":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"hemophilia":["251","243","250","287","1123","285","1403","249","246","247","248","249","287"],"lymphaden_benign":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"hemangioma":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","1399","1403","1459","1458","249","246","247","248","249","287"],"anemia":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"mesoblastic_nephroma":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"teratoma_benign":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"anemia_hemolytic":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"anemia_megaloblastic":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"anemia_other":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"bleeding_disorder_ns":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"g6pd_deficiency":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"hyper_gammaglobulinemia":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"neutropenia_ns":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"pancytopenia":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"platelet_function_disorder":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"thrombocytopenia_other":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"thrombocytosis":["251","243","250","287","1123","1403","249","246","247","248","249","287"],"medulloblastoma":["251","243","250","287","1123","248","249","246","245","247","281","291","290","289","288","292","1399","1403","1459","1458","249","246","247","248","249","287"]};

// vim: set foldmethod=marker:
//
// 

if(typeof(Control) == "undefined")
	Control = {};
Control.Time = Class.create();

Object.extend(Control.Time,{
	setHrs: function (element_id,setval)
	{
		// read current time in the element
		var org = $(element_id).value;

		// parse in to hours and minutes
		var hours = setval;
		var mins = parseInt(org.substr(3,2));

		$(element_id).value = Control.Time.getParsedTime(hours,mins);
	},

	setMins: function (element_id,setval)
	{
		// read current time in the element
		var org = $(element_id).value;

		// parse in to hours and minutes
		var hours = parseInt(org.substr(0,2));
		var mins = setval;

		$(element_id).value = Control.Time.getParsedTime(hours,mins);
	},

	getParsedTime: function(h,m)
	{
		if (isNaN(h)) { h = 0; }
		if (isNaN(m)) { m = 0; }

		// pad hours/mins
		if ( h < 10 )
		{
			h = new String("0"+h);
		}
		if ( m < 10)
		{
			m = new String("0"+m);
		}
		return h+":"+m;
	},

	getTimeFromString: function(str)
	{
		var hours = parseInt(str.substr(0,2));
		var mins = parseInt(str.substr(3,2));
		if (isNaN(hours)) { hours = 0; }
		if (isNaN(mins)) { mins = 0; }
		return [hours,mins];
	}
});

Object.extend(Control.Time.prototype,{
	// the data definition of the repeating fields
	initialize: function(element, options)
	{
		this.dialog =false;
		this.element_id = element;
		this.element = $(element);
		//this.img_element = $(this.element_id+"_timesel");
		this.options = {
			fade: true,
			fadeDuration: 0.25,
			minuteInterval: 5,
			value: '12:00'
		};
		// overide default options with the ones specified by the user
		Object.extend(this.options,options || {});

		// observe for clicks and focus
		this.element.observe('focus',this.open.bind(this));
		this.element.observe('click',this.open.bind(this));
		//this.img_element.observe('click',Control.Time.open.bindAsEventListener(Control.Time));
		//this.img_element.observe('click',this.open.bind(this));
	},

	// 
	open: function()
	{
		// get the value from the element
		var t = Control.Time.getTimeFromString(this.element.value);
		var hours = t[0];
		var mins = t[1];
		var sel = "";

		var html_contents = "<select onchange=\"Control.Time.setHrs('"+this.element_id+"',this.value);\" class='small_text' id='hrs'>";
		$R(0,23).each(function(i){
			sel = (hours == i) ? " selected=\"selected\"" : "";
			html_contents += "<option value=\""+i+"\""+sel+">"+i.toPaddedString(2)+"</option>";
		});
		html_contents += "</select>";

		html_contents += "<select onchange=\"Control.Time.setMins('"+this.element_id+"',this.value);\" class='small_text' id='mins'>";
		for(var i=0; i<60; i+= (this.options.minuteInterval))
		{
			sel = (mins == i) ? " selected=\"selected\"" : "";
			var str =i.toPaddedString(2);
			html_contents += "<option value=\""+str+"\""+sel+">"+str+"</option>";
		}
		html_contents += "</select>";

		html_contents += " <a style='font-size:10px;' href='#' onclick='Control.Modal.close();return false;'>Done</a>";

		this.dialog = new Control.Modal(this.element,{
			position: 'relative',
			offsetTop: 20,
			width: '124px',
			height: '34px',
			contents: html_contents
		});
		this.dialog.open();
		return false;
	}
});


if(typeof(Pond) == "undefined") Pond = {};var Pond_Lang = new Array();Pond_Lang['list_status_followup.relapse']='Relapse';
Pond_Lang['list_status_followup.cr1']='CR1';
Pond_Lang['list_status_followup.cr2']='CR2';
Pond_Lang['list_status_followup.cr3']='CR3';
Pond_Lang['list_status_followup.cr4']='CR4';
Pond_Lang['list_status_followup.resistant_disease']='Resistant disease (RD)';
Pond_Lang['list_status_followup.alive_w_disease']='Alive with Disease';
Pond_Lang['list_status_followup.partial_response']='Partial response (PR)';
Pond_Lang['list_status_followup.progressive']='Progressive disease (PD)';
Pond_Lang['list_status_followup.progressive_1']='Progressive disease 1st (PD-1)';
Pond_Lang['list_status_followup.progressive_2']='Progressive disease 2st (PD-2)';
Pond_Lang['list_status_followup.progressive_3']='Progressive disease 3st (PD-3)';
Pond_Lang['list_status_followup.progressive_4']='Progressive disease 4st (PD-4)';
Pond_Lang['list_status_followup.progressive_5']='Progressive disease 5st (PD-5)';
Pond_Lang['list_status_followup.progressive_6']='Progressive disease 6st (PD-6)';
Pond_Lang['list_status_followup.progressive_7']='Progressive disease 7st (PD-7)';
Pond_Lang['list_status_followup.progressive_8']='Progressive disease 8st (PD-8)';
Pond_Lang['list_status_followup.stable']='Stable disease (SD)';
Pond_Lang['list_ctcae_category.x']='No data';
Pond_Lang['list_ctcae_category.allergy_immuno']='Allergy / immunology';
Pond_Lang['list_ctcae_category.aud_ear']='Auditory / ear';
Pond_Lang['list_ctcae_category.blood_bone']='Blood / bone marrow';
Pond_Lang['list_ctcae_category.card_arrhy']='Cardiac arrhythmia';
Pond_Lang['list_ctcae_category.card_gen']='Cardiac general';
Pond_Lang['list_ctcae_category.coag']='Coagulation';
Pond_Lang['list_ctcae_category.const']='Constitutional symptoms';
Pond_Lang['list_ctcae_category.death']='Death';
Pond_Lang['list_ctcae_category.derma_skin']='Dermatology / skin';
Pond_Lang['list_ctcae_category.endo']='Endocrine';
Pond_Lang['list_ctcae_category.gastro']='Gastrointestinal';
Pond_Lang['list_ctcae_category.growth_devel']='Growth and development';
Pond_Lang['list_ctcae_category.hemor_bleed']='Hemorrhage / bleeding';
Pond_Lang['list_ctcae_category.hepat_panc']='Hepatobiliary / pancreas';
Pond_Lang['list_ctcae_category.infec']='Infection';
Pond_Lang['list_ctcae_category.lymph']='Lymphatics';
Pond_Lang['list_ctcae_category.metab_lab']='Metabolic / laboratory';
Pond_Lang['list_ctcae_category.muscul_tissue']='Musculoskeletal / soft tissue';
Pond_Lang['list_ctcae_category.neuro']='Neurology';
Pond_Lang['list_ctcae_category.ocu_vis']='Ocular / visual';
Pond_Lang['list_ctcae_category.pain']='Pain';
Pond_Lang['list_ctcae_category.pulm_resp']='Pulmonary / upper respiratory';
Pond_Lang['list_ctcae_category.renal_genit']='Renal / genitourinary';
Pond_Lang['list_ctcae_category.sec_malig']='Secondary malignancy';
Pond_Lang['list_ctcae_category.sex_repro']='Sexual / reproductive function';
Pond_Lang['list_ctcae_category.surg_injury']='Surgery / intra-operative injury';
Pond_Lang['list_ctcae_category.synd']='Syndromes';
Pond_Lang['list_ctcae_category.vasc']='Vascular';
Pond_Lang['list_ctcae_category.transreact']='Transfusion Reactions';
Pond_Lang['list_ctcae_event.allergy_immuno-hypersense']='Allergic reaction';
Pond_Lang['list_ctcae_event.allergy_immuno-rhinitis']='Rhinitis';
Pond_Lang['list_ctcae_event.allergy_immuno-autoimmune']='Autoimmune reaction';
Pond_Lang['list_ctcae_event.allergy_immuno-serum_sick']='Serum sickness';
Pond_Lang['list_ctcae_event.allergy_immuno-vasculitis']='Vasculitis';
Pond_Lang['list_ctcae_event.allergy_immuno-other']='Allergy -- Other (Specify)';
Pond_Lang['list_ctcae_event.aud_ear-hear_monitor']='Hearing (monitoring program)';
Pond_Lang['list_ctcae_event.aud_ear-hear_no_monitor']='Hearing (without monitoring program)';
Pond_Lang['list_ctcae_event.aud_ear-otitis_ext']='Otitis, external';
Pond_Lang['list_ctcae_event.aud_ear-otitis_mid']='Otitis, middle';
Pond_Lang['list_ctcae_event.aud_ear-tinnitus']='Tinnitus';
Pond_Lang['list_ctcae_event.aud_ear-other']='Auditory/Ear -- Other (Specify)';
Pond_Lang['list_ctcae_event.blood_bone-bone_marrow_cell']='Bone marrow cellularity';
Pond_Lang['list_ctcae_event.blood_bone-cd4']='CD4 count';
Pond_Lang['list_ctcae_event.blood_bone-haptoglobin']='Haptoglobin';
Pond_Lang['list_ctcae_event.blood_bone-hemoglobin']='Hemoglobin';
Pond_Lang['list_ctcae_event.blood_bone-hemolysis']='Hemolysis';
Pond_Lang['list_ctcae_event.blood_bone-iron_overload']='Iron overload';
Pond_Lang['list_ctcae_event.blood_bone-leukocytes']='Leukocytes';
Pond_Lang['list_ctcae_event.blood_bone-lymphopenia']='Lymphopenia';
Pond_Lang['list_ctcae_event.blood_bone-myelodysplasia']='Myelodysplasia';
Pond_Lang['list_ctcae_event.blood_bone-neutrophils']='Neutrophils';
Pond_Lang['list_ctcae_event.blood_bone-platelets']='Platelets';
Pond_Lang['list_ctcae_event.blood_bone-splenic_func']='Splenic function';
Pond_Lang['list_ctcae_event.blood_bone-other']='Blood -- Other (Specify)';
Pond_Lang['list_ctcae_event.card_arrhy-conduct_abnorm']='Conduction abnormality';
Pond_Lang['list_ctcae_event.card_arrhy-palpitations']='Palpitations';
Pond_Lang['list_ctcae_event.card_arrhy-prolong_qtc_int']='Prolonged QTc';
Pond_Lang['list_ctcae_event.card_arrhy-supravent_arrhythmia']='Supraventricular arrhythmia';
Pond_Lang['list_ctcae_event.card_arrhy-vasovagal_epi']='Vasovagal episode';
Pond_Lang['list_ctcae_event.card_arrhy-ventric_arrhythmia']='Ventricular arrhythmia';
Pond_Lang['list_ctcae_event.card_arrhy-other']='Cardiac Arrhythmia -- Other (Specify)';
Pond_Lang['list_ctcae_event.card_gen-ischem_infarc']='Cardiac ischemia/infarction';
Pond_Lang['list_ctcae_event.card_gen-troponin_I']='cTnI';
Pond_Lang['list_ctcae_event.card_gen-troponin_T']='cTnT';
Pond_Lang['list_ctcae_event.card_gen-arrest_unknown']='Cardiopulmonary arrest';
Pond_Lang['list_ctcae_event.card_gen-hypertension']='Hypertension';
Pond_Lang['list_ctcae_event.card_gen-hypotension']='Hypotension';
Pond_Lang['list_ctcae_event.card_gen-left_ventri_diastolic']='Left ventricular diastolic dysfunction';
Pond_Lang['list_ctcae_event.card_gen-left_ventri_systolic']='Left ventricular systolic dysfunction';
Pond_Lang['list_ctcae_event.card_gen-myocarditis']='Myocarditis';
Pond_Lang['list_ctcae_event.card_gen-pericard_effusion']='Pericardial effusion';
Pond_Lang['list_ctcae_event.card_gen-pericarditis']='Pericarditis';
Pond_Lang['list_ctcae_event.card_gen-pulm_hypertension']='Pulmonary hypertension';
Pond_Lang['list_ctcae_event.card_gen-restr_cardiomyopathy']='Restrictive cardiomyopathy';
Pond_Lang['list_ctcae_event.card_gen-right_ventri']='Right ventricular dysfunction';
Pond_Lang['list_ctcae_event.card_gen-valvular_heart_dis']='Valvular heart disease';
Pond_Lang['list_ctcae_event.card_gen-other']='Cardiac General -- Other (Specify)';
Pond_Lang['list_ctcae_event.coag-DIC']='DIC';
Pond_Lang['list_ctcae_event.coag-fibrinogen']='Fibrinogen';
Pond_Lang['list_ctcae_event.coag-INR_prothrombin']='INR';
Pond_Lang['list_ctcae_event.coag-PTT']='PTT';
Pond_Lang['list_ctcae_event.coag-thromb_microangi']='Thrombotic microangiopathy';
Pond_Lang['list_ctcae_event.coag-other']='Coagulation -- Other (Specify)';
Pond_Lang['list_ctcae_event.const-fatigue']='Fatigue';
Pond_Lang['list_ctcae_event.const-fever']='Fever';
Pond_Lang['list_ctcae_event.const-hypothermia']='Hypothermia';
Pond_Lang['list_ctcae_event.const-insomnia']='Insomnia';
Pond_Lang['list_ctcae_event.const-obesity']='Obesity';
Pond_Lang['list_ctcae_event.const-odor']='Patient odor';
Pond_Lang['list_ctcae_event.const-rigors_or_chills']='Rigors/chills';
Pond_Lang['list_ctcae_event.const-sweating']='Sweating';
Pond_Lang['list_ctcae_event.const-weight_gain']='Weight gain';
Pond_Lang['list_ctcae_event.const-weight_loss']='Weight loss';
Pond_Lang['list_ctcae_event.const-other']='Constitutional Symptoms -- Other (Specify)';
Pond_Lang['list_ctcae_event.death-death']='Death not associated with CTCAE term';
Pond_Lang['list_ctcae_event.derma_skin-atrophy_skin']='Atrophy, skin';
Pond_Lang['list_ctcae_event.derma_skin-atrophy_fat']='Atrophy, subcutaneous fat';
Pond_Lang['list_ctcae_event.derma_skin-bruising']='Bruising';
Pond_Lang['list_ctcae_event.derma_skin-burn']='Burn';
Pond_Lang['list_ctcae_event.derma_skin-cheilitis']='Cheilitis';
Pond_Lang['list_ctcae_event.derma_skin-dry_skin']='Dry skin';
Pond_Lang['list_ctcae_event.derma_skin-flushing']='Flushing';
Pond_Lang['list_ctcae_event.derma_skin-hair_loss']='Alopecia';
Pond_Lang['list_ctcae_event.derma_skin-hyperpigmentation']='Hyperpigmentation';
Pond_Lang['list_ctcae_event.derma_skin-hypopigmentation']='Hypopigmentation';
Pond_Lang['list_ctcae_event.derma_skin-induration_fibrosis']='Induration';
Pond_Lang['list_ctcae_event.derma_skin-inject_site_react']='Injection site reaction';
Pond_Lang['list_ctcae_event.derma_skin-nail_changes']='Nail changes';
Pond_Lang['list_ctcae_event.derma_skin-photosensitivity']='Photosensitivity';
Pond_Lang['list_ctcae_event.derma_skin-pruritus']='Pruritus';
Pond_Lang['list_ctcae_event.derma_skin-acne']='Acne';
Pond_Lang['list_ctcae_event.derma_skin-rash_dermatitis']='Dermatitis';
Pond_Lang['list_ctcae_event.derma_skin-rash_erythema']='Erythema multiforme';
Pond_Lang['list_ctcae_event.derma_skin-rash_hand_foot_react']='Hand-foot';
Pond_Lang['list_ctcae_event.derma_skin-decubitus']='Decubitus';
Pond_Lang['list_ctcae_event.derma_skin-striae']='Striae';
Pond_Lang['list_ctcae_event.derma_skin-telangiectasia']='Telangiectasia';
Pond_Lang['list_ctcae_event.derma_skin-ulceration']='Ulceration';
Pond_Lang['list_ctcae_event.derma_skin-urticaria']='Urticaria';
Pond_Lang['list_ctcae_event.derma_skin-wound_comp_non_inf']='Wound complication, non-infectious';
Pond_Lang['list_ctcae_event.derma_skin-other']='Dermatology -- Other (Specify)';
Pond_Lang['list_ctcae_event.endo-adren_insuff']='Adrenal insufficiency';
Pond_Lang['list_ctcae_event.endo-cushingoid_appear']='Cushingoid';
Pond_Lang['list_ctcae_event.endo-feminine_of_male']='Feminization of male';
Pond_Lang['list_ctcae_event.endo-hot_flashes']='Hot flashes';
Pond_Lang['list_ctcae_event.endo-masculine_of_female']='Masculinization of female';
Pond_Lang['list_ctcae_event.endo-neuro_ACTH_defic']='ACTH';
Pond_Lang['list_ctcae_event.endo-neuro_ADH_abnorm']='ADH';
Pond_Lang['list_ctcae_event.endo-neuro_gonado_abnorm']='Gonadotropin';
Pond_Lang['list_ctcae_event.endo-neuro_growth_horm_abnorm']='Growth hormone';
Pond_Lang['list_ctcae_event.endo-neuro_prolac_horm_abnorm']='Prolactin';
Pond_Lang['list_ctcae_event.endo-diabetes']='Diabetes';
Pond_Lang['list_ctcae_event.endo-hypoparathyroid']='Hypoparathyroidism';
Pond_Lang['list_ctcae_event.endo-hyperthyroidism']='Hyperthyroidism';
Pond_Lang['list_ctcae_event.endo-hypothyroidism']='Hypothyroidism';
Pond_Lang['list_ctcae_event.endo-other']='Endocrine -- Other (Specify)';
Pond_Lang['list_ctcae_event.gastro-anorexia']='Anorexia';
Pond_Lang['list_ctcae_event.gastro-ascites']='Ascites';
Pond_Lang['list_ctcae_event.gastro-colitis']='Colitis';
Pond_Lang['list_ctcae_event.gastro-constipation']='Constipation';
Pond_Lang['list_ctcae_event.gastro-dehydration']='Dehydration';
Pond_Lang['list_ctcae_event.gastro-dentures']='Dentures';
Pond_Lang['list_ctcae_event.gastro-periodontal']='Periodontal';
Pond_Lang['list_ctcae_event.gastro-teeth']='Teeth';
Pond_Lang['list_ctcae_event.gastro-diarrhea']='Diarrhea';
Pond_Lang['list_ctcae_event.gastro-distension']='Distension';
Pond_Lang['list_ctcae_event.gastro-dry_mouth']='Dry mouth';
Pond_Lang['list_ctcae_event.gastro-dysphagia']='Dysphagia';
Pond_Lang['list_ctcae_event.gastro-enteritis']='Enteritis';
Pond_Lang['list_ctcae_event.gastro-esophagitis']='Esophagitis';
Pond_Lang['list_ctcae_event.gastro-fistula']='Fistula, GI';
Pond_Lang['list_ctcae_event.gastro-flatulence']='Flatulence';
Pond_Lang['list_ctcae_event.gastro-gastritis']='Gastritis';
Pond_Lang['list_ctcae_event.gastro-heartburn']='Heartburn';
Pond_Lang['list_ctcae_event.gastro-hemorrhoids']='Hemorrhoids';
Pond_Lang['list_ctcae_event.gastro-ileus']='Ileus';
Pond_Lang['list_ctcae_event.gastro-incontinence_anal']='Incontinence, anal';
Pond_Lang['list_ctcae_event.gastro-leak']='Leak, GI';
Pond_Lang['list_ctcae_event.gastro-malabsorption']='Malabsorption';
Pond_Lang['list_ctcae_event.gastro-mucositis_clinic']='Mucositis (clinical exam)';
Pond_Lang['list_ctcae_event.gastro-mucositis_func']='Mucositis (functional/symptomatic)';
Pond_Lang['list_ctcae_event.gastro-nausea']='Nausea';
Pond_Lang['list_ctcae_event.gastro-necrosis']='Necrosis, GI';
Pond_Lang['list_ctcae_event.gastro-obstruction']='Obstruction, GI';
Pond_Lang['list_ctcae_event.gastro-perforation']='Perforation, GI';
Pond_Lang['list_ctcae_event.gastro-proctitis']='Proctitis';
Pond_Lang['list_ctcae_event.gastro-prolapse_stoma']='Prolapse of stoma, GI';
Pond_Lang['list_ctcae_event.gastro-salivary_gland']='Salivary gland changes';
Pond_Lang['list_ctcae_event.gastro-stricture']='Stricture, GI';
Pond_Lang['list_ctcae_event.gastro-taste_alter']='Taste alteration';
Pond_Lang['list_ctcae_event.gastro-typhlitis']='Typhlitis';
Pond_Lang['list_ctcae_event.gastro-ulcer']='Ulcer, GI';
Pond_Lang['list_ctcae_event.gastro-vomiting']='Vomiting';
Pond_Lang['list_ctcae_event.gastro-other']='GI -- Other (Specify)';
Pond_Lang['list_ctcae_event.growth_devel-bone_age']='Bone age';
Pond_Lang['list_ctcae_event.growth_devel-bone_femor_head']='Femoral head growth';
Pond_Lang['list_ctcae_event.growth_devel-bone_limb_length']='Limb length';
Pond_Lang['list_ctcae_event.growth_devel-bone_spine_kyph']='Kyphosis/lordosis';
Pond_Lang['list_ctcae_event.growth_devel-growth_velo']='Reduction in growth velocity';
Pond_Lang['list_ctcae_event.growth_devel-puberty_delayed']='Delayed puberty';
Pond_Lang['list_ctcae_event.growth_devel-puberty_precocious']='Precocious puberty';
Pond_Lang['list_ctcae_event.growth_devel-short_stature']='Short stature';
Pond_Lang['list_ctcae_event.growth_devel-other']='Growth and Development -- Other (Specify)';
Pond_Lang['list_ctcae_event.hemor_bleed-hematoma']='Hematoma';
Pond_Lang['list_ctcae_event.hemor_bleed-hemorr_w_surgery']='Hemorrhage with surgery';
Pond_Lang['list_ctcae_event.hemor_bleed-hemorr_CNS']='CNS hemorrhage';
Pond_Lang['list_ctcae_event.hemor_bleed-hemorr_GI']='Hemorrhage, GI';
Pond_Lang['list_ctcae_event.hemor_bleed-hemorr_GU']='Hemorrhage, GU';
Pond_Lang['list_ctcae_event.hemor_bleed-hemorr_pulm_resp']='Hemorrhage pulmonary';
Pond_Lang['list_ctcae_event.hemor_bleed-petechiae']='Petechiae';
Pond_Lang['list_ctcae_event.hemor_bleed-other']='Hemorrhage -- Other (Specify)';
Pond_Lang['list_ctcae_event.hepat_panc-cholecystitis']='Cholecystitis';
Pond_Lang['list_ctcae_event.hepat_panc-liver_dysfunc']='Liver dysfunction';
Pond_Lang['list_ctcae_event.hepat_panc-panc_exocrine_defic']='Pancreas, exocrine enzyme deficiency';
Pond_Lang['list_ctcae_event.hepat_panc-pancreatitis']='Pancreatitis';
Pond_Lang['list_ctcae_event.hepat_panc-other']='Hepatobiliary -- Other (Specify)';
Pond_Lang['list_ctcae_event.infec-colitis_infect']='Colitis, infectious';
Pond_Lang['list_ctcae_event.infec-febrile_neutropenia']='Febrile neutropenia';
Pond_Lang['list_ctcae_event.infec-infect_clinic']='Infection (documented clinically)';
Pond_Lang['list_ctcae_event.infec-infect_w_norm_ANC']='Infection with normal ANC';
Pond_Lang['list_ctcae_event.infec-infect_w_unkn_ANC']='Infection with unknown ANC';
Pond_Lang['list_ctcae_event.infec-lymphopenia_infect']='Opportunistic infection';
Pond_Lang['list_ctcae_event.infec-viral_hepatitis']='Viral hepatitis';
Pond_Lang['list_ctcae_event.infec-other']='Infection -- Other (Specify)';
Pond_Lang['list_ctcae_event.lymph-chyle_lymph_leak']='Chyle or lymph leakage';
Pond_Lang['list_ctcae_event.lymph-dermal_change']='Dermal change';
Pond_Lang['list_ctcae_event.lymph-edema_head_neck']='Edema: head and neck';
Pond_Lang['list_ctcae_event.lymph-edema_limb']='Edema: limb';
Pond_Lang['list_ctcae_event.lymph-edema_trunk_genital']='Edema: trunk/genital';
Pond_Lang['list_ctcae_event.lymph-edema_viscera']='Edema: viscera';
Pond_Lang['list_ctcae_event.lymph-lymphedema_rel_fibrosis']='Lymphedema-related fibrosis';
Pond_Lang['list_ctcae_event.lymph-lymphocele']='Lymphocele';
Pond_Lang['list_ctcae_event.lymph-phlebolymph_cord']='Phlebolymphatic cording';
Pond_Lang['list_ctcae_event.lymph-other']='Lymphatics -- Other (Specify)';
Pond_Lang['list_ctcae_event.metab_lab-acidosis']='Acidosis';
Pond_Lang['list_ctcae_event.metab_lab-hypoalbuminemia']='Hypoalbuminemia';
Pond_Lang['list_ctcae_event.metab_lab-alkaline_phosphatase']='Alkaline phosphatase';
Pond_Lang['list_ctcae_event.metab_lab-alkalosis']='Alkalosis';
Pond_Lang['list_ctcae_event.metab_lab-ALT_SGPT']='ALT';
Pond_Lang['list_ctcae_event.metab_lab-amylase']='Amylase';
Pond_Lang['list_ctcae_event.metab_lab-AST_SGOT']='AST';
Pond_Lang['list_ctcae_event.metab_lab-bicarbonate']='Bicarbonate, serum-low';
Pond_Lang['list_ctcae_event.metab_lab-bilirubin']='Bilirubin';
Pond_Lang['list_ctcae_event.metab_lab-hypocalcemia']='Hypocalcemia';
Pond_Lang['list_ctcae_event.metab_lab-hypercalcemia']='Hypercalcemia';
Pond_Lang['list_ctcae_event.metab_lab-cholesterol']='Cholesterol';
Pond_Lang['list_ctcae_event.metab_lab-CPK']='CPK';
Pond_Lang['list_ctcae_event.metab_lab-creatinine']='Creatinine';
Pond_Lang['list_ctcae_event.metab_lab-GCT']='GGT';
Pond_Lang['list_ctcae_event.metab_lab-GFR']='GFR';
Pond_Lang['list_ctcae_event.metab_lab-hyperglycemia']='Hyperglycemia';
Pond_Lang['list_ctcae_event.metab_lab-hypoglycemia']='Hypoglycemia';
Pond_Lang['list_ctcae_event.metab_lab-hemoglobinuria']='Hemoglobinuria';
Pond_Lang['list_ctcae_event.metab_lab-lipase']='Lipase';
Pond_Lang['list_ctcae_event.metab_lab-hypermagnesemia']='Hypermagnesemia';
Pond_Lang['list_ctcae_event.metab_lab-hypomagnesemia']='Hypomagnesemia';
Pond_Lang['list_ctcae_event.metab_lab-hypophosphatemia']='Hypophosphatemia';
Pond_Lang['list_ctcae_event.metab_lab-hyperkalemia']='Hyperkalemia';
Pond_Lang['list_ctcae_event.metab_lab-hypokalemia']='Hypokalemia';
Pond_Lang['list_ctcae_event.metab_lab-proteinuria']='Proteinuria';
Pond_Lang['list_ctcae_event.metab_lab-hypernatremia']='Hypernatremia';
Pond_Lang['list_ctcae_event.metab_lab-hyponatremia']='Hyponatremia';
Pond_Lang['list_ctcae_event.metab_lab-hypertriglyceridemia']='Hypertriglyceridemia';
Pond_Lang['list_ctcae_event.metab_lab-hyperuricemia']='Hyperuricemia';
Pond_Lang['list_ctcae_event.metab_lab-other']='Metabolic/Lab -- Other (Specify)';
Pond_Lang['list_ctcae_event.muscul_tissue-arthritis']='Arthritis';
Pond_Lang['list_ctcae_event.muscul_tissue-bone_scoliosis']='Scoliosis';
Pond_Lang['list_ctcae_event.muscul_tissue-cervic_spine_ROM']='Cervical spine ROM';
Pond_Lang['list_ctcae_event.muscul_tissue-exostosis']='Exostosis';
Pond_Lang['list_ctcae_event.muscul_tissue-extrem_gait']='Gait/walking';
Pond_Lang['list_ctcae_event.muscul_tissue-extrem_up_func']='Extremity-upper (function)';
Pond_Lang['list_ctcae_event.muscul_tissue-fibrosis_cosmesis']='Fibrosis-cosmesis';
Pond_Lang['list_ctcae_event.muscul_tissue-fibrosis_deep']='Fibrosis-deep connective tissue';
Pond_Lang['list_ctcae_event.muscul_tissue-fracture']='Fracture';
Pond_Lang['list_ctcae_event.muscul_tissue-joint_effus']='Joint-effusion';
Pond_Lang['list_ctcae_event.muscul_tissue-joint_func']='Joint-function';
Pond_Lang['list_ctcae_event.muscul_tissue-prosthesis']='Device/prosthesis';
Pond_Lang['list_ctcae_event.muscul_tissue-lumbar_spine_ROM']='Lumbar spine ROM';
Pond_Lang['list_ctcae_event.muscul_tissue-muscle_weak']='Muscle weakness';
Pond_Lang['list_ctcae_event.muscul_tissue-hypoplasia']='Muscular/skeletal hypoplasia';
Pond_Lang['list_ctcae_event.muscul_tissue-myositis']='Myositis';
Pond_Lang['list_ctcae_event.muscul_tissue-osteonecrosis']='Osteonecrosis';
Pond_Lang['list_ctcae_event.muscul_tissue-osteoporosis']='Osteoporosis';
Pond_Lang['list_ctcae_event.muscul_tissue-seroma']='Seroma';
Pond_Lang['list_ctcae_event.muscul_tissue-soft_necrosis']='Soft tissue necrosis';
Pond_Lang['list_ctcae_event.muscul_tissue-trismus']='Trismus';
Pond_Lang['list_ctcae_event.muscul_tissue-other']='Musculoskeletal -- Other (Specify)';
Pond_Lang['list_ctcae_event.neuro-apnea']='Apnea';
Pond_Lang['list_ctcae_event.neuro-arachnoiditis']='Arachnoiditis';
Pond_Lang['list_ctcae_event.neuro-ataxia']='Ataxia';
Pond_Lang['list_ctcae_event.neuro-brach_plexopathy']='Brachial plexopathy';
Pond_Lang['list_ctcae_event.neuro-CNS_ischemia']='CNS ischemia';
Pond_Lang['list_ctcae_event.neuro-CNS_necrosis']='CNS necrosis';
Pond_Lang['list_ctcae_event.neuro-cognitive_dist']='Cognitive disturbance';
Pond_Lang['list_ctcae_event.neuro-confusion']='Confusion';
Pond_Lang['list_ctcae_event.neuro-dizziness']='Dizziness';
Pond_Lang['list_ctcae_event.neuro-encephalopathy']='Encephalopathy';
Pond_Lang['list_ctcae_event.neuro-invol_movement']='Involuntary movement';
Pond_Lang['list_ctcae_event.neuro-hydrocephalus']='Hydrocephalus';
Pond_Lang['list_ctcae_event.neuro-irritability']='Irritability';
Pond_Lang['list_ctcae_event.neuro-laryngeal_nerve']='Laryngeal nerve';
Pond_Lang['list_ctcae_event.neuro-CSF_leak']='CSF leak';
Pond_Lang['list_ctcae_event.neuro-leukoencephalopathy']='Leukoencephalopathy';
Pond_Lang['list_ctcae_event.neuro-memory_impair']='Memory impairment';
Pond_Lang['list_ctcae_event.neuro-mental_status']='Mental status';
Pond_Lang['list_ctcae_event.neuro-mood_alter']='Mood alteration';
Pond_Lang['list_ctcae_event.neuro-myelitis']='Myelitis';
Pond_Lang['list_ctcae_event.neuro-neuro_cranial']='Neuropathy: cranial';
Pond_Lang['list_ctcae_event.neuro-neuro_motor']='Neuropathy-motor';
Pond_Lang['list_ctcae_event.neuro-neuro_sensory']='Neuropathy-sensory';
Pond_Lang['list_ctcae_event.neuro-personality']='Personality';
Pond_Lang['list_ctcae_event.neuro-phrenic_nerve']='Phrenic nerve';
Pond_Lang['list_ctcae_event.neuro-psychosis']='Psychosis';
Pond_Lang['list_ctcae_event.neuro-pyramidal_tract']='Pyramidal tract dysfunction';
Pond_Lang['list_ctcae_event.neuro-seizure']='Seizure';
Pond_Lang['list_ctcae_event.neuro-somnolence']='Somnolence';
Pond_Lang['list_ctcae_event.neuro-speech_impair']='Speech impairment';
Pond_Lang['list_ctcae_event.neuro-syncope_faint']='Syncope (fainting)';
Pond_Lang['list_ctcae_event.neuro-tremor']='Tremor';
Pond_Lang['list_ctcae_event.neuro-other']='Neurology -- Other (Specify)';
Pond_Lang['list_ctcae_event.ocu_vis-cataract']='Cataract';
Pond_Lang['list_ctcae_event.ocu_vis-dry_eye']='Dry eye';
Pond_Lang['list_ctcae_event.ocu_vis-eyelid_dysfunc']='Eyelid dysfunction';
Pond_Lang['list_ctcae_event.ocu_vis-glaucoma']='Glaucoma';
Pond_Lang['list_ctcae_event.ocu_vis-keratitis']='Keratitis';
Pond_Lang['list_ctcae_event.ocu_vis-nyctalopia']='Nyctalopia';
Pond_Lang['list_ctcae_event.ocu_vis-nystagmus']='Nystagmus';
Pond_Lang['list_ctcae_event.ocu_vis-ocular_surf_dis']='Ocular surface disease';
Pond_Lang['list_ctcae_event.ocu_vis-diplopia']='Diplopia';
Pond_Lang['list_ctcae_event.ocu_vis-optic_disc_edema']='Optic disc edema';
Pond_Lang['list_ctcae_event.ocu_vis-proptosis_enophthalmos']='Proptosis/enophthalmos';
Pond_Lang['list_ctcae_event.ocu_vis-retinal_detach']='Retinal detachment';
Pond_Lang['list_ctcae_event.ocu_vis-retinopathy']='Retinopathy';
Pond_Lang['list_ctcae_event.ocu_vis-scleral_necrosis']='Scleral necrosis';
Pond_Lang['list_ctcae_event.ocu_vis-uveitis']='Uveitis';
Pond_Lang['list_ctcae_event.ocu_vis-blurred_vision']='Blurred vision';
Pond_Lang['list_ctcae_event.ocu_vis-flashing_lights']='Flashing lights';
Pond_Lang['list_ctcae_event.ocu_vis-photophobia']='Photophobia';
Pond_Lang['list_ctcae_event.ocu_vis-vitreous_hemorr']='Vitreous hemorrhage';
Pond_Lang['list_ctcae_event.ocu_vis-watery_eye']='Watery eye';
Pond_Lang['list_ctcae_event.ocu_vis-other']='Ocular -- Other (Specify)';
Pond_Lang['list_ctcae_event.pain-pain']='Pain';
Pond_Lang['list_ctcae_event.pain-other']='Pain -- Other (Specify)';
Pond_Lang['list_ctcae_event.pulm_resp-ARDS']='ARDS';
Pond_Lang['list_ctcae_event.pulm_resp-aspiration']='Aspiration';
Pond_Lang['list_ctcae_event.pulm_resp-atelectasis']='Atelectasis';
Pond_Lang['list_ctcae_event.pulm_resp-bronchospasm']='Bronchospasm';
Pond_Lang['list_ctcae_event.pulm_resp-carb_monox_diff_cap']='DL<sub>CO</sub>';
Pond_Lang['list_ctcae_event.pulm_resp-chylothorax']='Chylothorax';
Pond_Lang['list_ctcae_event.pulm_resp-cough']='Cough';
Pond_Lang['list_ctcae_event.pulm_resp-dyspnea']='Dyspnea';
Pond_Lang['list_ctcae_event.pulm_resp-edema_larynx']='Edema, larynx';
Pond_Lang['list_ctcae_event.pulm_resp-fev1']='FEV<sub>1</sub>';
Pond_Lang['list_ctcae_event.pulm_resp-fistula_pulm']='Fistula, pulmonary';
Pond_Lang['list_ctcae_event.pulm_resp-hiccoughs']='Hiccoughs';
Pond_Lang['list_ctcae_event.pulm_resp-hypoxia']='Hypoxia';
Pond_Lang['list_ctcae_event.pulm_resp-nasal_paranasal_react']='Nasal/paranasal reactions';
Pond_Lang['list_ctcae_event.pulm_resp-obstruct_airway']='Airway obstruction';
Pond_Lang['list_ctcae_event.pulm_resp-pleural_effusion']='Pleural effusion';
Pond_Lang['list_ctcae_event.pulm_resp-pneumonitis']='Pneumonitis';
Pond_Lang['list_ctcae_event.pulm_resp-pneumothorax']='Pneumothorax';
Pond_Lang['list_ctcae_event.pulm_resp-chest_tube_drain_leak']='Chest tube drainage or leak';
Pond_Lang['list_ctcae_event.pulm_resp-prolong_intubation']='Prolonged intubation';
Pond_Lang['list_ctcae_event.pulm_resp-pulm_fibrosis']='Pulmonary fibrosis';
Pond_Lang['list_ctcae_event.pulm_resp-vital_capacity']='Vital capacity';
Pond_Lang['list_ctcae_event.pulm_resp-voice_change']='Voice changes';
Pond_Lang['list_ctcae_event.pulm_resp-other']='Pulmonary -- Other (Specify)';
Pond_Lang['list_ctcae_event.renal_genit-bladder_spasm']='Bladder spasms';
Pond_Lang['list_ctcae_event.renal_genit-cystitis']='Cystitis';
Pond_Lang['list_ctcae_event.renal_genit-fistula']='Fistula, GU';
Pond_Lang['list_ctcae_event.renal_genit-incontin_urine']='Incontinence, urinary';
Pond_Lang['list_ctcae_event.renal_genit-leak']='Leak, GU';
Pond_Lang['list_ctcae_event.renal_genit-obstruct']='Obstruction, GU';
Pond_Lang['list_ctcae_event.renal_genit-perforation']='Perforation, GU';
Pond_Lang['list_ctcae_event.renal_genit-prolapse_stoma']='Prolapse stoma, GU';
Pond_Lang['list_ctcae_event.renal_genit-renal_fail']='Renal failure';
Pond_Lang['list_ctcae_event.renal_genit-stricture_anastomo']='Stricture, anastomotic, GU';
Pond_Lang['list_ctcae_event.renal_genit-urinary_elect_waste']='Urinary electrolyte wasting';
Pond_Lang['list_ctcae_event.renal_genit-urinary_freq']='Urinary frequency';
Pond_Lang['list_ctcae_event.renal_genit-urinary_retent']='Urinary retention';
Pond_Lang['list_ctcae_event.renal_genit-urine_color_chg']='Urine color change';
Pond_Lang['list_ctcae_event.renal_genit-other']='Renal -- Other (Specify)';
Pond_Lang['list_ctcae_event.sec_malig-poss_rel']='Secondary Malignancy (possibly related to cancer treatment)';
Pond_Lang['list_ctcae_event.sex_repro-breast_func']='Breast function';
Pond_Lang['list_ctcae_event.sex_repro-nipple_areolar_deform']='Nipple/areolar';
Pond_Lang['list_ctcae_event.sex_repro-breast_vol']='Breast';
Pond_Lang['list_ctcae_event.sex_repro-erect_dysfunc']='Erectile dysfunction';
Pond_Lang['list_ctcae_event.sex_repro-ejac_dysfunc']='Ejaculatory dysfunction';
Pond_Lang['list_ctcae_event.sex_repro-gynecomastia']='Gynecomastia';
Pond_Lang['list_ctcae_event.sex_repro-infert_sterile']='Infertility/sterility';
Pond_Lang['list_ctcae_event.sex_repro-irreg_menses']='Irregular menses';
Pond_Lang['list_ctcae_event.sex_repro-libido']='Libido';
Pond_Lang['list_ctcae_event.sex_repro-orgas_dysfunc']='Orgasmic function';
Pond_Lang['list_ctcae_event.sex_repro-vaginal_discharge']='Vaginal discharge';
Pond_Lang['list_ctcae_event.sex_repro-vaginal_dry']='Vaginal dryness';
Pond_Lang['list_ctcae_event.sex_repro-vaginal_mucositis']='Vaginal mucositis';
Pond_Lang['list_ctcae_event.sex_repro-vaginal_stenosis']='Vaginal stenosis';
Pond_Lang['list_ctcae_event.sex_repro-vaginitis']='Vaginitis';
Pond_Lang['list_ctcae_event.sex_repro-other']='Sexual -- Other (Specify)';
Pond_Lang['list_ctcae_event.surg_injury-intraop_inj']='Intraop injury';
Pond_Lang['list_ctcae_event.surg_injury-other']='Intraop Injury -- Other (Specify)';
Pond_Lang['list_ctcae_event.synd-alcohol_intol']='Alcohol intolerance syndrome';
Pond_Lang['list_ctcae_event.synd-cytokine_release']='Cytokine release syndrome';
Pond_Lang['list_ctcae_event.synd-flu_like']='Flu-like syndrome';
Pond_Lang['list_ctcae_event.synd-retinoic_acid']='Retinoic acid syndrome';
Pond_Lang['list_ctcae_event.synd-tumor_flare']='Tumor flare';
Pond_Lang['list_ctcae_event.synd-tumor_lysis']='Tumor lysis syndrome';
Pond_Lang['list_ctcae_event.synd-other']='Syndromes -- Other (Specify)';
Pond_Lang['list_ctcae_event.vasc-acute_vasc_leak']='Acute vascular leak syndrome';
Pond_Lang['list_ctcae_event.vasc-periph_arter_ischemia']='Peripheral arterial ischemia';
Pond_Lang['list_ctcae_event.vasc-phlebitis']='Phlebitis';
Pond_Lang['list_ctcae_event.vasc-portal_flow']='Portal flow';
Pond_Lang['list_ctcae_event.vasc-thrombosis_emb_vascular']='Thrombosis/embolism (vascular access)';
Pond_Lang['list_ctcae_event.vasc-thrombosis_thrombus_emb']='Thrombosis/thrombus/embolism';
Pond_Lang['list_ctcae_event.vasc-vess_inj_artery']='Artery injury';
Pond_Lang['list_ctcae_event.vasc-vess_inj_vein']='Vein injury';
Pond_Lang['list_ctcae_event.vasc-visc_artery_ischemia']='Visceral arterial ischemia';
Pond_Lang['list_ctcae_event.vasc-other']='Vascular -- Other (Specify)';
Pond_Lang['list_ctcae_event.transreact-febrile']='Febrile Asymptomatic';
Pond_Lang['list_ctcae_event.transreact-allergic']='Allergic';
Pond_Lang['list_ctcae_event.transreact-inflammatory']='Inflammatory';
Pond_Lang['list_ctcae_event.transreact-mixed_allergic_inflam']='Mixed allergic/ Inflammatory';
Pond_Lang['list_ctcae_event.transreact-trali']='TRALI';
Pond_Lang['list_ctcae_event.transreact-hypotension']='Hypotension';
Pond_Lang['list_ctcae_event.transreact-hemolysis']='Hemolysis (specify immune or nonimmune)';
Pond_Lang['list_ctcae_event.transreact-sepsis']='Transfusion-associated sepsis';
Pond_Lang['list_ctcae_event.transreact-circulatory_overload']='Circulatory overload';
Pond_Lang['list_ctcae_supra.asystole']='Asystole';
Pond_Lang['list_ctcae_supra.av_block_first']='AV Block-First degree';
Pond_Lang['list_ctcae_supra.av_block_second_type_I']='AV Block-Second degree Mobitz Type I (Wenckebach)';
Pond_Lang['list_ctcae_supra.av_block_second_type_II']='AV Block-Second degree Mobitz Type II';
Pond_Lang['list_ctcae_supra.av_block_complete']='AV Block-Third degree (Complete AV block)';
Pond_Lang['list_ctcae_supra.conduct_abnorm_nos']='Conduction abnormality NOS';
Pond_Lang['list_ctcae_supra.sick_sinus']='Sick Sinus Syndrome';
Pond_Lang['list_ctcae_supra.stokes_adams']='Stokes-Adams Syndrome';
Pond_Lang['list_ctcae_supra.wolff_park_white']='Wolff-Parkinson-White Syndrome';
Pond_Lang['list_ctcae_supra.atrial_fibril']='Atrial fibrillation';
Pond_Lang['list_ctcae_supra.atrial_flut']='Atrial flutter';
Pond_Lang['list_ctcae_supra.atrial_tachyc']='Atrial tachycardia/Paroxysmal Atrial Tachycardia';
Pond_Lang['list_ctcae_supra.nodal_junc']='Nodal/Junctional';
Pond_Lang['list_ctcae_supra.sinus_arrhythm']='Sinus arrhythmia';
Pond_Lang['list_ctcae_supra.sinus_brady']='Sinus bradycardia';
Pond_Lang['list_ctcae_supra.sinus_tachyc']='Sinus tachycardia';
Pond_Lang['list_ctcae_supra.supravent_arrhythm_nos']='Supraventricular arrhythmia NOS';
Pond_Lang['list_ctcae_supra.supravent_extrasys']='Supraventricular extrasystoles (Premature Atrial Contractions; Premature Nodal/Junctional Contractions)';
Pond_Lang['list_ctcae_supra.supravent_tachyc']='Supraventricular tachycardia';
Pond_Lang['list_ctcae_supra.bigeminy']='Bigeminy';
Pond_Lang['list_ctcae_supra.idioventri_rhythm']='Idioventricular rhythm';
Pond_Lang['list_ctcae_supra.pvcs']='PVCs';
Pond_Lang['list_ctcae_supra.torsade_pointes']='Torsade de pointes';
Pond_Lang['list_ctcae_supra.trigeminy']='Trigeminy';
Pond_Lang['list_ctcae_supra.vent_arrhythm_nos']='Ventricular arrhythmia NOS';
Pond_Lang['list_ctcae_supra.vent_fibiril']='Ventricular fibrillation';
Pond_Lang['list_ctcae_supra.vent_flutter']='Ventricular flutter';
Pond_Lang['list_ctcae_supra.vent_tachyc']='Ventricular tachycardia';
Pond_Lang['list_ctcae_supra.death_nos']='Death NOS';
Pond_Lang['list_ctcae_supra.disease_prog_nos']='Disease progression NOS';
Pond_Lang['list_ctcae_supra.multiorgan_fail']='Multi-organ failure';
Pond_Lang['list_ctcae_supra.sudden_death']='Sudden death';
Pond_Lang['list_ctcae_supra.chemoradiation']='Chemoradiation';
Pond_Lang['list_ctcae_supra.radiation']='Radiation';
Pond_Lang['list_ctcae_supra.abdomen_nos']='Abdomen NOS';
Pond_Lang['list_ctcae_supra.anus']='Anus';
Pond_Lang['list_ctcae_supra.bilitree']='Biliary tree';
Pond_Lang['list_ctcae_supra.colon_cecum_appendix']='Colon/cecum/appendix';
Pond_Lang['list_ctcae_supra.duodenum']='Duodenum';
Pond_Lang['list_ctcae_supra.esophagus']='Esophagus';
Pond_Lang['list_ctcae_supra.gallbladder']='Gallbladder';
Pond_Lang['list_ctcae_supra.ileum']='Ileum';
Pond_Lang['list_ctcae_supra.jejunum']='Jejunum';
Pond_Lang['list_ctcae_supra.oral_cavity']='Oral cavity';
Pond_Lang['list_ctcae_supra.pancreas']='Pancreas';
Pond_Lang['list_ctcae_supra.pharynx']='Pharynx';
Pond_Lang['list_ctcae_supra.rectum']='Rectum';
Pond_Lang['list_ctcae_supra.salivary_gland']='Salivary gland';
Pond_Lang['list_ctcae_supra.small_bowel_nos']='Small bowel NOS';
Pond_Lang['list_ctcae_supra.stomach']='Stomach';
Pond_Lang['list_ctcae_supra.large_bowel']='Large bowel';
Pond_Lang['list_ctcae_supra.leak_nos']='Leak NOS';
Pond_Lang['list_ctcae_supra.small_bowel']='Small bowel';
Pond_Lang['list_ctcae_supra.stoma']='Stoma';
Pond_Lang['list_ctcae_supra.larynx']='Larynx';
Pond_Lang['list_ctcae_supra.trachea']='Trachea';
Pond_Lang['list_ctcae_supra.hepatic']='Hepatic';
Pond_Lang['list_ctcae_supra.oral']='Oral';
Pond_Lang['list_ctcae_supra.peritoneal_cavity']='Peritoneal cavity';
Pond_Lang['list_ctcae_supra.cecum']='Cecum';
Pond_Lang['list_ctcae_supra.colon']='Colon';
Pond_Lang['list_ctcae_supra.appendix']='Appendix';
Pond_Lang['list_ctcae_supra.pancreas_duct']='Pancreas/pancreatic duct';
Pond_Lang['list_ctcae_supra.cecum_appendix']='Cecum/appendix';
Pond_Lang['list_ctcae_supra.liver']='Liver';
Pond_Lang['list_ctcae_supra.lower_GI_nos']='Lower GI NOS';
Pond_Lang['list_ctcae_supra.upper_GI_nos']='Upper GI NOS';
Pond_Lang['list_ctcae_supra.varices_esophag']='Varices (esophageal)';
Pond_Lang['list_ctcae_supra.varices_rectal']='Varices (rectal)';
Pond_Lang['list_ctcae_supra.bladder']='Bladder';
Pond_Lang['list_ctcae_supra.fallopian_tube']='Fallopian tube';
Pond_Lang['list_ctcae_supra.kidney']='Kidney';
Pond_Lang['list_ctcae_supra.ovary']='Ovary';
Pond_Lang['list_ctcae_supra.prostate']='Prostate';
Pond_Lang['list_ctcae_supra.retroperitoneum']='Retroperitoneum';
Pond_Lang['list_ctcae_supra.spermatic_cord']='Spermatic cord';
Pond_Lang['list_ctcae_supra.testes']='Testes';
Pond_Lang['list_ctcae_supra.ureter']='Ureter';
Pond_Lang['list_ctcae_supra.urethra']='Urethra';
Pond_Lang['list_ctcae_supra.urinary_nos']='Urinary NOS';
Pond_Lang['list_ctcae_supra.uterus']='Uterus';
Pond_Lang['list_ctcae_supra.vagina']='Vagina';
Pond_Lang['list_ctcae_supra.vas_deferens']='Vas deferens';
Pond_Lang['list_ctcae_supra.bronchopulmn_nos']='Bronchopulmonary NOS';
Pond_Lang['list_ctcae_supra.bronchus']='Bronchus';
Pond_Lang['list_ctcae_supra.lung']='Lung';
Pond_Lang['list_ctcae_supra.mediastinum']='Mediastinum';
Pond_Lang['list_ctcae_supra.nose']='Nose';
Pond_Lang['list_ctcae_supra.pleura']='Pleura';
Pond_Lang['list_ctcae_supra.respir_tract_nos']='Respiratory tract NOS';
Pond_Lang['list_ctcae_supra.external_ear_otitis']='External ear (otitis externa)';
Pond_Lang['list_ctcae_supra.middle_ear_otitis']='Middle ear (otitis media)';
Pond_Lang['list_ctcae_supra.artery']='Artery';
Pond_Lang['list_ctcae_supra.heart_endocard']='Heart (endocarditis)';
Pond_Lang['list_ctcae_supra.spleen']='Spleen';
Pond_Lang['list_ctcae_supra.vein']='Vein';
Pond_Lang['list_ctcae_supra.lip_perioral']='Lip/perioral';
Pond_Lang['list_ctcae_supra.peristomal']='Peristomal';
Pond_Lang['list_ctcae_supra.cellulitis']='Skin (cellulitis)';
Pond_Lang['list_ctcae_supra.ungual_nails']='Ungual (nails)';
Pond_Lang['list_ctcae_supra.anal_perianal']='Anal/perianal';
Pond_Lang['list_ctcae_supra.dental_tooth']='Dental-tooth';
Pond_Lang['list_ctcae_supra.oral_cav_gingivitis']='Oral cavity-gums (gingivitis)';
Pond_Lang['list_ctcae_supra.blood']='Blood';
Pond_Lang['list_ctcae_supra.cathether_rel']='Catheter-related';
Pond_Lang['list_ctcae_supra.foreign_body']='Foreign body (e.g., graft, implant, prosthesis, stent)';
Pond_Lang['list_ctcae_supra.wound']='Wound';
Pond_Lang['list_ctcae_supra.gallbladder_cholecyst']='Gallbladder (cholecystitis)';
Pond_Lang['list_ctcae_supra.lymphatic']='Lymphatic';
Pond_Lang['list_ctcae_supra.bone_osteomyel']='Bone (osteomyelitis)';
Pond_Lang['list_ctcae_supra.joint']='Joint';
Pond_Lang['list_ctcae_supra.muscle_myositis']='Muscle (infection myositis)';
Pond_Lang['list_ctcae_supra.soft_tissue_nos']='Soft tissue NOS';
Pond_Lang['list_ctcae_supra.brain_encep_infec']='Brain (encephalitis, infectious)';
Pond_Lang['list_ctcae_supra.brain_spinal_encephal']='Brain + Spinal cord (encephalomyelitis)';
Pond_Lang['list_ctcae_supra.meninges_meningitis']='Meninges (meningitis)';
Pond_Lang['list_ctcae_supra.nerve_cranial']='Nerve-cranial';
Pond_Lang['list_ctcae_supra.nerve_peripheral']='Nerve-peripheral';
Pond_Lang['list_ctcae_supra.spinal_cord_myelitis']='Spinal cord (myelitis)';
Pond_Lang['list_ctcae_supra.conjunctiva']='Conjunctiva';
Pond_Lang['list_ctcae_supra.cornea']='Cornea';
Pond_Lang['list_ctcae_supra.eye_nos']='Eye NOS';
Pond_Lang['list_ctcae_supra.lens']='Lens';
Pond_Lang['list_ctcae_supra.lung_pneumonia']='Lung (pneumonia)';
Pond_Lang['list_ctcae_supra.mediastinum_nos']='Mediastinum NOS';
Pond_Lang['list_ctcae_supra.mucosa']='Mucosa';
Pond_Lang['list_ctcae_supra.neck_nos']='Neck NOS';
Pond_Lang['list_ctcae_supra.paranasal']='Paranasal';
Pond_Lang['list_ctcae_supra.pleura_empyema']='Pleura (empyema)';
Pond_Lang['list_ctcae_supra.sinus']='Sinus';
Pond_Lang['list_ctcae_supra.upper_aerodigest_nos']='Upper aerodigestive NOS';
Pond_Lang['list_ctcae_supra.upper_airway_nos']='Upper airway NOS';
Pond_Lang['list_ctcae_supra.bladder_urine']='Bladder (urinary)';
Pond_Lang['list_ctcae_supra.urinary_tract_nos']='Urinary tract NOS';
Pond_Lang['list_ctcae_supra.cervix']='Cervix';
Pond_Lang['list_ctcae_supra.pelvis_nos']='Pelvis NOS';
Pond_Lang['list_ctcae_supra.penis']='Penis';
Pond_Lang['list_ctcae_supra.scrotum']='Scrotum';
Pond_Lang['list_ctcae_supra.vulva']='Vulva';
Pond_Lang['list_ctcae_supra.extraocular']='Extraocular';
Pond_Lang['list_ctcae_supra.extremity_lower']='Extremity-lower';
Pond_Lang['list_ctcae_supra.extremity_upper']='Extremity-upper';
Pond_Lang['list_ctcae_supra.facial']='Facial';
Pond_Lang['list_ctcae_supra.left_sided']='Left-sided';
Pond_Lang['list_ctcae_supra.ocular']='Ocular';
Pond_Lang['list_ctcae_supra.pelvis']='Pelvic';
Pond_Lang['list_ctcae_supra.right_sided']='Right-sided';
Pond_Lang['list_ctcae_supra.trunk']='Trunk';
Pond_Lang['list_ctcae_supra.whole_body_general']='Whole body/generalized';
Pond_Lang['list_ctcae_supra.abdomen']='Abdomen';
Pond_Lang['list_ctcae_supra.head']='Head';
Pond_Lang['list_ctcae_supra.neck']='Neck';
Pond_Lang['list_ctcae_supra.pelvic']='Pelvic';
Pond_Lang['list_ctcae_supra.thorax']='Thorax';
Pond_Lang['list_ctcae_supra.agitation']='Agitation';
Pond_Lang['list_ctcae_supra.anxiety']='Anxiety';
Pond_Lang['list_ctcae_supra.depression']='Depression';
Pond_Lang['list_ctcae_supra.euphoria']='Euphoria';
Pond_Lang['list_ctcae_supra.cn_i_smell']='CN I Smell';
Pond_Lang['list_ctcae_supra.cn_ii_vision']='CN II Vision';
Pond_Lang['list_ctcae_supra.cn_iii_pupil']='CN III Pupil, upper eyelid, extra ocular movements';
Pond_Lang['list_ctcae_supra.cn_iv_down_eye']='CN IV Downward, inward movement of eye';
Pond_Lang['list_ctcae_supra.cn_v_mot_musc_face']='CN V Motor-jaw muscles; Sensory-facial';
Pond_Lang['list_ctcae_supra.cn_vi_lateral_eye']='CN VI Lateral deviation of eye';
Pond_Lang['list_ctcae_supra.cn_vii_mot_face_taste']='CN VII Motor-face; Sensory-taste';
Pond_Lang['list_ctcae_supra.cn_viii_hear_balance']='CN VIII Hearing and balance';
Pond_Lang['list_ctcae_supra.cn_ix_mot_pharynx_ear_tongue']='CN IX Motor-pharynx; Sensory-ear, pharynx, tongue';
Pond_Lang['list_ctcae_supra.cn_x_mot_palate_pharynx_larynx']='CN X Motor-palate; pharynx, larynx';
Pond_Lang['list_ctcae_supra.cn_xi_mot_sternomast_trapez']='CN XI Motor-sternomastoid and trapezius';
Pond_Lang['list_ctcae_supra.cn_xii_tongue']='CN XII Motor-tongue';
Pond_Lang['list_ctcae_supra.external_ear']='External ear';
Pond_Lang['list_ctcae_supra.middle_ear']='Middle ear';
Pond_Lang['list_ctcae_supra.cardiac_heart']='Cardiac/heart';
Pond_Lang['list_ctcae_supra.pericardium']='Pericardium';
Pond_Lang['list_ctcae_supra.face']='Face';
Pond_Lang['list_ctcae_supra.lip']='Lip';
Pond_Lang['list_ctcae_supra.oral_gums']='Oral-gums';
Pond_Lang['list_ctcae_supra.scalp']='Scalp';
Pond_Lang['list_ctcae_supra.skin']='Skin';
Pond_Lang['list_ctcae_supra.dental_teeth_periodon']='Dental/teeth/peridontal';
Pond_Lang['list_ctcae_supra.peritoneum']='Peritoneum';
Pond_Lang['list_ctcae_supra.pain_nos']='Pain NOS';
Pond_Lang['list_ctcae_supra.tumor_pain']='Tumor pain';
Pond_Lang['list_ctcae_supra.lymph_node']='Lymph node';
Pond_Lang['list_ctcae_supra.back']='Back';
Pond_Lang['list_ctcae_supra.bone']='Bone';
Pond_Lang['list_ctcae_supra.buttock']='Buttock';
Pond_Lang['list_ctcae_supra.extremity_limb']='Extremity-limb';
Pond_Lang['list_ctcae_supra.intestine']='Intestine';
Pond_Lang['list_ctcae_supra.muscle']='Muscle';
Pond_Lang['list_ctcae_supra.phantom_limb_pain']='Phantom (pain associated with missing limb)';
Pond_Lang['list_ctcae_supra.head_headache']='Head/headache';
Pond_Lang['list_ctcae_supra.neuralgia_periph_nerve']='Neuralgia/peripheral nerve';
Pond_Lang['list_ctcae_supra.eye']='Eye';
Pond_Lang['list_ctcae_supra.chest_wall']='Chest wall';
Pond_Lang['list_ctcae_supra.chest_thorax_nos']='Chest/thorax NOS';
Pond_Lang['list_ctcae_supra.throat_pharynx_larynx']='Throat/pharynx/larynx';
Pond_Lang['list_ctcae_supra.breast']='Breast';
Pond_Lang['list_ctcae_supra.ovulatory']='Ovulatory';
Pond_Lang['list_ctcae_supra.perineum']='Perineum';
Pond_Lang['list_ctcae_supra.testicle']='Testicle';
Pond_Lang['list_ctcae_supra.genital_tract_female']='Genital tract-female';
Pond_Lang['list_ctcae_supra.inner_ear']='Inner ear';
Pond_Lang['list_ctcae_supra.outer_ear_nos']='Outer ear NOS';
Pond_Lang['list_ctcae_supra.outer_ear_pinna']='Outer ear-Pinna';
Pond_Lang['list_ctcae_supra.artery_aorta']='Artery-aorta';
Pond_Lang['list_ctcae_supra.artery_carotid']='Artery-carotid';
Pond_Lang['list_ctcae_supra.artery_cerebral']='Artery-cerebral';
Pond_Lang['list_ctcae_supra.artery_extrem_lower']='Artery-extremity (lower)';
Pond_Lang['list_ctcae_supra.artery_extrem_upper']='Artery-extremity (upper)';
Pond_Lang['list_ctcae_supra.artery_hepatic']='Artery-hepatic';
Pond_Lang['list_ctcae_supra.artery_major_visceral']='Artery-major visceral artery';
Pond_Lang['list_ctcae_supra.artery_pulmonary']='Artery-pulmonary';
Pond_Lang['list_ctcae_supra.artery_nos']='Artery NOS';
Pond_Lang['list_ctcae_supra.heart']='Heart';
Pond_Lang['list_ctcae_supra.vein_extrem_lower']='Vein-extremity (lower)';
Pond_Lang['list_ctcae_supra.vein_extrem_upper']='Vein-extremity (upper)';
Pond_Lang['list_ctcae_supra.vein_hepatic']='Vein-hepatic';
Pond_Lang['list_ctcae_supra.vein_inferior']='Vein-inferior vena cava';
Pond_Lang['list_ctcae_supra.vein_jugular']='Vein-jugular';
Pond_Lang['list_ctcae_supra.vein_major_visc']='Vein-major visceral vein';
Pond_Lang['list_ctcae_supra.vein_portal']='Vein-portal vein';
Pond_Lang['list_ctcae_supra.vein_pulmon']='Vein-pulmonary';
Pond_Lang['list_ctcae_supra.vein_super_vena_cava']='Vein-superior vena cava';
Pond_Lang['list_ctcae_supra.vein_nos']='Vein NOS';
Pond_Lang['list_ctcae_supra.nails']='Nails';
Pond_Lang['list_ctcae_supra.adrenal_gland']='Adrenal gland';
Pond_Lang['list_ctcae_supra.parathyroid']='Parathyroid';
Pond_Lang['list_ctcae_supra.pituitary']='Pituitary';
Pond_Lang['list_ctcae_supra.thyroid']='Thyroid';
Pond_Lang['list_ctcae_supra.gingiva']='Gingiva';
Pond_Lang['list_ctcae_supra.face_nos']='Face NOS';
Pond_Lang['list_ctcae_supra.nasal_cavity']='Nasal cavity';
Pond_Lang['list_ctcae_supra.nasopharynx']='Nasopharynx';
Pond_Lang['list_ctcae_supra.oral_cavity_nos']='Oral cavity NOS';
Pond_Lang['list_ctcae_supra.parotid_gland']='Parotid gland';
Pond_Lang['list_ctcae_supra.salivary_duct']='Salivary duct';
Pond_Lang['list_ctcae_supra.teeth']='Teeth';
Pond_Lang['list_ctcae_supra.tongue']='Tongue';
Pond_Lang['list_ctcae_supra.anal_sphincter']='Anal sphincter';
Pond_Lang['list_ctcae_supra.stoma_GI']='Stoma (GI)';
Pond_Lang['list_ctcae_supra.bilitree_common_bile_duct']='Biliary tree-common bile duct';
Pond_Lang['list_ctcae_supra.bilitree_common_hepat_duct']='Biliary tree-common hepatic duct';
Pond_Lang['list_ctcae_supra.bilitree_left_hepat_duct']='Biliary tree-left hepatic duct';
Pond_Lang['list_ctcae_supra.bilitree_right_hepat_duct']='Biliary tree-right hepatic duct';
Pond_Lang['list_ctcae_supra.bilitree_nos']='Biliary tree NOS';
Pond_Lang['list_ctcae_supra.pancreatic_duct']='Pancreatic duct';
Pond_Lang['list_ctcae_supra.cartilage']='Cartilage';
Pond_Lang['list_ctcae_supra.ligament']='Ligament';
Pond_Lang['list_ctcae_supra.tendon']='Tendon';
Pond_Lang['list_ctcae_supra.brain']='Brain';
Pond_Lang['list_ctcae_supra.meninges']='Meninges';
Pond_Lang['list_ctcae_supra.spinal_cord']='Spinal cord';
Pond_Lang['list_ctcae_supra.brachial_plexus']='Brachial plexus';
Pond_Lang['list_ctcae_supra.nerv-cn_i_olfact']='CN I (olfactory)';
Pond_Lang['list_ctcae_supra.nerv-cn_ii_optic']='CN II (optic)';
Pond_Lang['list_ctcae_supra.nerv-cn_iii_oculo']='CN III (oculomotor)';
Pond_Lang['list_ctcae_supra.nerv-cn_iv_troch']='CN IV (trochlear)';
Pond_Lang['list_ctcae_supra.nerv-cn_v_trige_motor']='CN V (trigeminal) motor';
Pond_Lang['list_ctcae_supra.nerv-cn_v_trige_sensor']='CN V (trigeminal) sensory';
Pond_Lang['list_ctcae_supra.nerv-cn_vi_abducen']='CN VI (abducens)';
Pond_Lang['list_ctcae_supra.nerv-cn_vii_facial_motor']='CN VII (facial) motor-face';
Pond_Lang['list_ctcae_supra.nerv-cn_vii_facial_sensor']='CN VII (facial) sensorytaste';
Pond_Lang['list_ctcae_supra.nerv-cn_viii_vestibulococh']='CN VIII (vestibulocochlear)';
Pond_Lang['list_ctcae_supra.nerv-cn_ix_motor_pharynx']='CN IX (glossopharyngeal) motor pharynx';
Pond_Lang['list_ctcae_supra.nerv-cn_ix_sensor_ear_tongue']='CN IX (glossopharyngeal) sensory ear-pharynxtongue';
Pond_Lang['list_ctcae_supra.nerv-cn_x_vagus']='CN X (vagus)';
Pond_Lang['list_ctcae_supra.nerv-cn_xi_spinal']='CN XI (spinal accessory)';
Pond_Lang['list_ctcae_supra.nerv-cn_xii_hypogloss']='CN XII (hypoglossal)';
Pond_Lang['list_ctcae_supra.nerv-cranial_branch_nos']='Cranial nerve or branch NOS';
Pond_Lang['list_ctcae_supra.nerv-lingual']='Lingual';
Pond_Lang['list_ctcae_supra.nerv-lung_thoracic']='Lung thoracic';
Pond_Lang['list_ctcae_supra.nerv-periph_motor_nos']='Peripheral motor NOS';
Pond_Lang['list_ctcae_supra.nerv-periph_sensor_nos']='Peripheral sensory NOS';
Pond_Lang['list_ctcae_supra.recurrent_laryngeal']='Recurrent laryngeal';
Pond_Lang['list_ctcae_supra.sacral_plexus']='Sacral plexus';
Pond_Lang['list_ctcae_supra.sciatic']='Sciatic';
Pond_Lang['list_ctcae_supra.thoracodorsal']='Thoracodorsal';
Pond_Lang['list_ctcae_supra.retina']='Retina';
Pond_Lang['list_ctcae_supra.thoracic_duct']='Thoracic duct';
Pond_Lang['list_ctcae_supra.testis']='Testis';
Pond_Lang['list_ctcae_supra.urinary_conduit']='Urinary conduit';
Pond_Lang['list_ctcae_supra.aorta']='Aorta';
Pond_Lang['list_ctcae_supra.carotid']='Carotid';
Pond_Lang['list_ctcae_supra.other_nos']='Other NOS';
Pond_Lang['list_ctcae_supra.visceral']='Visceral';
Pond_Lang['list_ctcae_supra.ivc']='Inferior vena cava';
Pond_Lang['list_ctcae_supra.jugular']='Jugular';
Pond_Lang['list_ctcae_supra.svc']='Superior vena cava';
Pond_Lang['list_ctcae_supra.viscera']='Viscera';
Pond_Lang['list_ctcae_supra_cat.aud_ear']='AUDITORY/EAR';
Pond_Lang['list_ctcae_supra_cat.card']='CARDIOVASCULAR';
Pond_Lang['list_ctcae_supra_cat.derm_skin']='DERMATOLOGY/SKIN';
Pond_Lang['list_ctcae_supra_cat.gastro']='GASTROINTESTINAL';
Pond_Lang['list_ctcae_supra_cat.general']='GENERAL';
Pond_Lang['list_ctcae_supra_cat.hepa_panc']='HEPATOBILIARY/PANCREAS';
Pond_Lang['list_ctcae_supra_cat.lymph']='LYMPHATIC';
Pond_Lang['list_ctcae_supra_cat.muscskel']='MUSCULOSKELETAL';
Pond_Lang['list_ctcae_supra_cat.neuro']='NEUROLOGY';
Pond_Lang['list_ctcae_supra_cat.ocular']='OCULAR';
Pond_Lang['list_ctcae_supra_cat.pulm_uresp']='PULMONARY/UPPER RESPIRATORY';
Pond_Lang['list_ctcae_supra_cat.renal_geni']='RENAL/GENITOURINARY';
Pond_Lang['list_ctcae_supra_cat.sex_repro']='SEXUAL/REPRODUCTIVE FUNCTION';
Pond_Lang['list_ctcae_supra_cat.endocrine']='ENDOCRINE';
Pond_Lang['list_ctcae_supra_cat.head_neck']='HEAD AND NECK';
Pond_Lang['list_ctcae_supra_cat.nerve']='NERVES';
Pond_Lang['list_histology.burkit_lymp']='Burkitt lymphoma';
Pond_Lang['list_histology.fab_l1']='FAB L1';
Pond_Lang['list_histology.fab_l2']='FAB L2';
Pond_Lang['list_histology.fab_l3']='FAB L3';
Pond_Lang['list_histology.unclass']='Unclassifiable';
Pond_Lang['list_histology.aml_m0']='AML M0';
Pond_Lang['list_histology.aml_m1']='AML M1';
Pond_Lang['list_histology.aml_m2']='AML M2';
Pond_Lang['list_histology.aml_m3']='AML M3';
Pond_Lang['list_histology.aml_m4']='AML M4';
Pond_Lang['list_histology.aml_m5']='AML M5';
Pond_Lang['list_histology.aml_m6']='AML M6';
Pond_Lang['list_histology.aml_m7']='AML M7';
Pond_Lang['list_histology.acute_bilineage_leuk']='Acute bilineage leukemia (ALL and AML)';
Pond_Lang['list_histology.acute_undiff_leuk']='Acute undifferentiated leukemia';
Pond_Lang['list_histology.acute_leuk_unclass']='Acute leukemia, unclassifiable';
Pond_Lang['list_histology.chronic_lymph_leuk']='Chronic lymphocytic leukemia';
Pond_Lang['list_histology.chronic_mye_leuk']='Chronic myeloid leukemia';
Pond_Lang['list_histology.nod_sclerosing']='Nodular Sclerosing';
Pond_Lang['list_histology.lymp_predom']='Lymphocyte Predominance';
Pond_Lang['list_histology.mixed_cell']='Mixed Cellularity';
Pond_Lang['list_histology.lymp_deple']='Lymphocyte Depletion';
Pond_Lang['list_histology.b_clc_lymp']='B-Cell large cell lymphoma';
Pond_Lang['list_histology.lympho_lymp']='Lymphoblastic Lymphoma';
Pond_Lang['list_histology.anap_lymp']='Anaplastic large cell lymphoma';
Pond_Lang['list_histology.wilms_fav']='Favorable Histology';
Pond_Lang['list_histology.wilms_fav_nuclear']='Favorable Histology with Nuclear Unrest';
Pond_Lang['list_histology.wilms_anap']='Anaplastic Histology';
Pond_Lang['list_histology.rhab_tumor']='Rhabdoid Tumor';
Pond_Lang['list_histology.cc_sarcoma']='Clear cell sarcoma';
Pond_Lang['list_histology.renal_c_carc']='Renal Cell Carcinoma';
Pond_Lang['list_histology.meso_neph']='Mesoblastic Nephroma';
Pond_Lang['list_histology.hep_carc']='Hepatocellular Carcinoma';
Pond_Lang['list_histology.hep']='Hepatoblastoma';
Pond_Lang['list_histology.hep_fibro']='Hepatoblastoma, Fibrolamellar';
Pond_Lang['list_histology.alvelar_rhab']='Alveolar rhabdomyosarcoma';
Pond_Lang['list_histology.embryonal_rhab']='Embryonal rhabdomyosarcoma';
Pond_Lang['list_histology.botryoidal']='Botryoidal';
Pond_Lang['list_histology.pleomorphic']='Pleomorphic';
Pond_Lang['list_histology.undiff']='Undifferentiated';
Pond_Lang['list_histology.synovial_sarc']='Synovial Sarcoma';
Pond_Lang['list_histology.malig_fib']='Malignant Fibrous Histiocytoma';
Pond_Lang['list_histology.malig_pns_tumor']='Malignant Peripheral Nerve Sheath Tumor';
Pond_Lang['list_histology.fibro']='Fibrosarcoma';
Pond_Lang['list_histology.leiomyo_sarc']='Leiomyosarcoma';
Pond_Lang['list_histology.epi_sarc']='Epithelioid sarcoma';
Pond_Lang['list_histology.alvelar_sarc']='Alveolar soft part sarcoma';
Pond_Lang['list_histology.hemangioperi']='Hemangiopericytoma';
Pond_Lang['list_histology.oth']='Other';
Pond_Lang['list_histology.osteo']='Osteoblastic';
Pond_Lang['list_histology.chondro']='Chondroblastic';
Pond_Lang['list_histology.fibroblast']='Fibroblastic';
Pond_Lang['list_histology.telangiectatic']='Telangiectatic';
Pond_Lang['list_histology.small_cell']='Small cell';
Pond_Lang['list_histology.parsteal']='Parosteal';
Pond_Lang['list_histology.periosteal']='Periosteal';
Pond_Lang['list_histology.chondro_sarc']='Chondrosarcoma';
Pond_Lang['list_histology.ewing_sarc_bone']='Ewing Sarcoma, Bone';
Pond_Lang['list_histology.ewing_sarc_stissue']='Ewing Sarcoma, Soft Tissue';
Pond_Lang['list_histology.askin_tumor_st']='Soft tissue - Askin tumor';
Pond_Lang['list_histology.extra_ewing_st']='Soft tissue - Extraosseous Ewing\'s';
Pond_Lang['list_histology.desmo_sctumor_st']='Soft tissue - Desmoplastic Small Cell Tumor';
Pond_Lang['list_histology.mature_teratoma']='Mature Teratoma';
Pond_Lang['list_histology.immature_teratoma_ib']='Indeterminate Behavior - Immature Teratoma';
Pond_Lang['list_histology.malig_germinoma']='Malignant Germinoma';
Pond_Lang['list_histology.yolk_sac_carc']='Yolk Sac Carcinoma (Endodermal Sinus Tumor)';
Pond_Lang['list_histology.embryonal_carc']='Embryonal carcinoma';
Pond_Lang['list_histology.chorio_carc']='Choriocarcinoma';
Pond_Lang['list_histology.malig_gct_mixed']='Mixed Malignant Germ Cell Tumor';
Pond_Lang['list_histology.astro_nos']='Astrocytic, NOS';
Pond_Lang['list_histology.astro_px']='Astrocytic-pleomorphic xanthoastrocytoma';
Pond_Lang['list_histology.astro_ca']='Astrocytic-desmoplastic cerebral astrocytoma of infancy';
Pond_Lang['list_histology.astro_sgc']='Astrocytic-subependymal giant cell astrocytoma';
Pond_Lang['list_histology.astro_fib_astrocy_inf']='Astrocytic- fibrillary astrocytoma, infantile';
Pond_Lang['list_histology.astro_fib_astrocy_w2']='Astrocytic-fibrillary astrocytoma (WHO II)';
Pond_Lang['list_histology.astro_fib_anp_w3']='Astrocytic-fibrillary anaplastic astrocytoma (WHO III)';
Pond_Lang['list_histology.astro_fib_glioblast_w4']='Astrocytic-fibrillary glioblastoma multiforme (WHO IV)';
Pond_Lang['list_histology.oligo_oligo_w2']='Oligodendroglial-Oligodendroglioma (WHO II)';
Pond_Lang['list_histology.oligo_anap_oligo_w3']='Oligodendroglial-Anaplastic oligodendroglioma (WHO III)';
Pond_Lang['list_histology.mixed_glial_oligo_w2']='Mixed Glial-Oligoastrocytoma (WHO II)';
Pond_Lang['list_histology.mixed_glial_anp_oligo_w3']='Mixed Glial-Anaplastic Oligoastrocytoma (WHO III)';
Pond_Lang['list_histology.choroid_plexus_papi']='Choroid plexus-papilloma';
Pond_Lang['list_histology.choroid_plexus_carc']='Choroid plexus carcinoma';
Pond_Lang['list_histology.epen_epen_w2']='Ependymal-ependymoma (WHO II)';
Pond_Lang['list_histology.epen_anap_epen_w3']='Ependymal-anaplastic ependymoma (WHO III)';
Pond_Lang['list_histology.epen_epenblast_tumor']='Ependymal-ependymoblastoma (embryonal tumor)';
Pond_Lang['list_histology.epen_myxo_epen']='Ependymal-Myxopapillary Ependymoma';
Pond_Lang['list_histology.epen_subepen']='Ependymal - Subependymoma';
Pond_Lang['list_histology.neuronal_cerebral_gang']='Neuronal - Cerebral Neuroblastoma/Ganglioneuroblastoma';
Pond_Lang['list_histology.neuronal_central_neuro']='Neuronal - Central Neurocytoma';
Pond_Lang['list_histology.neuronal_pine']='Neuronal - Pineocytoma';
Pond_Lang['list_histology.neuronal_gang_w1']='Neuronal/Glial-Gangliocytoma (WHO I)';
Pond_Lang['list_histology.neuronal_gang_w2']='Neuronal/Glial-Gangliocytoma (WHO II)';
Pond_Lang['list_histology.neuronal_anap_gang_w3']='Neuronal/Glial-Anaplastic Ganglioglioma (WHO III)';
Pond_Lang['list_histology.neuronal_des_inf_gang']='Neuronal/Glial-Desmoplastic Infantile Ganglioglioma';
Pond_Lang['list_histology.neuronal_dys_neuro_tumor']='Neuronal/Glial-Dysembryoplastic Neuroepithelial Tumor';
Pond_Lang['list_histology.emb_pine']='Embryonal (PNET) - pineoblastoma';
Pond_Lang['list_histology.emb_mixed']='Embryonal (PNET) - mixed pineocytoma/pineoblastoma';
Pond_Lang['list_histology.emb_medepi']='Embryonal (PNET) - medulloepithelioma';
Pond_Lang['list_histology.emb_medblast']='Embryonal (PNET) - medulloblastoma';
Pond_Lang['list_histology.emb_atyp']='Embryonal (PNET) - atypical teratoid/rhabdoid tumor';
Pond_Lang['list_histology.sellar_cranio']='Sellar Region - Craniopharyngioma - Pituitaria Adenoma or Carcinoma';
Pond_Lang['list_histology.hemangioblast']='Hemangioblastoma';
Pond_Lang['list_histology.chordoma']='Chordoma';
Pond_Lang['list_histology.mening_nos']='Meningioma';
Pond_Lang['list_histology.mening_heman']='Meningeal Hemangiopericytoma';
Pond_Lang['list_histology.mening_mening']='Meningeal Meningioangiomatosis';
Pond_Lang['list_histology.langer_cell']='Langerhans Cell Histiocytosis';
Pond_Lang['list_histology.malig_hist']='Malignant Histiocytosis';
Pond_Lang['list_histology.hemoph_synd']='Hemophagocytic Syndromes';
Pond_Lang['list_histology.mening_mal_melano']='Meningeal Malignant Melanoma';
Pond_Lang['list_histology.mening_melanocy']='Meningeal Melanocytoma';
Pond_Lang['list_histology.mening_melanomat']='Meningeal Melanomatosis';
Pond_Lang['list_histology.neuroblastoma']='Neuroblastoma';
Pond_Lang['list_histology.ganglioneuroblastoma']='Ganglioneuroblastoma';
Pond_Lang['list_histology.ganglioneuma']='Ganglioneuroma';
Pond_Lang['list_histology.nasophar_carcin']='Nasopharyngeal Carcinoma';
Pond_Lang['list_histology.colon_carcin']='Colon Carcinoma';
Pond_Lang['list_histology.breast_carcin']='Breast carcinoma';
Pond_Lang['list_histology.ovarian_carcin']='Ovarian Carcinoma';
Pond_Lang['list_histology.t_lineage']='T-Lineage ALL';
Pond_Lang['list_histology.b_lineage']='B-lineage ALL';
Pond_Lang['list_histology.undiff_rhab']='Undifferentiated Rhabdomyosarcoma';
Pond_Lang['list_histology.neurofib_mal_schwan']='Neurofibrosarcoma - Malignant Schwannomas';
Pond_Lang['list_histology.liposarcoma']='Liposarcoma';
Pond_Lang['list_histology.conventional']='Conventional';
Pond_Lang['list_histology.multifocal']='Multifocal';
Pond_Lang['list_histology.pri_osteo_jaw']='Primary osteosarcoma of the jaw';
Pond_Lang['list_histology.extra_osteo']='Extraosseous Osteosarcoma';
Pond_Lang['list_histology.astro_juv_pilo_w1']='Astrocytic-juvenile pilocytic astrocytoma (WHO I)';
Pond_Lang['list_histology.astro_fib_astrocy']='Astrocytic-fibrillary astrocytoma';
Pond_Lang['list_histology.astro_fib_astrobl_w2']='Astrocytic-fibrillary astroblastoma (WHO II)';
Pond_Lang['list_histology.sellar_pituit']='Sellar Region- Pituitaria Ademonoma or Carcinoma';
Pond_Lang['list_histology.ben_mat_tera_gona']='Benign - mature teratoma - gonadoblastoma';
Pond_Lang['list_histology.ben_gona']='Benign - gonadoblastoma';
Pond_Lang['list_histology.ind_behav_imm_tera']='Indeterminate Behavior - Immature Teratoma';
Pond_Lang['list_histology.mal_germ_sem']='Malignant - Geminoma - Seminoma (Males)';
Pond_Lang['list_histology.mal_germ_dys']='Malignant - Geminoma - Dysgerminoma (Females)';
Pond_Lang['list_histology.yolk']='Yolk Sac Carcinoma (Endodermal Sinus Tumor)';
Pond_Lang['list_histology.emb_carc']='Embryonal carcinoma';
Pond_Lang['list_histology.chorio']='Choriocarcinoma';
Pond_Lang['list_histology.mix_mal_germ']='Mixed Malignant Germ Cell Tumor - Mature or Immature Teratoma';
Pond_Lang['list_histology.juv_chron_myel_leuk']='Juvenile Chronic Myelocytic Leukemia';
Pond_Lang['list_histology.anap']='Anaplastic';
Pond_Lang['list_histology.fibrolamellar']='Fibrolamellar';
Pond_Lang['list_histology.fibrolamellar_non']='Non-Fibrolamellar';
Pond_Lang['list_histology.unknown']='No data';
Pond_Lang['list_histology.fetal']='Fetal';
Pond_Lang['list_histology.undifferentiated']='Undifferentiated';
Pond_Lang['list_histology.mixed']='Mixed';
Pond_Lang['list_histology.ganglioneuroma']='Ganglioneuroma';
Pond_Lang['list_histology.non_anap_lymp']='Large cell lymphoma, non B-cell, non-anaplastic';
Pond_Lang['list_histology.carc_adrenocort']='Adrenocortical carcinoma';
Pond_Lang['list_histology.carc_skin']='Skin Carcinoma';
Pond_Lang['list_histology.carc_melanoma']='Melanoma';
Pond_Lang['list_histology.carc_basal']='Basal cell carcinoma';
Pond_Lang['list_histology.carc_thy_follic']='Follicular';
Pond_Lang['list_histology.carc_thy_pap']='Papillary';
Pond_Lang['list_histology.carc_thy_med']='Medullary';
Pond_Lang['list_histology.carc_other']='Other unspecified carcinomas';
Pond_Lang['list_histology.leuk_juv_mmc']='Juvenile myelomonocytic leukemia';
Pond_Lang['list_histology.leuk_nos']='Leukemia, not specified';
Pond_Lang['list_histology.hod_nos']='Hodgkin lymphoma, not specified';
Pond_Lang['list_histology.sarc_soft_other']='Soft tissue sarcoma';
Pond_Lang['list_histology.sarc_soft_nos']='Soft tissue sarcoma, not otherwise specified';
Pond_Lang['list_histology.sarc_soft_chondro']='Chondrosarcoma';
Pond_Lang['list_histology.gliomas_other']='Gliomas, other';
Pond_Lang['list_histology.neoplas_other']='Other intracranial or intraspinal neoplasms';
Pond_Lang['list_histology.mal_germ_xgonad']='Extragonadal germ cell tumor';
Pond_Lang['list_histology.carc_gonad']='Gonadal carcinoma';
Pond_Lang['list_histology.neural_tumor']='Neural tumor';
Pond_Lang['list_histology.lympho_lymp_b']='Lymphoblastic lymphoma, B-lineage';
Pond_Lang['list_histology.lympho_lymp_t']='Lymphoblastic lymphoma, T-lineage';
Pond_Lang['list_histology.lympho_lymp_nk']='Nasopharyngeal NK/T cell lymphoma';
Pond_Lang['list_histology.sarc_soft_clearcell']='Soft tissue sarcoma, clear cell';
Pond_Lang['list_histology.sarc_soft_nervesheath']='Malignant peripheral nerve sheath tumor';
Pond_Lang['list_histology.non_rhab_schwanoma']='Malignant schwannoma';
Pond_Lang['list_histology.ewing_neuroect']='Neuroectodermal tumor';
Pond_Lang['list_histology.cns_gbm']='Glioblastoma multiforme';
Pond_Lang['list_histology.cns_glioma_optic_nerve']='Optic nerve glioma';
Pond_Lang['list_histology.cns_glioma_brainstem']='Brainstem glioma';
Pond_Lang['list_histology.cns_spinalcord']='Spinal cord tumor';
Pond_Lang['list_histology.cns_teratoma']='CNS teratoma';
Pond_Lang['list_histology.cns_gct']='CNS germ cell tumor';
Pond_Lang['list_histology.cns_pineal']='Pineal tumor';
Pond_Lang['list_histology.osteo_nos']='Osteosarcoma, NOS';
Pond_Lang['list_histology.renal_nos']='Renal tumor, NOS';
Pond_Lang['list_histology.cns_nos']='CNS, NOS';
Pond_Lang['list_histology.malignant_rhabdoid_tumour_of_sof']='Malignant Rhabdoid Tumour of Soft Tissues';
Pond_Lang['list_histology.desmoplastic_small_round_cell_tu']='Desmoplastic Small Round Cell Tumour';
Pond_Lang['list_histology.congenital_infantile_fibrosarcom']='Congenital Infantile Fibrosarcoma';
Pond_Lang['list_histology.fibroblastic-myofibroblastic_pro']='Fibroblastic-Myofibroblastic Proliferations of Childhood';
Pond_Lang['list_histology.inflammatory_myofibroblastic_tum']='Inflammatory Myofibroblastic Tumour';
Pond_Lang['list_histology.desmoid-type_fibromatosis']='Desmoid-Type Fibromatosis';
Pond_Lang['list_histology.pilomyxoid_astro']='Pilomyxoid Astrocytoma';
Pond_Lang['list_histology.atypical_papilloma']='Atypical choroid plexus papilloma';
Pond_Lang['list_histology.ganglioma']='Ganglioma';
Pond_Lang['list_histology.pineal_parenchymal']='Pineal parenchymal tumor';
Pond_Lang['list_histology.medullo_desmoplastic']='Desmoplastic medulloblastoma';
Pond_Lang['list_histology.medullo_nodular']='Medulloblastoma with extensive nodularity';
Pond_Lang['list_histology.medullo_anaplastic']='Anaplastic medulloblastoma';
Pond_Lang['list_histology.medullo_large_cell']='Large cell medulloblastoma';
Pond_Lang['list_histology.cns_germinoma']='Central nervous system - germinoma';
Pond_Lang['list_histology.cns_embryo']='Central nervous system - embryonal carcinoma';
Pond_Lang['list_histology.cns_yolk_sac']='Central nervous system - yolk sac tumor';
Pond_Lang['list_histology.cns_choriocarcinoma']='Central nervous system - choriocarcinoma';
Pond_Lang['list_histology.cns_germ_cell']='Central nervous system - mixed germ cell tumor';
Pond_Lang['list_histology.merkel_cell_carcinoma']='Merkel Cell Carcinoma';
Pond_Lang['list_disease_name.all']='ALL (Acute leukemia)';
Pond_Lang['list_disease_name.aml']='AML (except APL)';
Pond_Lang['list_disease_name.apl']='Acute promyelocytic leukemia';
Pond_Lang['list_disease_name.cns']='CNS Cancer';
Pond_Lang['list_disease_name.ewing']='Ewing sarcoma';
Pond_Lang['list_disease_name.hblast']='Hepatoblastoma';
Pond_Lang['list_disease_name.hcellcarcinoma']='Hepatocellular carcinoma';
Pond_Lang['list_disease_name.hod']='Hodgkin lymphoma';
Pond_Lang['list_disease_name.nblast']='Neuroblastoma';
Pond_Lang['list_disease_name.non_cns']='Germ cell tumor (non-CNS)';
Pond_Lang['list_disease_name.non_hod']='Non-Hodgkin lymphoma';
Pond_Lang['list_disease_name.non_rhab']='Non-rhabdomyo sarcoma';
Pond_Lang['list_disease_name.non_wilms']='Non-Wilms renal cancer';
Pond_Lang['list_disease_name.osteo']='Osteosarcoma';
Pond_Lang['list_disease_name.leuk_other']='Leukemia - other';
Pond_Lang['list_disease_name.rblast']='Retinoblastoma';
Pond_Lang['list_disease_name.rhab']='Rhabdomyosarcoma';
Pond_Lang['list_disease_name.wilms']='Wilms tumor';
Pond_Lang['list_disease_name.histiocytic']='Histiocytic tumor';
Pond_Lang['list_disease_name.carcino']='Carcinoma';
Pond_Lang['list_disease_name.other']='Other cancer';
Pond_Lang['list_disease_name.cml']='CML (Chronic myeloid leukemia)';
Pond_Lang['list_disease_name.skin_cancer']='Skin cancer';
Pond_Lang['list_disease_name.carc_thyroid']='Thyroid carcinoma';
Pond_Lang['list_disease_name.neoplas_malig_unspec']='Unspecified malignant neoplasms';
Pond_Lang['list_disease_name.carc_parotid']='Parotid carcinoma';
Pond_Lang['list_disease_name.mds']='Myelodysplasia';
Pond_Lang['list_disease_name.mps']='Myeloproliferative syndrome';
Pond_Lang['list_disease_name.lymphoma_nos']='Lymphoma, NOS';
Pond_Lang['list_disease_name.gist']='Gastrointestinal stromal tumor';
Pond_Lang['list_disease_name.anemia_aplast']='Aplastic anemia';
Pond_Lang['list_disease_name.thalassemia']='Thalassemia';
Pond_Lang['list_disease_name.anemia_sicklecell']='Sickle cell anemia';
Pond_Lang['list_disease_name.anemia_fanconi']='Fanconi anemia';
Pond_Lang['list_disease_name.other_disease']='Other disease';
Pond_Lang['list_disease_name.no_diagnosis']='No diagnosis';
Pond_Lang['list_disease_name.itp']='Immune thrombocytopenic purpura (ITP)';
Pond_Lang['list_disease_name.hemophilia']='Hemophilia';
Pond_Lang['list_disease_name.lymphaden_benign']='Lymphadenopathy, benign';
Pond_Lang['list_disease_name.hemangioma']='Hemangioma';
Pond_Lang['list_disease_name.anemia']='Anemia, iron deficiency';
Pond_Lang['list_disease_name.mesoblastic_nephroma']='Mesoblastic nephroma';
Pond_Lang['list_disease_name.teratoma_benign']='Teratoma, benign';
Pond_Lang['list_disease_name.anemia_hemolytic']='Anemia, hemolytic';
Pond_Lang['list_disease_name.anemia_megaloblastic']='Anemia, megaloblastic';
Pond_Lang['list_disease_name.anemia_other']='Anemia, other';
Pond_Lang['list_disease_name.bleeding_disorder_ns']='Bleeding disorder, not specified';
Pond_Lang['list_disease_name.g6pd_deficiency']='G6PD deficiency';
Pond_Lang['list_disease_name.hyper_gammaglobulinemia']='Hyper gammaglobulinemia';
Pond_Lang['list_disease_name.neutropenia_ns']='Neutropenia, not specified';
Pond_Lang['list_disease_name.pancytopenia']='Pancytopenia';
Pond_Lang['list_disease_name.platelet_function_disorder']='Platelet function disorder';
Pond_Lang['list_disease_name.thrombocytopenia_other']='Thrombocytopenia, other';
Pond_Lang['list_disease_name.thrombocytosis']='Thrombocytosis';
Pond_Lang['list_disease_name.medulloblastoma']='Medulloblastoma';
Pond_Lang['form_control_comments']='Comments (reasons for marking form for review) (leave blank to unmark)';
Pond_Lang['form_control_confirm_delete_form']='This will delete this form, and remove it and all associated data from POND entirely. THIS ACTION IS PERMANENT AND IRREVERSIBLE.';
Pond_Lang['n_a']='n/a';
Pond_Lang['picker_add_new']='ADD NEW';
Pond_Lang['validation_required_lang']='This is a required field.';
Pond_Lang['validate_number_lang']='Please enter a valid number in this field.';
Pond_Lang['validate_digits_lang']='Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.';
Pond_Lang['validate_alpha_lang']='Please use letters only (a-z) in this field.';
Pond_Lang['validate_alphanum_lang']='Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.';
Pond_Lang['validate_date_lang']='Please enter a valid date.';
Pond_Lang['validate_email_lang']='Please enter a valid email address.';
Pond_Lang['validate_url_lang']='Please enter a valid URL.';
Pond_Lang['validate_dateau_lang']='Please use this date format: dd/mm/yyyy';
Pond_Lang['validate_currencydollar_lang']='Please enter a valid $ amount.';
Pond_Lang['validate_selection_lang']='Please make a selection.';
Pond_Lang['validate_onerequired_lang']='Please select one of the above options.';

// vim: set foldmethod=marker:
//

if(typeof(Pond) == "undefined") Pond = {};

Pond.Diagnosis = Class.create();
Object.extend(Pond.Diagnosis.prototype,{

	// {{{ initialize
	// the data definition of the repeating fields
	initialize: function(patient_id)
	{
		//constructor of the pond child class goes here.
		this.patient_id = patient_id;

		// currently editing variables:
		this.patient_diagnosis_id = $('record[patient_diagnosis][default][patient_diagnosis_id]').value;
		this.list_disease_name = $('record[patient_diagnosis][default][list_disease_name]').value;

		// dialog box vars
		this.add_disease_dialog = false;
	},
	// }}}

	// {{{ hook_update
	// this function is called whenever there is an update by the picker tool
	// 
	//		action
	//			if "clear", will clear the default_values array
	hook_update: function(action, data)
	{
		// action "Clear" is called when the disease was deleted.
		if (action == 'clear')
		{
			this.patient_diagnosis_id = "";
			this.list_disease_name = "";
			this.update_diag_table();
			this.hide_everything();
		}

		// don't bother with anything if there are no histologies
		var histObj = $('record[patient_diagnosis][default][list_histology]');
		if (!(histObj == null || histObj == 'record[patient_diagnosis][default][list_histology]'))
		{
			// there is a histology field in this form:

			// make sure disease is defined:
			if (this.list_disease_name != "" && undefined != Pond.disease_specific_histologies[this.list_disease_name])
			{
				$('record[patient_diagnosis][default][list_histology]_nohistmsg').hide();
				$('record[patient_diagnosis][default][list_histology]').show();
				var i=0; var sel=false;
				var current_histology;
				if (data != null )
				{
					current_histology = data.list_histology;
				}
				else
				{
					current_histology = histObj.value;
				}

				// blank the options
				histObj.options.length = 0;
				histObj.options[i++] = new Option('', '');

				// now fill the options
				Pond.disease_specific_histologies[this.list_disease_name].each(function(h){
					histObj.options[i++] = new Option(Pond.Func.translate_listkey('histology',h),h);
				});
				histObj.value = current_histology;
			}
			else
			{
				$('record[patient_diagnosis][default][list_histology]').hide();
				$('record[patient_diagnosis][default][list_histology]_nohistmsg').show();
			}
		}
	},
	//}}}

	// {{{ on_load
	on_load: function()
	{
		//insert after the piecediv...
	  new Insertion.After('piecediv_244', "<div id='after_piecediv_244'>Some initilization html goes here</div>"); 

		$('piecediv_244').up().show();
		$('record[patient_diagnosis][default][list_disease_name]').hide();

		this.update_diag_table();

		// data was already loaded by the quickform (php script), so we just need to toggle the
		// visibility of the pieces that belong to this disease...
		//
		// (perhaps this can be done at php script load time too... (improve JS performance)
		this.toggle_disease_specific_fields();

		// since that data was already loaded, we have to call the hook_update method manually.
		this.hook_update('add',null);
	},
	// }}}

	// {{{ update_diag_table
	update_diag_table: function()
	{
		// create a table in this.div
		// this table will contain all the diseases that this patient has, along with buttons to EDIT and add new disease.
		new Ajax.Updater('after_piecediv_244',http_root+'patient/ajax/diagnosis.php',{
			asynchronous: false,
			parameters: {
				op: 'get_listing',
				patient_diagnosis_id: this.patient_diagnosis_id,
				patient_id: qfwidget_patient_id
			}
		});
	},
	// }}}

	// {{{ add_disease
	add_disease: function()
	{
		// Strategy for adding a disease:
		//
		// First we prompt the user for the disease she wants to add, and the diagnosis date for this disease
		//
		// (diangois date is not required, the disease is required!)
		//
		// We create this record in the patient's db, and then we call "edit_disease" on this record...


		if (this.add_disease_dialog != false)
		{
			this.add_disease_dialog.close();
		}

		this.add_disease_dialog = new Control.Modal(false,{
			height: 140,
			width: 400,
			position: 'absolute',
			opacity: 0.7,
			contents: "<div id='pond_diagnosis_add_disease_dialog'>"+ "</div>"
		});
		this.add_disease_dialog.open();

		new Ajax.Updater('pond_diagnosis_add_disease_dialog',http_root+'patient/ajax/diagnosis.php',{
			asynchronous: false,
			parameters: {
				op: 'add_disease',
				patient_diagnosis_id: this.patient_diagnosis_id,
				patient_id: qfwidget_patient_id
			}
		});
	},
	// }}}

	// {{{ edit_disease
	edit_disease: function(patient_diagnosis_id,list_disease_name)
	{
		// first lets update the id
		this.patient_diagnosis_id = patient_diagnosis_id;
		this.list_disease_name = list_disease_name;

		// show and hide the "edit buttons" beside the disease name...
		this.toggle_edit_buttons();


		// lets now show all the disease specific fields for this disease
		//
		// get the array of all pieces for this disease...

		this.hide_everything();
		this.toggle_disease_specific_fields();

		// call the picker object's edit_record_confirm ().
		if (typeof(picker_obj_patient_diagnosisdefault) !='undefined')
		{
			picker_obj_patient_diagnosisdefault.edit_record(this.patient_diagnosis_id);
		}
	},
	// }}}

	// {{{ handle_add_disease
	handle_add_disease: function()
	{
		// This function will actually handle submitting the add disease request...
		//
		// Also does minor error handling...

		var json_response;
		var list_disease_name = $('add_record[list_disease_name]').value;
		new Ajax.Request(http_root+'patient/ajax/diagnosis.php',{
			asynchronous: false,
			parameters: {
				'op': 'op_add',
				'list_disease_name': list_disease_name,
				'patient_id': qfwidget_patient_id
			},
			onSuccess: function(transport){
				json_response = transport.headerJSON;
				if (transport.headerJSON.success)
				{
				}
				else
				{
					// big problem!
				}
			} 
		});

		if (json_response.success)
		{
			// 1. Close the dialog.
			if (this.add_disease_dialog != false)
			{
				this.add_disease_dialog.close();
			}

			// 2. Update the disease table.
			this.patient_diagnosis_id = json_response.id;
			this.list_disease_name = list_disease_name;
			this.update_diag_table();

			// 3. put the newly added disease in "edit" mode"
			this.edit_disease(this.patient_diagnosis_id,this.list_disease_name);
		}
		else
		{
			//Don't do anything - because the add failed
		}
	},
	// }}}

	// {{{ toggle_edit_buttons
	toggle_edit_buttons: function()
	{
		$$('div[id^=editboxeddiv_]').each(function(e){
			if ( e.id == 'editboxeddiv_'+this.patient_diagnosis_id)
			{
				e.hide();
				e.up('tr').addClassName('active');
				e.next('span').show();
			}
			else
			{
				e.up('tr').removeClassName('active');
				e.next('span').hide();
				e.show();
			}
		}.bind(this));
	},
	// }}}

	// {{{ toggle_disease_specific_fields
	toggle_disease_specific_fields: function()
	{
		if (undefined != Pond.disease_specific_fields[this.list_disease_name])
		{
			var transdname = Pond.Func.translate_listkey('disease_name',this.list_disease_name);
			Pond.disease_specific_fields[this.list_disease_name].each(function(pid){
				var obj = $('piecediv_'+pid);
				if (!(obj == null || obj == 'piecediv_'+pid))
				{
					obj.show();

					var fsobj = obj.up('fieldset');

					if (typeof(fsobj) == "undefined")
					{
						fsobj = obj.up('li');
					}


					if ("undefined" != typeof(fsobj))
					{
						if (!fsobj.visible())
						{
							var legend = obj.previous('legend');

							if (typeof(legend) !='undefined')
							{
								var tmp =legend.innerHTML.split('||');
								if (tmp.length == 1)
								{
									legend.innerHTML += " || Currently editing disease: " + transdname;
								}
								else
								{
									legend.innerHTML = tmp[0] + " || Currently editing disease: " + transdname;
								}
							}

							//obj.up('fieldset').show();
							fsobj.show();
						}
					}
				}
				else
				{
					// pid doesnt exists
				}
			});
		}
	},
	// }}}

	// {{{ hide_everything
	hide_everything: function()
	{
		// hide all the groups now (except for the disease group)
		$$('fieldset[id^=groupfieldset_9]').each(function(e){
			// should not hide the main div
			if (e.id != 'groupfieldset_9_patient_diagnosis_disease') { e.hide(); }
		});

		$$('fieldset[id^=piecediv_]').each(function(e){
			e.hide();
		});
	}
	// }}}

});


// vim: set foldmethod=marker:
if(typeof(Pond) == "undefined") Pond = {};
Pond.Medication = Class.create();
Object.extend(Pond.Medication,{
	// {{{ validate_daterange
	validate_daterange: function()
	{
		var passed = true;
		var frm = MM_findObj('meds_form');
		if ($('patient_treatmentmedsdefaul_multientry_ckbox').checked)
		{
			start = $("record[patient_treatmentmeds][default][event_date]");
			end = $("patient_treatmentmedsdefaul_multientry_enddate_input");

			if (end.value != '')
			{
				yr = start.value.substr(0,4);
				mo = start.value.substr(5,2);
				dt = start.value.substr(8,2);
				date_first = new Date(yr,mo - 1,dt);

				yr = end.value.substr(0,4);
				mo = end.value.substr(5,2);
				dt = end.value.substr(8,2);
				date_end = new Date(yr,mo - 1,dt);

				diff_days = (date_end - date_first) / (1000 * 24 * 60 * 60); // convert to number of days

				if (diff_days <= 0)
				{
					passed = false;
				}
				if (diff_days > 50)
				{
					//return confirm("<?php tpl_lang('confirm_meds_diff_days_high') ?>");
				}
			}
		}
		return passed;
	}
	// }}}
});


// --
// @Copyright (c) 2003-2004 St. Jude Children's Research Hospital, except as noted.
// --

var lang_translations = new Object();
lang_translations.form_control_really_confirm_delete_form = "This will delete this form, and remove it and all associated data from POND entirely. THIS ACTION IS PERMANENT AND IRREVERSIBLE.  Proceed?";
lang_translations.form_control_really_confirm_delete_patient = "This will delete this patient, and remove it and all associated data from POND entirely. THIS ACTION IS PERMANENT AND IRREVERSIBLE.  Proceed?";
lang_translations.sure_its_not_dupe = "Are you certain these patients are not duplicates?";
lang_translations.click_to_expand = "Click here to expand";
lang_translations.click_to_collapse = "Click here to collapse";


/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},

	'min-pond' : function(v,elm,opt) {
		if (v == -99) return true;
		return (v >= parseFloat(opt));
	},
	'max-pond' : function(v,elm,opt) {
		if (v == -99) return true;
		return (v <= parseFloat(opt));
	},

	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', Pond_Lang['validation_required_lang'], function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', Pond_Lang['validate_number_lang'], function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', Pond_Lang['validate_digits_lang'], function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', Pond_Lang['validate_alpha_lang'], function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', Pond_Lang['validate_alphanum_lang'], function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', Pond_Lang['validate_date_lang'], function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', Pond_Lang['validate_email_lang'], function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', Pond_Lang['validate_url_lang'], function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', Pond_Lang['validate_dateau_lang'], function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', Pond_Lang['validate_currencydollar_lang'], function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', Pond_Lang['validate_selection_lang'], function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', Pond_Lang['validate_onerequired_lang'], function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);
